trace-event-python.c 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784
  1. /*
  2. * trace-event-python. Feed trace events to an embedded Python interpreter.
  3. *
  4. * Copyright (C) 2010 Tom Zanussi <tzanussi@gmail.com>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. *
  20. */
  21. #include <Python.h>
  22. #include <inttypes.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <stdbool.h>
  27. #include <errno.h>
  28. #include <linux/bitmap.h>
  29. #include <linux/compiler.h>
  30. #include <linux/time64.h>
  31. #include "../../perf.h"
  32. #include "../debug.h"
  33. #include "../callchain.h"
  34. #include "../evsel.h"
  35. #include "../util.h"
  36. #include "../event.h"
  37. #include "../thread.h"
  38. #include "../comm.h"
  39. #include "../machine.h"
  40. #include "../db-export.h"
  41. #include "../thread-stack.h"
  42. #include "../trace-event.h"
  43. #include "../call-path.h"
  44. #include "thread_map.h"
  45. #include "cpumap.h"
  46. #include "print_binary.h"
  47. #include "stat.h"
  48. #include "mem-events.h"
  49. #if PY_MAJOR_VERSION < 3
  50. #define _PyUnicode_FromString(arg) \
  51. PyString_FromString(arg)
  52. #define _PyUnicode_FromStringAndSize(arg1, arg2) \
  53. PyString_FromStringAndSize((arg1), (arg2))
  54. #define _PyBytes_FromStringAndSize(arg1, arg2) \
  55. PyString_FromStringAndSize((arg1), (arg2))
  56. #define _PyLong_FromLong(arg) \
  57. PyInt_FromLong(arg)
  58. #define _PyLong_AsLong(arg) \
  59. PyInt_AsLong(arg)
  60. #define _PyCapsule_New(arg1, arg2, arg3) \
  61. PyCObject_FromVoidPtr((arg1), (arg2))
  62. PyMODINIT_FUNC initperf_trace_context(void);
  63. #else
  64. #define _PyUnicode_FromString(arg) \
  65. PyUnicode_FromString(arg)
  66. #define _PyUnicode_FromStringAndSize(arg1, arg2) \
  67. PyUnicode_FromStringAndSize((arg1), (arg2))
  68. #define _PyBytes_FromStringAndSize(arg1, arg2) \
  69. PyBytes_FromStringAndSize((arg1), (arg2))
  70. #define _PyLong_FromLong(arg) \
  71. PyLong_FromLong(arg)
  72. #define _PyLong_AsLong(arg) \
  73. PyLong_AsLong(arg)
  74. #define _PyCapsule_New(arg1, arg2, arg3) \
  75. PyCapsule_New((arg1), (arg2), (arg3))
  76. PyMODINIT_FUNC PyInit_perf_trace_context(void);
  77. #endif
  78. #define TRACE_EVENT_TYPE_MAX \
  79. ((1 << (sizeof(unsigned short) * 8)) - 1)
  80. static DECLARE_BITMAP(events_defined, TRACE_EVENT_TYPE_MAX);
  81. #define MAX_FIELDS 64
  82. #define N_COMMON_FIELDS 7
  83. extern struct scripting_context *scripting_context;
  84. static char *cur_field_name;
  85. static int zero_flag_atom;
  86. static PyObject *main_module, *main_dict;
  87. struct tables {
  88. struct db_export dbe;
  89. PyObject *evsel_handler;
  90. PyObject *machine_handler;
  91. PyObject *thread_handler;
  92. PyObject *comm_handler;
  93. PyObject *comm_thread_handler;
  94. PyObject *dso_handler;
  95. PyObject *symbol_handler;
  96. PyObject *branch_type_handler;
  97. PyObject *sample_handler;
  98. PyObject *call_path_handler;
  99. PyObject *call_return_handler;
  100. bool db_export_mode;
  101. };
  102. static struct tables tables_global;
  103. static void handler_call_die(const char *handler_name) __noreturn;
  104. static void handler_call_die(const char *handler_name)
  105. {
  106. PyErr_Print();
  107. Py_FatalError("problem in Python trace event handler");
  108. // Py_FatalError does not return
  109. // but we have to make the compiler happy
  110. abort();
  111. }
  112. /*
  113. * Insert val into into the dictionary and decrement the reference counter.
  114. * This is necessary for dictionaries since PyDict_SetItemString() does not
  115. * steal a reference, as opposed to PyTuple_SetItem().
  116. */
  117. static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
  118. {
  119. PyDict_SetItemString(dict, key, val);
  120. Py_DECREF(val);
  121. }
  122. static PyObject *get_handler(const char *handler_name)
  123. {
  124. PyObject *handler;
  125. handler = PyDict_GetItemString(main_dict, handler_name);
  126. if (handler && !PyCallable_Check(handler))
  127. return NULL;
  128. return handler;
  129. }
  130. static int get_argument_count(PyObject *handler)
  131. {
  132. int arg_count = 0;
  133. /*
  134. * The attribute for the code object is func_code in Python 2,
  135. * whereas it is __code__ in Python 3.0+.
  136. */
  137. PyObject *code_obj = PyObject_GetAttrString(handler,
  138. "func_code");
  139. if (PyErr_Occurred()) {
  140. PyErr_Clear();
  141. code_obj = PyObject_GetAttrString(handler,
  142. "__code__");
  143. }
  144. PyErr_Clear();
  145. if (code_obj) {
  146. PyObject *arg_count_obj = PyObject_GetAttrString(code_obj,
  147. "co_argcount");
  148. if (arg_count_obj) {
  149. arg_count = (int) _PyLong_AsLong(arg_count_obj);
  150. Py_DECREF(arg_count_obj);
  151. }
  152. Py_DECREF(code_obj);
  153. }
  154. return arg_count;
  155. }
  156. static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
  157. {
  158. PyObject *retval;
  159. retval = PyObject_CallObject(handler, args);
  160. if (retval == NULL)
  161. handler_call_die(die_msg);
  162. Py_DECREF(retval);
  163. }
  164. static void try_call_object(const char *handler_name, PyObject *args)
  165. {
  166. PyObject *handler;
  167. handler = get_handler(handler_name);
  168. if (handler)
  169. call_object(handler, args, handler_name);
  170. }
  171. static void define_value(enum print_arg_type field_type,
  172. const char *ev_name,
  173. const char *field_name,
  174. const char *field_value,
  175. const char *field_str)
  176. {
  177. const char *handler_name = "define_flag_value";
  178. PyObject *t;
  179. unsigned long long value;
  180. unsigned n = 0;
  181. if (field_type == PRINT_SYMBOL)
  182. handler_name = "define_symbolic_value";
  183. t = PyTuple_New(4);
  184. if (!t)
  185. Py_FatalError("couldn't create Python tuple");
  186. value = eval_flag(field_value);
  187. PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
  188. PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
  189. PyTuple_SetItem(t, n++, _PyLong_FromLong(value));
  190. PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_str));
  191. try_call_object(handler_name, t);
  192. Py_DECREF(t);
  193. }
  194. static void define_values(enum print_arg_type field_type,
  195. struct print_flag_sym *field,
  196. const char *ev_name,
  197. const char *field_name)
  198. {
  199. define_value(field_type, ev_name, field_name, field->value,
  200. field->str);
  201. if (field->next)
  202. define_values(field_type, field->next, ev_name, field_name);
  203. }
  204. static void define_field(enum print_arg_type field_type,
  205. const char *ev_name,
  206. const char *field_name,
  207. const char *delim)
  208. {
  209. const char *handler_name = "define_flag_field";
  210. PyObject *t;
  211. unsigned n = 0;
  212. if (field_type == PRINT_SYMBOL)
  213. handler_name = "define_symbolic_field";
  214. if (field_type == PRINT_FLAGS)
  215. t = PyTuple_New(3);
  216. else
  217. t = PyTuple_New(2);
  218. if (!t)
  219. Py_FatalError("couldn't create Python tuple");
  220. PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
  221. PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
  222. if (field_type == PRINT_FLAGS)
  223. PyTuple_SetItem(t, n++, _PyUnicode_FromString(delim));
  224. try_call_object(handler_name, t);
  225. Py_DECREF(t);
  226. }
  227. static void define_event_symbols(struct event_format *event,
  228. const char *ev_name,
  229. struct print_arg *args)
  230. {
  231. if (args == NULL)
  232. return;
  233. switch (args->type) {
  234. case PRINT_NULL:
  235. break;
  236. case PRINT_ATOM:
  237. define_value(PRINT_FLAGS, ev_name, cur_field_name, "0",
  238. args->atom.atom);
  239. zero_flag_atom = 0;
  240. break;
  241. case PRINT_FIELD:
  242. free(cur_field_name);
  243. cur_field_name = strdup(args->field.name);
  244. break;
  245. case PRINT_FLAGS:
  246. define_event_symbols(event, ev_name, args->flags.field);
  247. define_field(PRINT_FLAGS, ev_name, cur_field_name,
  248. args->flags.delim);
  249. define_values(PRINT_FLAGS, args->flags.flags, ev_name,
  250. cur_field_name);
  251. break;
  252. case PRINT_SYMBOL:
  253. define_event_symbols(event, ev_name, args->symbol.field);
  254. define_field(PRINT_SYMBOL, ev_name, cur_field_name, NULL);
  255. define_values(PRINT_SYMBOL, args->symbol.symbols, ev_name,
  256. cur_field_name);
  257. break;
  258. case PRINT_HEX:
  259. case PRINT_HEX_STR:
  260. define_event_symbols(event, ev_name, args->hex.field);
  261. define_event_symbols(event, ev_name, args->hex.size);
  262. break;
  263. case PRINT_INT_ARRAY:
  264. define_event_symbols(event, ev_name, args->int_array.field);
  265. define_event_symbols(event, ev_name, args->int_array.count);
  266. define_event_symbols(event, ev_name, args->int_array.el_size);
  267. break;
  268. case PRINT_STRING:
  269. break;
  270. case PRINT_TYPE:
  271. define_event_symbols(event, ev_name, args->typecast.item);
  272. break;
  273. case PRINT_OP:
  274. if (strcmp(args->op.op, ":") == 0)
  275. zero_flag_atom = 1;
  276. define_event_symbols(event, ev_name, args->op.left);
  277. define_event_symbols(event, ev_name, args->op.right);
  278. break;
  279. default:
  280. /* gcc warns for these? */
  281. case PRINT_BSTRING:
  282. case PRINT_DYNAMIC_ARRAY:
  283. case PRINT_DYNAMIC_ARRAY_LEN:
  284. case PRINT_FUNC:
  285. case PRINT_BITMASK:
  286. /* we should warn... */
  287. return;
  288. }
  289. if (args->next)
  290. define_event_symbols(event, ev_name, args->next);
  291. }
  292. static PyObject *get_field_numeric_entry(struct event_format *event,
  293. struct format_field *field, void *data)
  294. {
  295. bool is_array = field->flags & FIELD_IS_ARRAY;
  296. PyObject *obj = NULL, *list = NULL;
  297. unsigned long long val;
  298. unsigned int item_size, n_items, i;
  299. if (is_array) {
  300. list = PyList_New(field->arraylen);
  301. item_size = field->size / field->arraylen;
  302. n_items = field->arraylen;
  303. } else {
  304. item_size = field->size;
  305. n_items = 1;
  306. }
  307. for (i = 0; i < n_items; i++) {
  308. val = read_size(event, data + field->offset + i * item_size,
  309. item_size);
  310. if (field->flags & FIELD_IS_SIGNED) {
  311. if ((long long)val >= LONG_MIN &&
  312. (long long)val <= LONG_MAX)
  313. obj = _PyLong_FromLong(val);
  314. else
  315. obj = PyLong_FromLongLong(val);
  316. } else {
  317. if (val <= LONG_MAX)
  318. obj = _PyLong_FromLong(val);
  319. else
  320. obj = PyLong_FromUnsignedLongLong(val);
  321. }
  322. if (is_array)
  323. PyList_SET_ITEM(list, i, obj);
  324. }
  325. if (is_array)
  326. obj = list;
  327. return obj;
  328. }
  329. static const char *get_dsoname(struct map *map)
  330. {
  331. const char *dsoname = "[unknown]";
  332. if (map && map->dso) {
  333. if (symbol_conf.show_kernel_path && map->dso->long_name)
  334. dsoname = map->dso->long_name;
  335. else
  336. dsoname = map->dso->name;
  337. }
  338. return dsoname;
  339. }
  340. static PyObject *python_process_callchain(struct perf_sample *sample,
  341. struct perf_evsel *evsel,
  342. struct addr_location *al)
  343. {
  344. PyObject *pylist;
  345. pylist = PyList_New(0);
  346. if (!pylist)
  347. Py_FatalError("couldn't create Python list");
  348. if (!symbol_conf.use_callchain || !sample->callchain)
  349. goto exit;
  350. if (thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
  351. sample, NULL, NULL,
  352. scripting_max_stack) != 0) {
  353. pr_err("Failed to resolve callchain. Skipping\n");
  354. goto exit;
  355. }
  356. callchain_cursor_commit(&callchain_cursor);
  357. while (1) {
  358. PyObject *pyelem;
  359. struct callchain_cursor_node *node;
  360. node = callchain_cursor_current(&callchain_cursor);
  361. if (!node)
  362. break;
  363. pyelem = PyDict_New();
  364. if (!pyelem)
  365. Py_FatalError("couldn't create Python dictionary");
  366. pydict_set_item_string_decref(pyelem, "ip",
  367. PyLong_FromUnsignedLongLong(node->ip));
  368. if (node->sym) {
  369. PyObject *pysym = PyDict_New();
  370. if (!pysym)
  371. Py_FatalError("couldn't create Python dictionary");
  372. pydict_set_item_string_decref(pysym, "start",
  373. PyLong_FromUnsignedLongLong(node->sym->start));
  374. pydict_set_item_string_decref(pysym, "end",
  375. PyLong_FromUnsignedLongLong(node->sym->end));
  376. pydict_set_item_string_decref(pysym, "binding",
  377. _PyLong_FromLong(node->sym->binding));
  378. pydict_set_item_string_decref(pysym, "name",
  379. _PyUnicode_FromStringAndSize(node->sym->name,
  380. node->sym->namelen));
  381. pydict_set_item_string_decref(pyelem, "sym", pysym);
  382. }
  383. if (node->map) {
  384. const char *dsoname = get_dsoname(node->map);
  385. pydict_set_item_string_decref(pyelem, "dso",
  386. _PyUnicode_FromString(dsoname));
  387. }
  388. callchain_cursor_advance(&callchain_cursor);
  389. PyList_Append(pylist, pyelem);
  390. Py_DECREF(pyelem);
  391. }
  392. exit:
  393. return pylist;
  394. }
  395. static PyObject *python_process_brstack(struct perf_sample *sample,
  396. struct thread *thread)
  397. {
  398. struct branch_stack *br = sample->branch_stack;
  399. PyObject *pylist;
  400. u64 i;
  401. pylist = PyList_New(0);
  402. if (!pylist)
  403. Py_FatalError("couldn't create Python list");
  404. if (!(br && br->nr))
  405. goto exit;
  406. for (i = 0; i < br->nr; i++) {
  407. PyObject *pyelem;
  408. struct addr_location al;
  409. const char *dsoname;
  410. pyelem = PyDict_New();
  411. if (!pyelem)
  412. Py_FatalError("couldn't create Python dictionary");
  413. pydict_set_item_string_decref(pyelem, "from",
  414. PyLong_FromUnsignedLongLong(br->entries[i].from));
  415. pydict_set_item_string_decref(pyelem, "to",
  416. PyLong_FromUnsignedLongLong(br->entries[i].to));
  417. pydict_set_item_string_decref(pyelem, "mispred",
  418. PyBool_FromLong(br->entries[i].flags.mispred));
  419. pydict_set_item_string_decref(pyelem, "predicted",
  420. PyBool_FromLong(br->entries[i].flags.predicted));
  421. pydict_set_item_string_decref(pyelem, "in_tx",
  422. PyBool_FromLong(br->entries[i].flags.in_tx));
  423. pydict_set_item_string_decref(pyelem, "abort",
  424. PyBool_FromLong(br->entries[i].flags.abort));
  425. pydict_set_item_string_decref(pyelem, "cycles",
  426. PyLong_FromUnsignedLongLong(br->entries[i].flags.cycles));
  427. thread__find_map_fb(thread, sample->cpumode,
  428. br->entries[i].from, &al);
  429. dsoname = get_dsoname(al.map);
  430. pydict_set_item_string_decref(pyelem, "from_dsoname",
  431. _PyUnicode_FromString(dsoname));
  432. thread__find_map_fb(thread, sample->cpumode,
  433. br->entries[i].to, &al);
  434. dsoname = get_dsoname(al.map);
  435. pydict_set_item_string_decref(pyelem, "to_dsoname",
  436. _PyUnicode_FromString(dsoname));
  437. PyList_Append(pylist, pyelem);
  438. Py_DECREF(pyelem);
  439. }
  440. exit:
  441. return pylist;
  442. }
  443. static unsigned long get_offset(struct symbol *sym, struct addr_location *al)
  444. {
  445. unsigned long offset;
  446. if (al->addr < sym->end)
  447. offset = al->addr - sym->start;
  448. else
  449. offset = al->addr - al->map->start - sym->start;
  450. return offset;
  451. }
  452. static int get_symoff(struct symbol *sym, struct addr_location *al,
  453. bool print_off, char *bf, int size)
  454. {
  455. unsigned long offset;
  456. if (!sym || !sym->name[0])
  457. return scnprintf(bf, size, "%s", "[unknown]");
  458. if (!print_off)
  459. return scnprintf(bf, size, "%s", sym->name);
  460. offset = get_offset(sym, al);
  461. return scnprintf(bf, size, "%s+0x%x", sym->name, offset);
  462. }
  463. static int get_br_mspred(struct branch_flags *flags, char *bf, int size)
  464. {
  465. if (!flags->mispred && !flags->predicted)
  466. return scnprintf(bf, size, "%s", "-");
  467. if (flags->mispred)
  468. return scnprintf(bf, size, "%s", "M");
  469. return scnprintf(bf, size, "%s", "P");
  470. }
  471. static PyObject *python_process_brstacksym(struct perf_sample *sample,
  472. struct thread *thread)
  473. {
  474. struct branch_stack *br = sample->branch_stack;
  475. PyObject *pylist;
  476. u64 i;
  477. char bf[512];
  478. struct addr_location al;
  479. pylist = PyList_New(0);
  480. if (!pylist)
  481. Py_FatalError("couldn't create Python list");
  482. if (!(br && br->nr))
  483. goto exit;
  484. for (i = 0; i < br->nr; i++) {
  485. PyObject *pyelem;
  486. pyelem = PyDict_New();
  487. if (!pyelem)
  488. Py_FatalError("couldn't create Python dictionary");
  489. thread__find_symbol_fb(thread, sample->cpumode,
  490. br->entries[i].from, &al);
  491. get_symoff(al.sym, &al, true, bf, sizeof(bf));
  492. pydict_set_item_string_decref(pyelem, "from",
  493. _PyUnicode_FromString(bf));
  494. thread__find_symbol_fb(thread, sample->cpumode,
  495. br->entries[i].to, &al);
  496. get_symoff(al.sym, &al, true, bf, sizeof(bf));
  497. pydict_set_item_string_decref(pyelem, "to",
  498. _PyUnicode_FromString(bf));
  499. get_br_mspred(&br->entries[i].flags, bf, sizeof(bf));
  500. pydict_set_item_string_decref(pyelem, "pred",
  501. _PyUnicode_FromString(bf));
  502. if (br->entries[i].flags.in_tx) {
  503. pydict_set_item_string_decref(pyelem, "in_tx",
  504. _PyUnicode_FromString("X"));
  505. } else {
  506. pydict_set_item_string_decref(pyelem, "in_tx",
  507. _PyUnicode_FromString("-"));
  508. }
  509. if (br->entries[i].flags.abort) {
  510. pydict_set_item_string_decref(pyelem, "abort",
  511. _PyUnicode_FromString("A"));
  512. } else {
  513. pydict_set_item_string_decref(pyelem, "abort",
  514. _PyUnicode_FromString("-"));
  515. }
  516. PyList_Append(pylist, pyelem);
  517. Py_DECREF(pyelem);
  518. }
  519. exit:
  520. return pylist;
  521. }
  522. static PyObject *get_sample_value_as_tuple(struct sample_read_value *value)
  523. {
  524. PyObject *t;
  525. t = PyTuple_New(2);
  526. if (!t)
  527. Py_FatalError("couldn't create Python tuple");
  528. PyTuple_SetItem(t, 0, PyLong_FromUnsignedLongLong(value->id));
  529. PyTuple_SetItem(t, 1, PyLong_FromUnsignedLongLong(value->value));
  530. return t;
  531. }
  532. static void set_sample_read_in_dict(PyObject *dict_sample,
  533. struct perf_sample *sample,
  534. struct perf_evsel *evsel)
  535. {
  536. u64 read_format = evsel->attr.read_format;
  537. PyObject *values;
  538. unsigned int i;
  539. if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
  540. pydict_set_item_string_decref(dict_sample, "time_enabled",
  541. PyLong_FromUnsignedLongLong(sample->read.time_enabled));
  542. }
  543. if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
  544. pydict_set_item_string_decref(dict_sample, "time_running",
  545. PyLong_FromUnsignedLongLong(sample->read.time_running));
  546. }
  547. if (read_format & PERF_FORMAT_GROUP)
  548. values = PyList_New(sample->read.group.nr);
  549. else
  550. values = PyList_New(1);
  551. if (!values)
  552. Py_FatalError("couldn't create Python list");
  553. if (read_format & PERF_FORMAT_GROUP) {
  554. for (i = 0; i < sample->read.group.nr; i++) {
  555. PyObject *t = get_sample_value_as_tuple(&sample->read.group.values[i]);
  556. PyList_SET_ITEM(values, i, t);
  557. }
  558. } else {
  559. PyObject *t = get_sample_value_as_tuple(&sample->read.one);
  560. PyList_SET_ITEM(values, 0, t);
  561. }
  562. pydict_set_item_string_decref(dict_sample, "values", values);
  563. }
  564. static void set_sample_datasrc_in_dict(PyObject *dict,
  565. struct perf_sample *sample)
  566. {
  567. struct mem_info mi = { .data_src.val = sample->data_src };
  568. char decode[100];
  569. pydict_set_item_string_decref(dict, "datasrc",
  570. PyLong_FromUnsignedLongLong(sample->data_src));
  571. perf_script__meminfo_scnprintf(decode, 100, &mi);
  572. pydict_set_item_string_decref(dict, "datasrc_decode",
  573. _PyUnicode_FromString(decode));
  574. }
  575. static int regs_map(struct regs_dump *regs, uint64_t mask, char *bf, int size)
  576. {
  577. unsigned int i = 0, r;
  578. int printed = 0;
  579. bf[0] = 0;
  580. for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
  581. u64 val = regs->regs[i++];
  582. printed += scnprintf(bf + printed, size - printed,
  583. "%5s:0x%" PRIx64 " ",
  584. perf_reg_name(r), val);
  585. }
  586. return printed;
  587. }
  588. static void set_regs_in_dict(PyObject *dict,
  589. struct perf_sample *sample,
  590. struct perf_evsel *evsel)
  591. {
  592. struct perf_event_attr *attr = &evsel->attr;
  593. char bf[512];
  594. regs_map(&sample->intr_regs, attr->sample_regs_intr, bf, sizeof(bf));
  595. pydict_set_item_string_decref(dict, "iregs",
  596. _PyUnicode_FromString(bf));
  597. regs_map(&sample->user_regs, attr->sample_regs_user, bf, sizeof(bf));
  598. pydict_set_item_string_decref(dict, "uregs",
  599. _PyUnicode_FromString(bf));
  600. }
  601. static PyObject *get_perf_sample_dict(struct perf_sample *sample,
  602. struct perf_evsel *evsel,
  603. struct addr_location *al,
  604. PyObject *callchain)
  605. {
  606. PyObject *dict, *dict_sample, *brstack, *brstacksym;
  607. dict = PyDict_New();
  608. if (!dict)
  609. Py_FatalError("couldn't create Python dictionary");
  610. dict_sample = PyDict_New();
  611. if (!dict_sample)
  612. Py_FatalError("couldn't create Python dictionary");
  613. pydict_set_item_string_decref(dict, "ev_name", _PyUnicode_FromString(perf_evsel__name(evsel)));
  614. pydict_set_item_string_decref(dict, "attr", _PyBytes_FromStringAndSize((const char *)&evsel->attr, sizeof(evsel->attr)));
  615. pydict_set_item_string_decref(dict_sample, "pid",
  616. _PyLong_FromLong(sample->pid));
  617. pydict_set_item_string_decref(dict_sample, "tid",
  618. _PyLong_FromLong(sample->tid));
  619. pydict_set_item_string_decref(dict_sample, "cpu",
  620. _PyLong_FromLong(sample->cpu));
  621. pydict_set_item_string_decref(dict_sample, "ip",
  622. PyLong_FromUnsignedLongLong(sample->ip));
  623. pydict_set_item_string_decref(dict_sample, "time",
  624. PyLong_FromUnsignedLongLong(sample->time));
  625. pydict_set_item_string_decref(dict_sample, "period",
  626. PyLong_FromUnsignedLongLong(sample->period));
  627. pydict_set_item_string_decref(dict_sample, "phys_addr",
  628. PyLong_FromUnsignedLongLong(sample->phys_addr));
  629. pydict_set_item_string_decref(dict_sample, "addr",
  630. PyLong_FromUnsignedLongLong(sample->addr));
  631. set_sample_read_in_dict(dict_sample, sample, evsel);
  632. pydict_set_item_string_decref(dict_sample, "weight",
  633. PyLong_FromUnsignedLongLong(sample->weight));
  634. pydict_set_item_string_decref(dict_sample, "transaction",
  635. PyLong_FromUnsignedLongLong(sample->transaction));
  636. set_sample_datasrc_in_dict(dict_sample, sample);
  637. pydict_set_item_string_decref(dict, "sample", dict_sample);
  638. pydict_set_item_string_decref(dict, "raw_buf", _PyBytes_FromStringAndSize(
  639. (const char *)sample->raw_data, sample->raw_size));
  640. pydict_set_item_string_decref(dict, "comm",
  641. _PyUnicode_FromString(thread__comm_str(al->thread)));
  642. if (al->map) {
  643. pydict_set_item_string_decref(dict, "dso",
  644. _PyUnicode_FromString(al->map->dso->name));
  645. }
  646. if (al->sym) {
  647. pydict_set_item_string_decref(dict, "symbol",
  648. _PyUnicode_FromString(al->sym->name));
  649. }
  650. pydict_set_item_string_decref(dict, "callchain", callchain);
  651. brstack = python_process_brstack(sample, al->thread);
  652. pydict_set_item_string_decref(dict, "brstack", brstack);
  653. brstacksym = python_process_brstacksym(sample, al->thread);
  654. pydict_set_item_string_decref(dict, "brstacksym", brstacksym);
  655. set_regs_in_dict(dict, sample, evsel);
  656. return dict;
  657. }
  658. static void python_process_tracepoint(struct perf_sample *sample,
  659. struct perf_evsel *evsel,
  660. struct addr_location *al)
  661. {
  662. struct event_format *event = evsel->tp_format;
  663. PyObject *handler, *context, *t, *obj = NULL, *callchain;
  664. PyObject *dict = NULL, *all_entries_dict = NULL;
  665. static char handler_name[256];
  666. struct format_field *field;
  667. unsigned long s, ns;
  668. unsigned n = 0;
  669. int pid;
  670. int cpu = sample->cpu;
  671. void *data = sample->raw_data;
  672. unsigned long long nsecs = sample->time;
  673. const char *comm = thread__comm_str(al->thread);
  674. const char *default_handler_name = "trace_unhandled";
  675. if (!event) {
  676. snprintf(handler_name, sizeof(handler_name),
  677. "ug! no event found for type %" PRIu64, (u64)evsel->attr.config);
  678. Py_FatalError(handler_name);
  679. }
  680. pid = raw_field_value(event, "common_pid", data);
  681. sprintf(handler_name, "%s__%s", event->system, event->name);
  682. if (!test_and_set_bit(event->id, events_defined))
  683. define_event_symbols(event, handler_name, event->print_fmt.args);
  684. handler = get_handler(handler_name);
  685. if (!handler) {
  686. handler = get_handler(default_handler_name);
  687. if (!handler)
  688. return;
  689. dict = PyDict_New();
  690. if (!dict)
  691. Py_FatalError("couldn't create Python dict");
  692. }
  693. t = PyTuple_New(MAX_FIELDS);
  694. if (!t)
  695. Py_FatalError("couldn't create Python tuple");
  696. s = nsecs / NSEC_PER_SEC;
  697. ns = nsecs - s * NSEC_PER_SEC;
  698. scripting_context->event_data = data;
  699. scripting_context->pevent = evsel->tp_format->pevent;
  700. context = _PyCapsule_New(scripting_context, NULL, NULL);
  701. PyTuple_SetItem(t, n++, _PyUnicode_FromString(handler_name));
  702. PyTuple_SetItem(t, n++, context);
  703. /* ip unwinding */
  704. callchain = python_process_callchain(sample, evsel, al);
  705. /* Need an additional reference for the perf_sample dict */
  706. Py_INCREF(callchain);
  707. if (!dict) {
  708. PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
  709. PyTuple_SetItem(t, n++, _PyLong_FromLong(s));
  710. PyTuple_SetItem(t, n++, _PyLong_FromLong(ns));
  711. PyTuple_SetItem(t, n++, _PyLong_FromLong(pid));
  712. PyTuple_SetItem(t, n++, _PyUnicode_FromString(comm));
  713. PyTuple_SetItem(t, n++, callchain);
  714. } else {
  715. pydict_set_item_string_decref(dict, "common_cpu", _PyLong_FromLong(cpu));
  716. pydict_set_item_string_decref(dict, "common_s", _PyLong_FromLong(s));
  717. pydict_set_item_string_decref(dict, "common_ns", _PyLong_FromLong(ns));
  718. pydict_set_item_string_decref(dict, "common_pid", _PyLong_FromLong(pid));
  719. pydict_set_item_string_decref(dict, "common_comm", _PyUnicode_FromString(comm));
  720. pydict_set_item_string_decref(dict, "common_callchain", callchain);
  721. }
  722. for (field = event->format.fields; field; field = field->next) {
  723. unsigned int offset, len;
  724. unsigned long long val;
  725. if (field->flags & FIELD_IS_ARRAY) {
  726. offset = field->offset;
  727. len = field->size;
  728. if (field->flags & FIELD_IS_DYNAMIC) {
  729. val = tep_read_number(scripting_context->pevent,
  730. data + offset, len);
  731. offset = val;
  732. len = offset >> 16;
  733. offset &= 0xffff;
  734. }
  735. if (field->flags & FIELD_IS_STRING &&
  736. is_printable_array(data + offset, len)) {
  737. obj = _PyUnicode_FromString((char *) data + offset);
  738. } else {
  739. obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
  740. field->flags &= ~FIELD_IS_STRING;
  741. }
  742. } else { /* FIELD_IS_NUMERIC */
  743. obj = get_field_numeric_entry(event, field, data);
  744. }
  745. if (!dict)
  746. PyTuple_SetItem(t, n++, obj);
  747. else
  748. pydict_set_item_string_decref(dict, field->name, obj);
  749. }
  750. if (dict)
  751. PyTuple_SetItem(t, n++, dict);
  752. if (get_argument_count(handler) == (int) n + 1) {
  753. all_entries_dict = get_perf_sample_dict(sample, evsel, al,
  754. callchain);
  755. PyTuple_SetItem(t, n++, all_entries_dict);
  756. } else {
  757. Py_DECREF(callchain);
  758. }
  759. if (_PyTuple_Resize(&t, n) == -1)
  760. Py_FatalError("error resizing Python tuple");
  761. if (!dict)
  762. call_object(handler, t, handler_name);
  763. else
  764. call_object(handler, t, default_handler_name);
  765. Py_DECREF(t);
  766. }
  767. static PyObject *tuple_new(unsigned int sz)
  768. {
  769. PyObject *t;
  770. t = PyTuple_New(sz);
  771. if (!t)
  772. Py_FatalError("couldn't create Python tuple");
  773. return t;
  774. }
  775. static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
  776. {
  777. #if BITS_PER_LONG == 64
  778. return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
  779. #endif
  780. #if BITS_PER_LONG == 32
  781. return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
  782. #endif
  783. }
  784. static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
  785. {
  786. return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
  787. }
  788. static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
  789. {
  790. return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
  791. }
  792. static int python_export_evsel(struct db_export *dbe, struct perf_evsel *evsel)
  793. {
  794. struct tables *tables = container_of(dbe, struct tables, dbe);
  795. PyObject *t;
  796. t = tuple_new(2);
  797. tuple_set_u64(t, 0, evsel->db_id);
  798. tuple_set_string(t, 1, perf_evsel__name(evsel));
  799. call_object(tables->evsel_handler, t, "evsel_table");
  800. Py_DECREF(t);
  801. return 0;
  802. }
  803. static int python_export_machine(struct db_export *dbe,
  804. struct machine *machine)
  805. {
  806. struct tables *tables = container_of(dbe, struct tables, dbe);
  807. PyObject *t;
  808. t = tuple_new(3);
  809. tuple_set_u64(t, 0, machine->db_id);
  810. tuple_set_s32(t, 1, machine->pid);
  811. tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
  812. call_object(tables->machine_handler, t, "machine_table");
  813. Py_DECREF(t);
  814. return 0;
  815. }
  816. static int python_export_thread(struct db_export *dbe, struct thread *thread,
  817. u64 main_thread_db_id, struct machine *machine)
  818. {
  819. struct tables *tables = container_of(dbe, struct tables, dbe);
  820. PyObject *t;
  821. t = tuple_new(5);
  822. tuple_set_u64(t, 0, thread->db_id);
  823. tuple_set_u64(t, 1, machine->db_id);
  824. tuple_set_u64(t, 2, main_thread_db_id);
  825. tuple_set_s32(t, 3, thread->pid_);
  826. tuple_set_s32(t, 4, thread->tid);
  827. call_object(tables->thread_handler, t, "thread_table");
  828. Py_DECREF(t);
  829. return 0;
  830. }
  831. static int python_export_comm(struct db_export *dbe, struct comm *comm)
  832. {
  833. struct tables *tables = container_of(dbe, struct tables, dbe);
  834. PyObject *t;
  835. t = tuple_new(2);
  836. tuple_set_u64(t, 0, comm->db_id);
  837. tuple_set_string(t, 1, comm__str(comm));
  838. call_object(tables->comm_handler, t, "comm_table");
  839. Py_DECREF(t);
  840. return 0;
  841. }
  842. static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
  843. struct comm *comm, struct thread *thread)
  844. {
  845. struct tables *tables = container_of(dbe, struct tables, dbe);
  846. PyObject *t;
  847. t = tuple_new(3);
  848. tuple_set_u64(t, 0, db_id);
  849. tuple_set_u64(t, 1, comm->db_id);
  850. tuple_set_u64(t, 2, thread->db_id);
  851. call_object(tables->comm_thread_handler, t, "comm_thread_table");
  852. Py_DECREF(t);
  853. return 0;
  854. }
  855. static int python_export_dso(struct db_export *dbe, struct dso *dso,
  856. struct machine *machine)
  857. {
  858. struct tables *tables = container_of(dbe, struct tables, dbe);
  859. char sbuild_id[SBUILD_ID_SIZE];
  860. PyObject *t;
  861. build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);
  862. t = tuple_new(5);
  863. tuple_set_u64(t, 0, dso->db_id);
  864. tuple_set_u64(t, 1, machine->db_id);
  865. tuple_set_string(t, 2, dso->short_name);
  866. tuple_set_string(t, 3, dso->long_name);
  867. tuple_set_string(t, 4, sbuild_id);
  868. call_object(tables->dso_handler, t, "dso_table");
  869. Py_DECREF(t);
  870. return 0;
  871. }
  872. static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
  873. struct dso *dso)
  874. {
  875. struct tables *tables = container_of(dbe, struct tables, dbe);
  876. u64 *sym_db_id = symbol__priv(sym);
  877. PyObject *t;
  878. t = tuple_new(6);
  879. tuple_set_u64(t, 0, *sym_db_id);
  880. tuple_set_u64(t, 1, dso->db_id);
  881. tuple_set_u64(t, 2, sym->start);
  882. tuple_set_u64(t, 3, sym->end);
  883. tuple_set_s32(t, 4, sym->binding);
  884. tuple_set_string(t, 5, sym->name);
  885. call_object(tables->symbol_handler, t, "symbol_table");
  886. Py_DECREF(t);
  887. return 0;
  888. }
  889. static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
  890. const char *name)
  891. {
  892. struct tables *tables = container_of(dbe, struct tables, dbe);
  893. PyObject *t;
  894. t = tuple_new(2);
  895. tuple_set_s32(t, 0, branch_type);
  896. tuple_set_string(t, 1, name);
  897. call_object(tables->branch_type_handler, t, "branch_type_table");
  898. Py_DECREF(t);
  899. return 0;
  900. }
  901. static int python_export_sample(struct db_export *dbe,
  902. struct export_sample *es)
  903. {
  904. struct tables *tables = container_of(dbe, struct tables, dbe);
  905. PyObject *t;
  906. t = tuple_new(22);
  907. tuple_set_u64(t, 0, es->db_id);
  908. tuple_set_u64(t, 1, es->evsel->db_id);
  909. tuple_set_u64(t, 2, es->al->machine->db_id);
  910. tuple_set_u64(t, 3, es->al->thread->db_id);
  911. tuple_set_u64(t, 4, es->comm_db_id);
  912. tuple_set_u64(t, 5, es->dso_db_id);
  913. tuple_set_u64(t, 6, es->sym_db_id);
  914. tuple_set_u64(t, 7, es->offset);
  915. tuple_set_u64(t, 8, es->sample->ip);
  916. tuple_set_u64(t, 9, es->sample->time);
  917. tuple_set_s32(t, 10, es->sample->cpu);
  918. tuple_set_u64(t, 11, es->addr_dso_db_id);
  919. tuple_set_u64(t, 12, es->addr_sym_db_id);
  920. tuple_set_u64(t, 13, es->addr_offset);
  921. tuple_set_u64(t, 14, es->sample->addr);
  922. tuple_set_u64(t, 15, es->sample->period);
  923. tuple_set_u64(t, 16, es->sample->weight);
  924. tuple_set_u64(t, 17, es->sample->transaction);
  925. tuple_set_u64(t, 18, es->sample->data_src);
  926. tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
  927. tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
  928. tuple_set_u64(t, 21, es->call_path_id);
  929. call_object(tables->sample_handler, t, "sample_table");
  930. Py_DECREF(t);
  931. return 0;
  932. }
  933. static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
  934. {
  935. struct tables *tables = container_of(dbe, struct tables, dbe);
  936. PyObject *t;
  937. u64 parent_db_id, sym_db_id;
  938. parent_db_id = cp->parent ? cp->parent->db_id : 0;
  939. sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
  940. t = tuple_new(4);
  941. tuple_set_u64(t, 0, cp->db_id);
  942. tuple_set_u64(t, 1, parent_db_id);
  943. tuple_set_u64(t, 2, sym_db_id);
  944. tuple_set_u64(t, 3, cp->ip);
  945. call_object(tables->call_path_handler, t, "call_path_table");
  946. Py_DECREF(t);
  947. return 0;
  948. }
  949. static int python_export_call_return(struct db_export *dbe,
  950. struct call_return *cr)
  951. {
  952. struct tables *tables = container_of(dbe, struct tables, dbe);
  953. u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
  954. PyObject *t;
  955. t = tuple_new(11);
  956. tuple_set_u64(t, 0, cr->db_id);
  957. tuple_set_u64(t, 1, cr->thread->db_id);
  958. tuple_set_u64(t, 2, comm_db_id);
  959. tuple_set_u64(t, 3, cr->cp->db_id);
  960. tuple_set_u64(t, 4, cr->call_time);
  961. tuple_set_u64(t, 5, cr->return_time);
  962. tuple_set_u64(t, 6, cr->branch_count);
  963. tuple_set_u64(t, 7, cr->call_ref);
  964. tuple_set_u64(t, 8, cr->return_ref);
  965. tuple_set_u64(t, 9, cr->cp->parent->db_id);
  966. tuple_set_s32(t, 10, cr->flags);
  967. call_object(tables->call_return_handler, t, "call_return_table");
  968. Py_DECREF(t);
  969. return 0;
  970. }
  971. static int python_process_call_return(struct call_return *cr, void *data)
  972. {
  973. struct db_export *dbe = data;
  974. return db_export__call_return(dbe, cr);
  975. }
  976. static void python_process_general_event(struct perf_sample *sample,
  977. struct perf_evsel *evsel,
  978. struct addr_location *al)
  979. {
  980. PyObject *handler, *t, *dict, *callchain;
  981. static char handler_name[64];
  982. unsigned n = 0;
  983. snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
  984. handler = get_handler(handler_name);
  985. if (!handler)
  986. return;
  987. /*
  988. * Use the MAX_FIELDS to make the function expandable, though
  989. * currently there is only one item for the tuple.
  990. */
  991. t = PyTuple_New(MAX_FIELDS);
  992. if (!t)
  993. Py_FatalError("couldn't create Python tuple");
  994. /* ip unwinding */
  995. callchain = python_process_callchain(sample, evsel, al);
  996. dict = get_perf_sample_dict(sample, evsel, al, callchain);
  997. PyTuple_SetItem(t, n++, dict);
  998. if (_PyTuple_Resize(&t, n) == -1)
  999. Py_FatalError("error resizing Python tuple");
  1000. call_object(handler, t, handler_name);
  1001. Py_DECREF(t);
  1002. }
  1003. static void python_process_event(union perf_event *event,
  1004. struct perf_sample *sample,
  1005. struct perf_evsel *evsel,
  1006. struct addr_location *al)
  1007. {
  1008. struct tables *tables = &tables_global;
  1009. switch (evsel->attr.type) {
  1010. case PERF_TYPE_TRACEPOINT:
  1011. python_process_tracepoint(sample, evsel, al);
  1012. break;
  1013. /* Reserve for future process_hw/sw/raw APIs */
  1014. default:
  1015. if (tables->db_export_mode)
  1016. db_export__sample(&tables->dbe, event, sample, evsel, al);
  1017. else
  1018. python_process_general_event(sample, evsel, al);
  1019. }
  1020. }
  1021. static void get_handler_name(char *str, size_t size,
  1022. struct perf_evsel *evsel)
  1023. {
  1024. char *p = str;
  1025. scnprintf(str, size, "stat__%s", perf_evsel__name(evsel));
  1026. while ((p = strchr(p, ':'))) {
  1027. *p = '_';
  1028. p++;
  1029. }
  1030. }
  1031. static void
  1032. process_stat(struct perf_evsel *counter, int cpu, int thread, u64 tstamp,
  1033. struct perf_counts_values *count)
  1034. {
  1035. PyObject *handler, *t;
  1036. static char handler_name[256];
  1037. int n = 0;
  1038. t = PyTuple_New(MAX_FIELDS);
  1039. if (!t)
  1040. Py_FatalError("couldn't create Python tuple");
  1041. get_handler_name(handler_name, sizeof(handler_name),
  1042. counter);
  1043. handler = get_handler(handler_name);
  1044. if (!handler) {
  1045. pr_debug("can't find python handler %s\n", handler_name);
  1046. return;
  1047. }
  1048. PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
  1049. PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
  1050. tuple_set_u64(t, n++, tstamp);
  1051. tuple_set_u64(t, n++, count->val);
  1052. tuple_set_u64(t, n++, count->ena);
  1053. tuple_set_u64(t, n++, count->run);
  1054. if (_PyTuple_Resize(&t, n) == -1)
  1055. Py_FatalError("error resizing Python tuple");
  1056. call_object(handler, t, handler_name);
  1057. Py_DECREF(t);
  1058. }
  1059. static void python_process_stat(struct perf_stat_config *config,
  1060. struct perf_evsel *counter, u64 tstamp)
  1061. {
  1062. struct thread_map *threads = counter->threads;
  1063. struct cpu_map *cpus = counter->cpus;
  1064. int cpu, thread;
  1065. if (config->aggr_mode == AGGR_GLOBAL) {
  1066. process_stat(counter, -1, -1, tstamp,
  1067. &counter->counts->aggr);
  1068. return;
  1069. }
  1070. for (thread = 0; thread < threads->nr; thread++) {
  1071. for (cpu = 0; cpu < cpus->nr; cpu++) {
  1072. process_stat(counter, cpus->map[cpu],
  1073. thread_map__pid(threads, thread), tstamp,
  1074. perf_counts(counter->counts, cpu, thread));
  1075. }
  1076. }
  1077. }
  1078. static void python_process_stat_interval(u64 tstamp)
  1079. {
  1080. PyObject *handler, *t;
  1081. static const char handler_name[] = "stat__interval";
  1082. int n = 0;
  1083. t = PyTuple_New(MAX_FIELDS);
  1084. if (!t)
  1085. Py_FatalError("couldn't create Python tuple");
  1086. handler = get_handler(handler_name);
  1087. if (!handler) {
  1088. pr_debug("can't find python handler %s\n", handler_name);
  1089. return;
  1090. }
  1091. tuple_set_u64(t, n++, tstamp);
  1092. if (_PyTuple_Resize(&t, n) == -1)
  1093. Py_FatalError("error resizing Python tuple");
  1094. call_object(handler, t, handler_name);
  1095. Py_DECREF(t);
  1096. }
  1097. static int run_start_sub(void)
  1098. {
  1099. main_module = PyImport_AddModule("__main__");
  1100. if (main_module == NULL)
  1101. return -1;
  1102. Py_INCREF(main_module);
  1103. main_dict = PyModule_GetDict(main_module);
  1104. if (main_dict == NULL)
  1105. goto error;
  1106. Py_INCREF(main_dict);
  1107. try_call_object("trace_begin", NULL);
  1108. return 0;
  1109. error:
  1110. Py_XDECREF(main_dict);
  1111. Py_XDECREF(main_module);
  1112. return -1;
  1113. }
  1114. #define SET_TABLE_HANDLER_(name, handler_name, table_name) do { \
  1115. tables->handler_name = get_handler(#table_name); \
  1116. if (tables->handler_name) \
  1117. tables->dbe.export_ ## name = python_export_ ## name; \
  1118. } while (0)
  1119. #define SET_TABLE_HANDLER(name) \
  1120. SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
  1121. static void set_table_handlers(struct tables *tables)
  1122. {
  1123. const char *perf_db_export_mode = "perf_db_export_mode";
  1124. const char *perf_db_export_calls = "perf_db_export_calls";
  1125. const char *perf_db_export_callchains = "perf_db_export_callchains";
  1126. PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
  1127. bool export_calls = false;
  1128. bool export_callchains = false;
  1129. int ret;
  1130. memset(tables, 0, sizeof(struct tables));
  1131. if (db_export__init(&tables->dbe))
  1132. Py_FatalError("failed to initialize export");
  1133. db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
  1134. if (!db_export_mode)
  1135. return;
  1136. ret = PyObject_IsTrue(db_export_mode);
  1137. if (ret == -1)
  1138. handler_call_die(perf_db_export_mode);
  1139. if (!ret)
  1140. return;
  1141. /* handle export calls */
  1142. tables->dbe.crp = NULL;
  1143. db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
  1144. if (db_export_calls) {
  1145. ret = PyObject_IsTrue(db_export_calls);
  1146. if (ret == -1)
  1147. handler_call_die(perf_db_export_calls);
  1148. export_calls = !!ret;
  1149. }
  1150. if (export_calls) {
  1151. tables->dbe.crp =
  1152. call_return_processor__new(python_process_call_return,
  1153. &tables->dbe);
  1154. if (!tables->dbe.crp)
  1155. Py_FatalError("failed to create calls processor");
  1156. }
  1157. /* handle export callchains */
  1158. tables->dbe.cpr = NULL;
  1159. db_export_callchains = PyDict_GetItemString(main_dict,
  1160. perf_db_export_callchains);
  1161. if (db_export_callchains) {
  1162. ret = PyObject_IsTrue(db_export_callchains);
  1163. if (ret == -1)
  1164. handler_call_die(perf_db_export_callchains);
  1165. export_callchains = !!ret;
  1166. }
  1167. if (export_callchains) {
  1168. /*
  1169. * Attempt to use the call path root from the call return
  1170. * processor, if the call return processor is in use. Otherwise,
  1171. * we allocate a new call path root. This prevents exporting
  1172. * duplicate call path ids when both are in use simultaniously.
  1173. */
  1174. if (tables->dbe.crp)
  1175. tables->dbe.cpr = tables->dbe.crp->cpr;
  1176. else
  1177. tables->dbe.cpr = call_path_root__new();
  1178. if (!tables->dbe.cpr)
  1179. Py_FatalError("failed to create call path root");
  1180. }
  1181. tables->db_export_mode = true;
  1182. /*
  1183. * Reserve per symbol space for symbol->db_id via symbol__priv()
  1184. */
  1185. symbol_conf.priv_size = sizeof(u64);
  1186. SET_TABLE_HANDLER(evsel);
  1187. SET_TABLE_HANDLER(machine);
  1188. SET_TABLE_HANDLER(thread);
  1189. SET_TABLE_HANDLER(comm);
  1190. SET_TABLE_HANDLER(comm_thread);
  1191. SET_TABLE_HANDLER(dso);
  1192. SET_TABLE_HANDLER(symbol);
  1193. SET_TABLE_HANDLER(branch_type);
  1194. SET_TABLE_HANDLER(sample);
  1195. SET_TABLE_HANDLER(call_path);
  1196. SET_TABLE_HANDLER(call_return);
  1197. }
  1198. #if PY_MAJOR_VERSION < 3
  1199. static void _free_command_line(const char **command_line, int num)
  1200. {
  1201. free(command_line);
  1202. }
  1203. #else
  1204. static void _free_command_line(wchar_t **command_line, int num)
  1205. {
  1206. int i;
  1207. for (i = 0; i < num; i++)
  1208. PyMem_RawFree(command_line[i]);
  1209. free(command_line);
  1210. }
  1211. #endif
  1212. /*
  1213. * Start trace script
  1214. */
  1215. static int python_start_script(const char *script, int argc, const char **argv)
  1216. {
  1217. struct tables *tables = &tables_global;
  1218. #if PY_MAJOR_VERSION < 3
  1219. const char **command_line;
  1220. #else
  1221. wchar_t **command_line;
  1222. #endif
  1223. /*
  1224. * Use a non-const name variable to cope with python 2.6's
  1225. * PyImport_AppendInittab prototype
  1226. */
  1227. char buf[PATH_MAX], name[19] = "perf_trace_context";
  1228. int i, err = 0;
  1229. FILE *fp;
  1230. #if PY_MAJOR_VERSION < 3
  1231. command_line = malloc((argc + 1) * sizeof(const char *));
  1232. command_line[0] = script;
  1233. for (i = 1; i < argc + 1; i++)
  1234. command_line[i] = argv[i - 1];
  1235. PyImport_AppendInittab(name, initperf_trace_context);
  1236. #else
  1237. command_line = malloc((argc + 1) * sizeof(wchar_t *));
  1238. command_line[0] = Py_DecodeLocale(script, NULL);
  1239. for (i = 1; i < argc + 1; i++)
  1240. command_line[i] = Py_DecodeLocale(argv[i - 1], NULL);
  1241. PyImport_AppendInittab(name, PyInit_perf_trace_context);
  1242. #endif
  1243. Py_Initialize();
  1244. #if PY_MAJOR_VERSION < 3
  1245. PySys_SetArgv(argc + 1, (char **)command_line);
  1246. #else
  1247. PySys_SetArgv(argc + 1, command_line);
  1248. #endif
  1249. fp = fopen(script, "r");
  1250. if (!fp) {
  1251. sprintf(buf, "Can't open python script \"%s\"", script);
  1252. perror(buf);
  1253. err = -1;
  1254. goto error;
  1255. }
  1256. err = PyRun_SimpleFile(fp, script);
  1257. if (err) {
  1258. fprintf(stderr, "Error running python script %s\n", script);
  1259. goto error;
  1260. }
  1261. err = run_start_sub();
  1262. if (err) {
  1263. fprintf(stderr, "Error starting python script %s\n", script);
  1264. goto error;
  1265. }
  1266. set_table_handlers(tables);
  1267. if (tables->db_export_mode) {
  1268. err = db_export__branch_types(&tables->dbe);
  1269. if (err)
  1270. goto error;
  1271. }
  1272. _free_command_line(command_line, argc + 1);
  1273. return err;
  1274. error:
  1275. Py_Finalize();
  1276. _free_command_line(command_line, argc + 1);
  1277. return err;
  1278. }
  1279. static int python_flush_script(void)
  1280. {
  1281. struct tables *tables = &tables_global;
  1282. return db_export__flush(&tables->dbe);
  1283. }
  1284. /*
  1285. * Stop trace script
  1286. */
  1287. static int python_stop_script(void)
  1288. {
  1289. struct tables *tables = &tables_global;
  1290. try_call_object("trace_end", NULL);
  1291. db_export__exit(&tables->dbe);
  1292. Py_XDECREF(main_dict);
  1293. Py_XDECREF(main_module);
  1294. Py_Finalize();
  1295. return 0;
  1296. }
  1297. static int python_generate_script(struct tep_handle *pevent, const char *outfile)
  1298. {
  1299. struct event_format *event = NULL;
  1300. struct format_field *f;
  1301. char fname[PATH_MAX];
  1302. int not_first, count;
  1303. FILE *ofp;
  1304. sprintf(fname, "%s.py", outfile);
  1305. ofp = fopen(fname, "w");
  1306. if (ofp == NULL) {
  1307. fprintf(stderr, "couldn't open %s\n", fname);
  1308. return -1;
  1309. }
  1310. fprintf(ofp, "# perf script event handlers, "
  1311. "generated by perf script -g python\n");
  1312. fprintf(ofp, "# Licensed under the terms of the GNU GPL"
  1313. " License version 2\n\n");
  1314. fprintf(ofp, "# The common_* event handler fields are the most useful "
  1315. "fields common to\n");
  1316. fprintf(ofp, "# all events. They don't necessarily correspond to "
  1317. "the 'common_*' fields\n");
  1318. fprintf(ofp, "# in the format files. Those fields not available as "
  1319. "handler params can\n");
  1320. fprintf(ofp, "# be retrieved using Python functions of the form "
  1321. "common_*(context).\n");
  1322. fprintf(ofp, "# See the perf-script-python Documentation for the list "
  1323. "of available functions.\n\n");
  1324. fprintf(ofp, "from __future__ import print_function\n\n");
  1325. fprintf(ofp, "import os\n");
  1326. fprintf(ofp, "import sys\n\n");
  1327. fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
  1328. fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
  1329. fprintf(ofp, "\nfrom perf_trace_context import *\n");
  1330. fprintf(ofp, "from Core import *\n\n\n");
  1331. fprintf(ofp, "def trace_begin():\n");
  1332. fprintf(ofp, "\tprint(\"in trace_begin\")\n\n");
  1333. fprintf(ofp, "def trace_end():\n");
  1334. fprintf(ofp, "\tprint(\"in trace_end\")\n\n");
  1335. while ((event = trace_find_next_event(pevent, event))) {
  1336. fprintf(ofp, "def %s__%s(", event->system, event->name);
  1337. fprintf(ofp, "event_name, ");
  1338. fprintf(ofp, "context, ");
  1339. fprintf(ofp, "common_cpu,\n");
  1340. fprintf(ofp, "\tcommon_secs, ");
  1341. fprintf(ofp, "common_nsecs, ");
  1342. fprintf(ofp, "common_pid, ");
  1343. fprintf(ofp, "common_comm,\n\t");
  1344. fprintf(ofp, "common_callchain, ");
  1345. not_first = 0;
  1346. count = 0;
  1347. for (f = event->format.fields; f; f = f->next) {
  1348. if (not_first++)
  1349. fprintf(ofp, ", ");
  1350. if (++count % 5 == 0)
  1351. fprintf(ofp, "\n\t");
  1352. fprintf(ofp, "%s", f->name);
  1353. }
  1354. if (not_first++)
  1355. fprintf(ofp, ", ");
  1356. if (++count % 5 == 0)
  1357. fprintf(ofp, "\n\t\t");
  1358. fprintf(ofp, "perf_sample_dict");
  1359. fprintf(ofp, "):\n");
  1360. fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
  1361. "common_secs, common_nsecs,\n\t\t\t"
  1362. "common_pid, common_comm)\n\n");
  1363. fprintf(ofp, "\t\tprint(\"");
  1364. not_first = 0;
  1365. count = 0;
  1366. for (f = event->format.fields; f; f = f->next) {
  1367. if (not_first++)
  1368. fprintf(ofp, ", ");
  1369. if (count && count % 3 == 0) {
  1370. fprintf(ofp, "\" \\\n\t\t\"");
  1371. }
  1372. count++;
  1373. fprintf(ofp, "%s=", f->name);
  1374. if (f->flags & FIELD_IS_STRING ||
  1375. f->flags & FIELD_IS_FLAG ||
  1376. f->flags & FIELD_IS_ARRAY ||
  1377. f->flags & FIELD_IS_SYMBOLIC)
  1378. fprintf(ofp, "%%s");
  1379. else if (f->flags & FIELD_IS_SIGNED)
  1380. fprintf(ofp, "%%d");
  1381. else
  1382. fprintf(ofp, "%%u");
  1383. }
  1384. fprintf(ofp, "\" %% \\\n\t\t(");
  1385. not_first = 0;
  1386. count = 0;
  1387. for (f = event->format.fields; f; f = f->next) {
  1388. if (not_first++)
  1389. fprintf(ofp, ", ");
  1390. if (++count % 5 == 0)
  1391. fprintf(ofp, "\n\t\t");
  1392. if (f->flags & FIELD_IS_FLAG) {
  1393. if ((count - 1) % 5 != 0) {
  1394. fprintf(ofp, "\n\t\t");
  1395. count = 4;
  1396. }
  1397. fprintf(ofp, "flag_str(\"");
  1398. fprintf(ofp, "%s__%s\", ", event->system,
  1399. event->name);
  1400. fprintf(ofp, "\"%s\", %s)", f->name,
  1401. f->name);
  1402. } else if (f->flags & FIELD_IS_SYMBOLIC) {
  1403. if ((count - 1) % 5 != 0) {
  1404. fprintf(ofp, "\n\t\t");
  1405. count = 4;
  1406. }
  1407. fprintf(ofp, "symbol_str(\"");
  1408. fprintf(ofp, "%s__%s\", ", event->system,
  1409. event->name);
  1410. fprintf(ofp, "\"%s\", %s)", f->name,
  1411. f->name);
  1412. } else
  1413. fprintf(ofp, "%s", f->name);
  1414. }
  1415. fprintf(ofp, "))\n\n");
  1416. fprintf(ofp, "\t\tprint('Sample: {'+"
  1417. "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
  1418. fprintf(ofp, "\t\tfor node in common_callchain:");
  1419. fprintf(ofp, "\n\t\t\tif 'sym' in node:");
  1420. fprintf(ofp, "\n\t\t\t\tprint(\"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name']))");
  1421. fprintf(ofp, "\n\t\t\telse:");
  1422. fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x]\" %% (node['ip']))\n\n");
  1423. fprintf(ofp, "\t\tprint()\n\n");
  1424. }
  1425. fprintf(ofp, "def trace_unhandled(event_name, context, "
  1426. "event_fields_dict, perf_sample_dict):\n");
  1427. fprintf(ofp, "\t\tprint(get_dict_as_string(event_fields_dict))\n");
  1428. fprintf(ofp, "\t\tprint('Sample: {'+"
  1429. "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
  1430. fprintf(ofp, "def print_header("
  1431. "event_name, cpu, secs, nsecs, pid, comm):\n"
  1432. "\tprint(\"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
  1433. "(event_name, cpu, secs, nsecs, pid, comm), end=\"\")\n\n");
  1434. fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
  1435. "\treturn delimiter.join"
  1436. "(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
  1437. fclose(ofp);
  1438. fprintf(stderr, "generated Python script: %s\n", fname);
  1439. return 0;
  1440. }
  1441. struct scripting_ops python_scripting_ops = {
  1442. .name = "Python",
  1443. .start_script = python_start_script,
  1444. .flush_script = python_flush_script,
  1445. .stop_script = python_stop_script,
  1446. .process_event = python_process_event,
  1447. .process_stat = python_process_stat,
  1448. .process_stat_interval = python_process_stat_interval,
  1449. .generate_script = python_generate_script,
  1450. };