trace-event-python.c 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786
  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(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(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(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(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", _PyUnicode_FromStringAndSize(
  615. (const char *)&evsel->attr, sizeof(evsel->attr)));
  616. pydict_set_item_string_decref(dict_sample, "pid",
  617. _PyLong_FromLong(sample->pid));
  618. pydict_set_item_string_decref(dict_sample, "tid",
  619. _PyLong_FromLong(sample->tid));
  620. pydict_set_item_string_decref(dict_sample, "cpu",
  621. _PyLong_FromLong(sample->cpu));
  622. pydict_set_item_string_decref(dict_sample, "ip",
  623. PyLong_FromUnsignedLongLong(sample->ip));
  624. pydict_set_item_string_decref(dict_sample, "time",
  625. PyLong_FromUnsignedLongLong(sample->time));
  626. pydict_set_item_string_decref(dict_sample, "period",
  627. PyLong_FromUnsignedLongLong(sample->period));
  628. pydict_set_item_string_decref(dict_sample, "phys_addr",
  629. PyLong_FromUnsignedLongLong(sample->phys_addr));
  630. pydict_set_item_string_decref(dict_sample, "addr",
  631. PyLong_FromUnsignedLongLong(sample->addr));
  632. set_sample_read_in_dict(dict_sample, sample, evsel);
  633. pydict_set_item_string_decref(dict_sample, "weight",
  634. PyLong_FromUnsignedLongLong(sample->weight));
  635. pydict_set_item_string_decref(dict_sample, "transaction",
  636. PyLong_FromUnsignedLongLong(sample->transaction));
  637. set_sample_datasrc_in_dict(dict_sample, sample);
  638. pydict_set_item_string_decref(dict, "sample", dict_sample);
  639. pydict_set_item_string_decref(dict, "raw_buf", _PyBytes_FromStringAndSize(
  640. (const char *)sample->raw_data, sample->raw_size));
  641. pydict_set_item_string_decref(dict, "comm",
  642. _PyUnicode_FromString(thread__comm_str(al->thread)));
  643. if (al->map) {
  644. pydict_set_item_string_decref(dict, "dso",
  645. _PyUnicode_FromString(al->map->dso->name));
  646. }
  647. if (al->sym) {
  648. pydict_set_item_string_decref(dict, "symbol",
  649. _PyUnicode_FromString(al->sym->name));
  650. }
  651. pydict_set_item_string_decref(dict, "callchain", callchain);
  652. brstack = python_process_brstack(sample, al->thread);
  653. pydict_set_item_string_decref(dict, "brstack", brstack);
  654. brstacksym = python_process_brstacksym(sample, al->thread);
  655. pydict_set_item_string_decref(dict, "brstacksym", brstacksym);
  656. set_regs_in_dict(dict, sample, evsel);
  657. return dict;
  658. }
  659. static void python_process_tracepoint(struct perf_sample *sample,
  660. struct perf_evsel *evsel,
  661. struct addr_location *al)
  662. {
  663. struct event_format *event = evsel->tp_format;
  664. PyObject *handler, *context, *t, *obj = NULL, *callchain;
  665. PyObject *dict = NULL, *all_entries_dict = NULL;
  666. static char handler_name[256];
  667. struct format_field *field;
  668. unsigned long s, ns;
  669. unsigned n = 0;
  670. int pid;
  671. int cpu = sample->cpu;
  672. void *data = sample->raw_data;
  673. unsigned long long nsecs = sample->time;
  674. const char *comm = thread__comm_str(al->thread);
  675. const char *default_handler_name = "trace_unhandled";
  676. if (!event) {
  677. snprintf(handler_name, sizeof(handler_name),
  678. "ug! no event found for type %" PRIu64, (u64)evsel->attr.config);
  679. Py_FatalError(handler_name);
  680. }
  681. pid = raw_field_value(event, "common_pid", data);
  682. sprintf(handler_name, "%s__%s", event->system, event->name);
  683. if (!test_and_set_bit(event->id, events_defined))
  684. define_event_symbols(event, handler_name, event->print_fmt.args);
  685. handler = get_handler(handler_name);
  686. if (!handler) {
  687. handler = get_handler(default_handler_name);
  688. if (!handler)
  689. return;
  690. dict = PyDict_New();
  691. if (!dict)
  692. Py_FatalError("couldn't create Python dict");
  693. }
  694. t = PyTuple_New(MAX_FIELDS);
  695. if (!t)
  696. Py_FatalError("couldn't create Python tuple");
  697. s = nsecs / NSEC_PER_SEC;
  698. ns = nsecs - s * NSEC_PER_SEC;
  699. scripting_context->event_data = data;
  700. scripting_context->pevent = evsel->tp_format->pevent;
  701. context = _PyCapsule_New(scripting_context, NULL, NULL);
  702. PyTuple_SetItem(t, n++, _PyUnicode_FromString(handler_name));
  703. PyTuple_SetItem(t, n++, context);
  704. /* ip unwinding */
  705. callchain = python_process_callchain(sample, evsel, al);
  706. /* Need an additional reference for the perf_sample dict */
  707. Py_INCREF(callchain);
  708. if (!dict) {
  709. PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
  710. PyTuple_SetItem(t, n++, _PyLong_FromLong(s));
  711. PyTuple_SetItem(t, n++, _PyLong_FromLong(ns));
  712. PyTuple_SetItem(t, n++, _PyLong_FromLong(pid));
  713. PyTuple_SetItem(t, n++, _PyUnicode_FromString(comm));
  714. PyTuple_SetItem(t, n++, callchain);
  715. } else {
  716. pydict_set_item_string_decref(dict, "common_cpu", _PyLong_FromLong(cpu));
  717. pydict_set_item_string_decref(dict, "common_s", _PyLong_FromLong(s));
  718. pydict_set_item_string_decref(dict, "common_ns", _PyLong_FromLong(ns));
  719. pydict_set_item_string_decref(dict, "common_pid", _PyLong_FromLong(pid));
  720. pydict_set_item_string_decref(dict, "common_comm", _PyUnicode_FromString(comm));
  721. pydict_set_item_string_decref(dict, "common_callchain", callchain);
  722. }
  723. for (field = event->format.fields; field; field = field->next) {
  724. unsigned int offset, len;
  725. unsigned long long val;
  726. if (field->flags & FIELD_IS_ARRAY) {
  727. offset = field->offset;
  728. len = field->size;
  729. if (field->flags & FIELD_IS_DYNAMIC) {
  730. val = pevent_read_number(scripting_context->pevent,
  731. data + offset, len);
  732. offset = val;
  733. len = offset >> 16;
  734. offset &= 0xffff;
  735. }
  736. if (field->flags & FIELD_IS_STRING &&
  737. is_printable_array(data + offset, len)) {
  738. obj = _PyUnicode_FromString((char *) data + offset);
  739. } else {
  740. obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
  741. field->flags &= ~FIELD_IS_STRING;
  742. }
  743. } else { /* FIELD_IS_NUMERIC */
  744. obj = get_field_numeric_entry(event, field, data);
  745. }
  746. if (!dict)
  747. PyTuple_SetItem(t, n++, obj);
  748. else
  749. pydict_set_item_string_decref(dict, field->name, obj);
  750. }
  751. if (dict)
  752. PyTuple_SetItem(t, n++, dict);
  753. if (get_argument_count(handler) == (int) n + 1) {
  754. all_entries_dict = get_perf_sample_dict(sample, evsel, al,
  755. callchain);
  756. PyTuple_SetItem(t, n++, all_entries_dict);
  757. } else {
  758. Py_DECREF(callchain);
  759. }
  760. if (_PyTuple_Resize(&t, n) == -1)
  761. Py_FatalError("error resizing Python tuple");
  762. if (!dict) {
  763. call_object(handler, t, handler_name);
  764. } else {
  765. call_object(handler, t, default_handler_name);
  766. Py_DECREF(dict);
  767. }
  768. Py_XDECREF(all_entries_dict);
  769. Py_DECREF(t);
  770. }
  771. static PyObject *tuple_new(unsigned int sz)
  772. {
  773. PyObject *t;
  774. t = PyTuple_New(sz);
  775. if (!t)
  776. Py_FatalError("couldn't create Python tuple");
  777. return t;
  778. }
  779. static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
  780. {
  781. #if BITS_PER_LONG == 64
  782. return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
  783. #endif
  784. #if BITS_PER_LONG == 32
  785. return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
  786. #endif
  787. }
  788. static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
  789. {
  790. return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
  791. }
  792. static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
  793. {
  794. return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
  795. }
  796. static int python_export_evsel(struct db_export *dbe, struct perf_evsel *evsel)
  797. {
  798. struct tables *tables = container_of(dbe, struct tables, dbe);
  799. PyObject *t;
  800. t = tuple_new(2);
  801. tuple_set_u64(t, 0, evsel->db_id);
  802. tuple_set_string(t, 1, perf_evsel__name(evsel));
  803. call_object(tables->evsel_handler, t, "evsel_table");
  804. Py_DECREF(t);
  805. return 0;
  806. }
  807. static int python_export_machine(struct db_export *dbe,
  808. struct machine *machine)
  809. {
  810. struct tables *tables = container_of(dbe, struct tables, dbe);
  811. PyObject *t;
  812. t = tuple_new(3);
  813. tuple_set_u64(t, 0, machine->db_id);
  814. tuple_set_s32(t, 1, machine->pid);
  815. tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
  816. call_object(tables->machine_handler, t, "machine_table");
  817. Py_DECREF(t);
  818. return 0;
  819. }
  820. static int python_export_thread(struct db_export *dbe, struct thread *thread,
  821. u64 main_thread_db_id, struct machine *machine)
  822. {
  823. struct tables *tables = container_of(dbe, struct tables, dbe);
  824. PyObject *t;
  825. t = tuple_new(5);
  826. tuple_set_u64(t, 0, thread->db_id);
  827. tuple_set_u64(t, 1, machine->db_id);
  828. tuple_set_u64(t, 2, main_thread_db_id);
  829. tuple_set_s32(t, 3, thread->pid_);
  830. tuple_set_s32(t, 4, thread->tid);
  831. call_object(tables->thread_handler, t, "thread_table");
  832. Py_DECREF(t);
  833. return 0;
  834. }
  835. static int python_export_comm(struct db_export *dbe, struct comm *comm)
  836. {
  837. struct tables *tables = container_of(dbe, struct tables, dbe);
  838. PyObject *t;
  839. t = tuple_new(2);
  840. tuple_set_u64(t, 0, comm->db_id);
  841. tuple_set_string(t, 1, comm__str(comm));
  842. call_object(tables->comm_handler, t, "comm_table");
  843. Py_DECREF(t);
  844. return 0;
  845. }
  846. static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
  847. struct comm *comm, struct thread *thread)
  848. {
  849. struct tables *tables = container_of(dbe, struct tables, dbe);
  850. PyObject *t;
  851. t = tuple_new(3);
  852. tuple_set_u64(t, 0, db_id);
  853. tuple_set_u64(t, 1, comm->db_id);
  854. tuple_set_u64(t, 2, thread->db_id);
  855. call_object(tables->comm_thread_handler, t, "comm_thread_table");
  856. Py_DECREF(t);
  857. return 0;
  858. }
  859. static int python_export_dso(struct db_export *dbe, struct dso *dso,
  860. struct machine *machine)
  861. {
  862. struct tables *tables = container_of(dbe, struct tables, dbe);
  863. char sbuild_id[SBUILD_ID_SIZE];
  864. PyObject *t;
  865. build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);
  866. t = tuple_new(5);
  867. tuple_set_u64(t, 0, dso->db_id);
  868. tuple_set_u64(t, 1, machine->db_id);
  869. tuple_set_string(t, 2, dso->short_name);
  870. tuple_set_string(t, 3, dso->long_name);
  871. tuple_set_string(t, 4, sbuild_id);
  872. call_object(tables->dso_handler, t, "dso_table");
  873. Py_DECREF(t);
  874. return 0;
  875. }
  876. static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
  877. struct dso *dso)
  878. {
  879. struct tables *tables = container_of(dbe, struct tables, dbe);
  880. u64 *sym_db_id = symbol__priv(sym);
  881. PyObject *t;
  882. t = tuple_new(6);
  883. tuple_set_u64(t, 0, *sym_db_id);
  884. tuple_set_u64(t, 1, dso->db_id);
  885. tuple_set_u64(t, 2, sym->start);
  886. tuple_set_u64(t, 3, sym->end);
  887. tuple_set_s32(t, 4, sym->binding);
  888. tuple_set_string(t, 5, sym->name);
  889. call_object(tables->symbol_handler, t, "symbol_table");
  890. Py_DECREF(t);
  891. return 0;
  892. }
  893. static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
  894. const char *name)
  895. {
  896. struct tables *tables = container_of(dbe, struct tables, dbe);
  897. PyObject *t;
  898. t = tuple_new(2);
  899. tuple_set_s32(t, 0, branch_type);
  900. tuple_set_string(t, 1, name);
  901. call_object(tables->branch_type_handler, t, "branch_type_table");
  902. Py_DECREF(t);
  903. return 0;
  904. }
  905. static int python_export_sample(struct db_export *dbe,
  906. struct export_sample *es)
  907. {
  908. struct tables *tables = container_of(dbe, struct tables, dbe);
  909. PyObject *t;
  910. t = tuple_new(22);
  911. tuple_set_u64(t, 0, es->db_id);
  912. tuple_set_u64(t, 1, es->evsel->db_id);
  913. tuple_set_u64(t, 2, es->al->machine->db_id);
  914. tuple_set_u64(t, 3, es->al->thread->db_id);
  915. tuple_set_u64(t, 4, es->comm_db_id);
  916. tuple_set_u64(t, 5, es->dso_db_id);
  917. tuple_set_u64(t, 6, es->sym_db_id);
  918. tuple_set_u64(t, 7, es->offset);
  919. tuple_set_u64(t, 8, es->sample->ip);
  920. tuple_set_u64(t, 9, es->sample->time);
  921. tuple_set_s32(t, 10, es->sample->cpu);
  922. tuple_set_u64(t, 11, es->addr_dso_db_id);
  923. tuple_set_u64(t, 12, es->addr_sym_db_id);
  924. tuple_set_u64(t, 13, es->addr_offset);
  925. tuple_set_u64(t, 14, es->sample->addr);
  926. tuple_set_u64(t, 15, es->sample->period);
  927. tuple_set_u64(t, 16, es->sample->weight);
  928. tuple_set_u64(t, 17, es->sample->transaction);
  929. tuple_set_u64(t, 18, es->sample->data_src);
  930. tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
  931. tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
  932. tuple_set_u64(t, 21, es->call_path_id);
  933. call_object(tables->sample_handler, t, "sample_table");
  934. Py_DECREF(t);
  935. return 0;
  936. }
  937. static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
  938. {
  939. struct tables *tables = container_of(dbe, struct tables, dbe);
  940. PyObject *t;
  941. u64 parent_db_id, sym_db_id;
  942. parent_db_id = cp->parent ? cp->parent->db_id : 0;
  943. sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
  944. t = tuple_new(4);
  945. tuple_set_u64(t, 0, cp->db_id);
  946. tuple_set_u64(t, 1, parent_db_id);
  947. tuple_set_u64(t, 2, sym_db_id);
  948. tuple_set_u64(t, 3, cp->ip);
  949. call_object(tables->call_path_handler, t, "call_path_table");
  950. Py_DECREF(t);
  951. return 0;
  952. }
  953. static int python_export_call_return(struct db_export *dbe,
  954. struct call_return *cr)
  955. {
  956. struct tables *tables = container_of(dbe, struct tables, dbe);
  957. u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
  958. PyObject *t;
  959. t = tuple_new(11);
  960. tuple_set_u64(t, 0, cr->db_id);
  961. tuple_set_u64(t, 1, cr->thread->db_id);
  962. tuple_set_u64(t, 2, comm_db_id);
  963. tuple_set_u64(t, 3, cr->cp->db_id);
  964. tuple_set_u64(t, 4, cr->call_time);
  965. tuple_set_u64(t, 5, cr->return_time);
  966. tuple_set_u64(t, 6, cr->branch_count);
  967. tuple_set_u64(t, 7, cr->call_ref);
  968. tuple_set_u64(t, 8, cr->return_ref);
  969. tuple_set_u64(t, 9, cr->cp->parent->db_id);
  970. tuple_set_s32(t, 10, cr->flags);
  971. call_object(tables->call_return_handler, t, "call_return_table");
  972. Py_DECREF(t);
  973. return 0;
  974. }
  975. static int python_process_call_return(struct call_return *cr, void *data)
  976. {
  977. struct db_export *dbe = data;
  978. return db_export__call_return(dbe, cr);
  979. }
  980. static void python_process_general_event(struct perf_sample *sample,
  981. struct perf_evsel *evsel,
  982. struct addr_location *al)
  983. {
  984. PyObject *handler, *t, *dict, *callchain;
  985. static char handler_name[64];
  986. unsigned n = 0;
  987. snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
  988. handler = get_handler(handler_name);
  989. if (!handler)
  990. return;
  991. /*
  992. * Use the MAX_FIELDS to make the function expandable, though
  993. * currently there is only one item for the tuple.
  994. */
  995. t = PyTuple_New(MAX_FIELDS);
  996. if (!t)
  997. Py_FatalError("couldn't create Python tuple");
  998. /* ip unwinding */
  999. callchain = python_process_callchain(sample, evsel, al);
  1000. dict = get_perf_sample_dict(sample, evsel, al, callchain);
  1001. PyTuple_SetItem(t, n++, dict);
  1002. if (_PyTuple_Resize(&t, n) == -1)
  1003. Py_FatalError("error resizing Python tuple");
  1004. call_object(handler, t, handler_name);
  1005. Py_DECREF(dict);
  1006. Py_DECREF(t);
  1007. }
  1008. static void python_process_event(union perf_event *event,
  1009. struct perf_sample *sample,
  1010. struct perf_evsel *evsel,
  1011. struct addr_location *al)
  1012. {
  1013. struct tables *tables = &tables_global;
  1014. switch (evsel->attr.type) {
  1015. case PERF_TYPE_TRACEPOINT:
  1016. python_process_tracepoint(sample, evsel, al);
  1017. break;
  1018. /* Reserve for future process_hw/sw/raw APIs */
  1019. default:
  1020. if (tables->db_export_mode)
  1021. db_export__sample(&tables->dbe, event, sample, evsel, al);
  1022. else
  1023. python_process_general_event(sample, evsel, al);
  1024. }
  1025. }
  1026. static void get_handler_name(char *str, size_t size,
  1027. struct perf_evsel *evsel)
  1028. {
  1029. char *p = str;
  1030. scnprintf(str, size, "stat__%s", perf_evsel__name(evsel));
  1031. while ((p = strchr(p, ':'))) {
  1032. *p = '_';
  1033. p++;
  1034. }
  1035. }
  1036. static void
  1037. process_stat(struct perf_evsel *counter, int cpu, int thread, u64 tstamp,
  1038. struct perf_counts_values *count)
  1039. {
  1040. PyObject *handler, *t;
  1041. static char handler_name[256];
  1042. int n = 0;
  1043. t = PyTuple_New(MAX_FIELDS);
  1044. if (!t)
  1045. Py_FatalError("couldn't create Python tuple");
  1046. get_handler_name(handler_name, sizeof(handler_name),
  1047. counter);
  1048. handler = get_handler(handler_name);
  1049. if (!handler) {
  1050. pr_debug("can't find python handler %s\n", handler_name);
  1051. return;
  1052. }
  1053. PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
  1054. PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
  1055. tuple_set_u64(t, n++, tstamp);
  1056. tuple_set_u64(t, n++, count->val);
  1057. tuple_set_u64(t, n++, count->ena);
  1058. tuple_set_u64(t, n++, count->run);
  1059. if (_PyTuple_Resize(&t, n) == -1)
  1060. Py_FatalError("error resizing Python tuple");
  1061. call_object(handler, t, handler_name);
  1062. Py_DECREF(t);
  1063. }
  1064. static void python_process_stat(struct perf_stat_config *config,
  1065. struct perf_evsel *counter, u64 tstamp)
  1066. {
  1067. struct thread_map *threads = counter->threads;
  1068. struct cpu_map *cpus = counter->cpus;
  1069. int cpu, thread;
  1070. if (config->aggr_mode == AGGR_GLOBAL) {
  1071. process_stat(counter, -1, -1, tstamp,
  1072. &counter->counts->aggr);
  1073. return;
  1074. }
  1075. for (thread = 0; thread < threads->nr; thread++) {
  1076. for (cpu = 0; cpu < cpus->nr; cpu++) {
  1077. process_stat(counter, cpus->map[cpu],
  1078. thread_map__pid(threads, thread), tstamp,
  1079. perf_counts(counter->counts, cpu, thread));
  1080. }
  1081. }
  1082. }
  1083. static void python_process_stat_interval(u64 tstamp)
  1084. {
  1085. PyObject *handler, *t;
  1086. static const char handler_name[] = "stat__interval";
  1087. int n = 0;
  1088. t = PyTuple_New(MAX_FIELDS);
  1089. if (!t)
  1090. Py_FatalError("couldn't create Python tuple");
  1091. handler = get_handler(handler_name);
  1092. if (!handler) {
  1093. pr_debug("can't find python handler %s\n", handler_name);
  1094. return;
  1095. }
  1096. tuple_set_u64(t, n++, tstamp);
  1097. if (_PyTuple_Resize(&t, n) == -1)
  1098. Py_FatalError("error resizing Python tuple");
  1099. call_object(handler, t, handler_name);
  1100. Py_DECREF(t);
  1101. }
  1102. static int run_start_sub(void)
  1103. {
  1104. main_module = PyImport_AddModule("__main__");
  1105. if (main_module == NULL)
  1106. return -1;
  1107. Py_INCREF(main_module);
  1108. main_dict = PyModule_GetDict(main_module);
  1109. if (main_dict == NULL)
  1110. goto error;
  1111. Py_INCREF(main_dict);
  1112. try_call_object("trace_begin", NULL);
  1113. return 0;
  1114. error:
  1115. Py_XDECREF(main_dict);
  1116. Py_XDECREF(main_module);
  1117. return -1;
  1118. }
  1119. #define SET_TABLE_HANDLER_(name, handler_name, table_name) do { \
  1120. tables->handler_name = get_handler(#table_name); \
  1121. if (tables->handler_name) \
  1122. tables->dbe.export_ ## name = python_export_ ## name; \
  1123. } while (0)
  1124. #define SET_TABLE_HANDLER(name) \
  1125. SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
  1126. static void set_table_handlers(struct tables *tables)
  1127. {
  1128. const char *perf_db_export_mode = "perf_db_export_mode";
  1129. const char *perf_db_export_calls = "perf_db_export_calls";
  1130. const char *perf_db_export_callchains = "perf_db_export_callchains";
  1131. PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
  1132. bool export_calls = false;
  1133. bool export_callchains = false;
  1134. int ret;
  1135. memset(tables, 0, sizeof(struct tables));
  1136. if (db_export__init(&tables->dbe))
  1137. Py_FatalError("failed to initialize export");
  1138. db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
  1139. if (!db_export_mode)
  1140. return;
  1141. ret = PyObject_IsTrue(db_export_mode);
  1142. if (ret == -1)
  1143. handler_call_die(perf_db_export_mode);
  1144. if (!ret)
  1145. return;
  1146. /* handle export calls */
  1147. tables->dbe.crp = NULL;
  1148. db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
  1149. if (db_export_calls) {
  1150. ret = PyObject_IsTrue(db_export_calls);
  1151. if (ret == -1)
  1152. handler_call_die(perf_db_export_calls);
  1153. export_calls = !!ret;
  1154. }
  1155. if (export_calls) {
  1156. tables->dbe.crp =
  1157. call_return_processor__new(python_process_call_return,
  1158. &tables->dbe);
  1159. if (!tables->dbe.crp)
  1160. Py_FatalError("failed to create calls processor");
  1161. }
  1162. /* handle export callchains */
  1163. tables->dbe.cpr = NULL;
  1164. db_export_callchains = PyDict_GetItemString(main_dict,
  1165. perf_db_export_callchains);
  1166. if (db_export_callchains) {
  1167. ret = PyObject_IsTrue(db_export_callchains);
  1168. if (ret == -1)
  1169. handler_call_die(perf_db_export_callchains);
  1170. export_callchains = !!ret;
  1171. }
  1172. if (export_callchains) {
  1173. /*
  1174. * Attempt to use the call path root from the call return
  1175. * processor, if the call return processor is in use. Otherwise,
  1176. * we allocate a new call path root. This prevents exporting
  1177. * duplicate call path ids when both are in use simultaniously.
  1178. */
  1179. if (tables->dbe.crp)
  1180. tables->dbe.cpr = tables->dbe.crp->cpr;
  1181. else
  1182. tables->dbe.cpr = call_path_root__new();
  1183. if (!tables->dbe.cpr)
  1184. Py_FatalError("failed to create call path root");
  1185. }
  1186. tables->db_export_mode = true;
  1187. /*
  1188. * Reserve per symbol space for symbol->db_id via symbol__priv()
  1189. */
  1190. symbol_conf.priv_size = sizeof(u64);
  1191. SET_TABLE_HANDLER(evsel);
  1192. SET_TABLE_HANDLER(machine);
  1193. SET_TABLE_HANDLER(thread);
  1194. SET_TABLE_HANDLER(comm);
  1195. SET_TABLE_HANDLER(comm_thread);
  1196. SET_TABLE_HANDLER(dso);
  1197. SET_TABLE_HANDLER(symbol);
  1198. SET_TABLE_HANDLER(branch_type);
  1199. SET_TABLE_HANDLER(sample);
  1200. SET_TABLE_HANDLER(call_path);
  1201. SET_TABLE_HANDLER(call_return);
  1202. }
  1203. #if PY_MAJOR_VERSION < 3
  1204. static void _free_command_line(const char **command_line, int num)
  1205. {
  1206. free(command_line);
  1207. }
  1208. #else
  1209. static void _free_command_line(wchar_t **command_line, int num)
  1210. {
  1211. int i;
  1212. for (i = 0; i < num; i++)
  1213. PyMem_RawFree(command_line[i]);
  1214. free(command_line);
  1215. }
  1216. #endif
  1217. /*
  1218. * Start trace script
  1219. */
  1220. static int python_start_script(const char *script, int argc, const char **argv)
  1221. {
  1222. struct tables *tables = &tables_global;
  1223. #if PY_MAJOR_VERSION < 3
  1224. const char **command_line;
  1225. #else
  1226. wchar_t **command_line;
  1227. #endif
  1228. char buf[PATH_MAX];
  1229. int i, err = 0;
  1230. FILE *fp;
  1231. #if PY_MAJOR_VERSION < 3
  1232. command_line = malloc((argc + 1) * sizeof(const char *));
  1233. command_line[0] = script;
  1234. for (i = 1; i < argc + 1; i++)
  1235. command_line[i] = argv[i - 1];
  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. #endif
  1242. Py_Initialize();
  1243. #if PY_MAJOR_VERSION < 3
  1244. initperf_trace_context();
  1245. PySys_SetArgv(argc + 1, (char **)command_line);
  1246. #else
  1247. PyInit_perf_trace_context();
  1248. PySys_SetArgv(argc + 1, command_line);
  1249. #endif
  1250. fp = fopen(script, "r");
  1251. if (!fp) {
  1252. sprintf(buf, "Can't open python script \"%s\"", script);
  1253. perror(buf);
  1254. err = -1;
  1255. goto error;
  1256. }
  1257. err = PyRun_SimpleFile(fp, script);
  1258. if (err) {
  1259. fprintf(stderr, "Error running python script %s\n", script);
  1260. goto error;
  1261. }
  1262. err = run_start_sub();
  1263. if (err) {
  1264. fprintf(stderr, "Error starting python script %s\n", script);
  1265. goto error;
  1266. }
  1267. set_table_handlers(tables);
  1268. if (tables->db_export_mode) {
  1269. err = db_export__branch_types(&tables->dbe);
  1270. if (err)
  1271. goto error;
  1272. }
  1273. _free_command_line(command_line, argc + 1);
  1274. return err;
  1275. error:
  1276. Py_Finalize();
  1277. _free_command_line(command_line, argc + 1);
  1278. return err;
  1279. }
  1280. static int python_flush_script(void)
  1281. {
  1282. struct tables *tables = &tables_global;
  1283. return db_export__flush(&tables->dbe);
  1284. }
  1285. /*
  1286. * Stop trace script
  1287. */
  1288. static int python_stop_script(void)
  1289. {
  1290. struct tables *tables = &tables_global;
  1291. try_call_object("trace_end", NULL);
  1292. db_export__exit(&tables->dbe);
  1293. Py_XDECREF(main_dict);
  1294. Py_XDECREF(main_module);
  1295. Py_Finalize();
  1296. return 0;
  1297. }
  1298. static int python_generate_script(struct pevent *pevent, const char *outfile)
  1299. {
  1300. struct event_format *event = NULL;
  1301. struct format_field *f;
  1302. char fname[PATH_MAX];
  1303. int not_first, count;
  1304. FILE *ofp;
  1305. sprintf(fname, "%s.py", outfile);
  1306. ofp = fopen(fname, "w");
  1307. if (ofp == NULL) {
  1308. fprintf(stderr, "couldn't open %s\n", fname);
  1309. return -1;
  1310. }
  1311. fprintf(ofp, "# perf script event handlers, "
  1312. "generated by perf script -g python\n");
  1313. fprintf(ofp, "# Licensed under the terms of the GNU GPL"
  1314. " License version 2\n\n");
  1315. fprintf(ofp, "# The common_* event handler fields are the most useful "
  1316. "fields common to\n");
  1317. fprintf(ofp, "# all events. They don't necessarily correspond to "
  1318. "the 'common_*' fields\n");
  1319. fprintf(ofp, "# in the format files. Those fields not available as "
  1320. "handler params can\n");
  1321. fprintf(ofp, "# be retrieved using Python functions of the form "
  1322. "common_*(context).\n");
  1323. fprintf(ofp, "# See the perf-script-python Documentation for the list "
  1324. "of available functions.\n\n");
  1325. fprintf(ofp, "from __future__ import print_function\n\n");
  1326. fprintf(ofp, "import os\n");
  1327. fprintf(ofp, "import sys\n\n");
  1328. fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
  1329. fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
  1330. fprintf(ofp, "\nfrom perf_trace_context import *\n");
  1331. fprintf(ofp, "from Core import *\n\n\n");
  1332. fprintf(ofp, "def trace_begin():\n");
  1333. fprintf(ofp, "\tprint(\"in trace_begin\")\n\n");
  1334. fprintf(ofp, "def trace_end():\n");
  1335. fprintf(ofp, "\tprint(\"in trace_end\")\n\n");
  1336. while ((event = trace_find_next_event(pevent, event))) {
  1337. fprintf(ofp, "def %s__%s(", event->system, event->name);
  1338. fprintf(ofp, "event_name, ");
  1339. fprintf(ofp, "context, ");
  1340. fprintf(ofp, "common_cpu,\n");
  1341. fprintf(ofp, "\tcommon_secs, ");
  1342. fprintf(ofp, "common_nsecs, ");
  1343. fprintf(ofp, "common_pid, ");
  1344. fprintf(ofp, "common_comm,\n\t");
  1345. fprintf(ofp, "common_callchain, ");
  1346. not_first = 0;
  1347. count = 0;
  1348. for (f = event->format.fields; f; f = f->next) {
  1349. if (not_first++)
  1350. fprintf(ofp, ", ");
  1351. if (++count % 5 == 0)
  1352. fprintf(ofp, "\n\t");
  1353. fprintf(ofp, "%s", f->name);
  1354. }
  1355. if (not_first++)
  1356. fprintf(ofp, ", ");
  1357. if (++count % 5 == 0)
  1358. fprintf(ofp, "\n\t\t");
  1359. fprintf(ofp, "perf_sample_dict");
  1360. fprintf(ofp, "):\n");
  1361. fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
  1362. "common_secs, common_nsecs,\n\t\t\t"
  1363. "common_pid, common_comm)\n\n");
  1364. fprintf(ofp, "\t\tprint(\"");
  1365. not_first = 0;
  1366. count = 0;
  1367. for (f = event->format.fields; f; f = f->next) {
  1368. if (not_first++)
  1369. fprintf(ofp, ", ");
  1370. if (count && count % 3 == 0) {
  1371. fprintf(ofp, "\" \\\n\t\t\"");
  1372. }
  1373. count++;
  1374. fprintf(ofp, "%s=", f->name);
  1375. if (f->flags & FIELD_IS_STRING ||
  1376. f->flags & FIELD_IS_FLAG ||
  1377. f->flags & FIELD_IS_ARRAY ||
  1378. f->flags & FIELD_IS_SYMBOLIC)
  1379. fprintf(ofp, "%%s");
  1380. else if (f->flags & FIELD_IS_SIGNED)
  1381. fprintf(ofp, "%%d");
  1382. else
  1383. fprintf(ofp, "%%u");
  1384. }
  1385. fprintf(ofp, "\" %% \\\n\t\t(");
  1386. not_first = 0;
  1387. count = 0;
  1388. for (f = event->format.fields; f; f = f->next) {
  1389. if (not_first++)
  1390. fprintf(ofp, ", ");
  1391. if (++count % 5 == 0)
  1392. fprintf(ofp, "\n\t\t");
  1393. if (f->flags & FIELD_IS_FLAG) {
  1394. if ((count - 1) % 5 != 0) {
  1395. fprintf(ofp, "\n\t\t");
  1396. count = 4;
  1397. }
  1398. fprintf(ofp, "flag_str(\"");
  1399. fprintf(ofp, "%s__%s\", ", event->system,
  1400. event->name);
  1401. fprintf(ofp, "\"%s\", %s)", f->name,
  1402. f->name);
  1403. } else if (f->flags & FIELD_IS_SYMBOLIC) {
  1404. if ((count - 1) % 5 != 0) {
  1405. fprintf(ofp, "\n\t\t");
  1406. count = 4;
  1407. }
  1408. fprintf(ofp, "symbol_str(\"");
  1409. fprintf(ofp, "%s__%s\", ", event->system,
  1410. event->name);
  1411. fprintf(ofp, "\"%s\", %s)", f->name,
  1412. f->name);
  1413. } else
  1414. fprintf(ofp, "%s", f->name);
  1415. }
  1416. fprintf(ofp, "))\n\n");
  1417. fprintf(ofp, "\t\tprint('Sample: {'+"
  1418. "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
  1419. fprintf(ofp, "\t\tfor node in common_callchain:");
  1420. fprintf(ofp, "\n\t\t\tif 'sym' in node:");
  1421. fprintf(ofp, "\n\t\t\t\tprint(\"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name']))");
  1422. fprintf(ofp, "\n\t\t\telse:");
  1423. fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x]\" %% (node['ip']))\n\n");
  1424. fprintf(ofp, "\t\tprint()\n\n");
  1425. }
  1426. fprintf(ofp, "def trace_unhandled(event_name, context, "
  1427. "event_fields_dict, perf_sample_dict):\n");
  1428. fprintf(ofp, "\t\tprint(get_dict_as_string(event_fields_dict))\n");
  1429. fprintf(ofp, "\t\tprint('Sample: {'+"
  1430. "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
  1431. fprintf(ofp, "def print_header("
  1432. "event_name, cpu, secs, nsecs, pid, comm):\n"
  1433. "\tprint(\"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
  1434. "(event_name, cpu, secs, nsecs, pid, comm), end=\"\")\n\n");
  1435. fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
  1436. "\treturn delimiter.join"
  1437. "(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
  1438. fclose(ofp);
  1439. fprintf(stderr, "generated Python script: %s\n", fname);
  1440. return 0;
  1441. }
  1442. struct scripting_ops python_scripting_ops = {
  1443. .name = "Python",
  1444. .start_script = python_start_script,
  1445. .flush_script = python_flush_script,
  1446. .stop_script = python_stop_script,
  1447. .process_event = python_process_event,
  1448. .process_stat = python_process_stat,
  1449. .process_stat_interval = python_process_stat_interval,
  1450. .generate_script = python_generate_script,
  1451. };