trace-event-python.c 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209
  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. #ifdef HAVE_LIBTRACEEVENT
  32. #include <event-parse.h>
  33. #endif
  34. #include "../build-id.h"
  35. #include "../counts.h"
  36. #include "../debug.h"
  37. #include "../dso.h"
  38. #include "../callchain.h"
  39. #include "../env.h"
  40. #include "../evsel.h"
  41. #include "../event.h"
  42. #include "../thread.h"
  43. #include "../comm.h"
  44. #include "../machine.h"
  45. #include "../mem-info.h"
  46. #include "../db-export.h"
  47. #include "../thread-stack.h"
  48. #include "../trace-event.h"
  49. #include "../call-path.h"
  50. #include "dwarf-regs.h"
  51. #include "map.h"
  52. #include "symbol.h"
  53. #include "thread_map.h"
  54. #include "print_binary.h"
  55. #include "stat.h"
  56. #include "mem-events.h"
  57. #include "util/perf_regs.h"
  58. #define _PyUnicode_FromString(arg) \
  59. PyUnicode_FromString(arg)
  60. #define _PyUnicode_FromStringAndSize(arg1, arg2) \
  61. PyUnicode_FromStringAndSize((arg1), (arg2))
  62. #define _PyBytes_FromStringAndSize(arg1, arg2) \
  63. PyBytes_FromStringAndSize((arg1), (arg2))
  64. #define _PyLong_FromLong(arg) \
  65. PyLong_FromLong(arg)
  66. #define _PyLong_AsLong(arg) \
  67. PyLong_AsLong(arg)
  68. #define _PyCapsule_New(arg1, arg2, arg3) \
  69. PyCapsule_New((arg1), (arg2), (arg3))
  70. PyMODINIT_FUNC PyInit_perf_trace_context(void);
  71. #ifdef HAVE_LIBTRACEEVENT
  72. #define TRACE_EVENT_TYPE_MAX \
  73. ((1 << (sizeof(unsigned short) * 8)) - 1)
  74. #define N_COMMON_FIELDS 7
  75. static char *cur_field_name;
  76. static int zero_flag_atom;
  77. #endif
  78. #define MAX_FIELDS 64
  79. extern struct scripting_context *scripting_context;
  80. static PyObject *main_module, *main_dict;
  81. struct tables {
  82. struct db_export dbe;
  83. PyObject *evsel_handler;
  84. PyObject *machine_handler;
  85. PyObject *thread_handler;
  86. PyObject *comm_handler;
  87. PyObject *comm_thread_handler;
  88. PyObject *dso_handler;
  89. PyObject *symbol_handler;
  90. PyObject *branch_type_handler;
  91. PyObject *sample_handler;
  92. PyObject *call_path_handler;
  93. PyObject *call_return_handler;
  94. PyObject *synth_handler;
  95. PyObject *context_switch_handler;
  96. bool db_export_mode;
  97. };
  98. static struct tables tables_global;
  99. static void handler_call_die(const char *handler_name) __noreturn;
  100. static void handler_call_die(const char *handler_name)
  101. {
  102. PyErr_Print();
  103. Py_FatalError("problem in Python trace event handler");
  104. // Py_FatalError does not return
  105. // but we have to make the compiler happy
  106. abort();
  107. }
  108. /*
  109. * Insert val into the dictionary and decrement the reference counter.
  110. * This is necessary for dictionaries since PyDict_SetItemString() does not
  111. * steal a reference, as opposed to PyTuple_SetItem().
  112. */
  113. static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
  114. {
  115. PyDict_SetItemString(dict, key, val);
  116. Py_DECREF(val);
  117. }
  118. static PyObject *get_handler(const char *handler_name)
  119. {
  120. PyObject *handler;
  121. handler = PyDict_GetItemString(main_dict, handler_name);
  122. if (handler && !PyCallable_Check(handler))
  123. return NULL;
  124. return handler;
  125. }
  126. static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
  127. {
  128. PyObject *retval;
  129. retval = PyObject_CallObject(handler, args);
  130. if (retval == NULL)
  131. handler_call_die(die_msg);
  132. Py_DECREF(retval);
  133. }
  134. static void try_call_object(const char *handler_name, PyObject *args)
  135. {
  136. PyObject *handler;
  137. handler = get_handler(handler_name);
  138. if (handler)
  139. call_object(handler, args, handler_name);
  140. }
  141. #ifdef HAVE_LIBTRACEEVENT
  142. static int get_argument_count(PyObject *handler)
  143. {
  144. int arg_count = 0;
  145. PyObject *code_obj = code_obj = PyObject_GetAttrString(handler, "__code__");
  146. PyErr_Clear();
  147. if (code_obj) {
  148. PyObject *arg_count_obj = PyObject_GetAttrString(code_obj,
  149. "co_argcount");
  150. if (arg_count_obj) {
  151. arg_count = (int) _PyLong_AsLong(arg_count_obj);
  152. Py_DECREF(arg_count_obj);
  153. }
  154. Py_DECREF(code_obj);
  155. }
  156. return arg_count;
  157. }
  158. static void define_value(enum tep_print_arg_type field_type,
  159. const char *ev_name,
  160. const char *field_name,
  161. const char *field_value,
  162. const char *field_str)
  163. {
  164. const char *handler_name = "define_flag_value";
  165. PyObject *t;
  166. unsigned long long value;
  167. unsigned n = 0;
  168. if (field_type == TEP_PRINT_SYMBOL)
  169. handler_name = "define_symbolic_value";
  170. t = PyTuple_New(4);
  171. if (!t)
  172. Py_FatalError("couldn't create Python tuple");
  173. value = eval_flag(field_value);
  174. PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
  175. PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
  176. PyTuple_SetItem(t, n++, _PyLong_FromLong(value));
  177. PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_str));
  178. try_call_object(handler_name, t);
  179. Py_DECREF(t);
  180. }
  181. static void define_values(enum tep_print_arg_type field_type,
  182. struct tep_print_flag_sym *field,
  183. const char *ev_name,
  184. const char *field_name)
  185. {
  186. define_value(field_type, ev_name, field_name, field->value,
  187. field->str);
  188. if (field->next)
  189. define_values(field_type, field->next, ev_name, field_name);
  190. }
  191. static void define_field(enum tep_print_arg_type field_type,
  192. const char *ev_name,
  193. const char *field_name,
  194. const char *delim)
  195. {
  196. const char *handler_name = "define_flag_field";
  197. PyObject *t;
  198. unsigned n = 0;
  199. if (field_type == TEP_PRINT_SYMBOL)
  200. handler_name = "define_symbolic_field";
  201. if (field_type == TEP_PRINT_FLAGS)
  202. t = PyTuple_New(3);
  203. else
  204. t = PyTuple_New(2);
  205. if (!t)
  206. Py_FatalError("couldn't create Python tuple");
  207. PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
  208. PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
  209. if (field_type == TEP_PRINT_FLAGS)
  210. PyTuple_SetItem(t, n++, _PyUnicode_FromString(delim));
  211. try_call_object(handler_name, t);
  212. Py_DECREF(t);
  213. }
  214. static void define_event_symbols(struct tep_event *event,
  215. const char *ev_name,
  216. struct tep_print_arg *args)
  217. {
  218. if (args == NULL)
  219. return;
  220. switch (args->type) {
  221. case TEP_PRINT_NULL:
  222. break;
  223. case TEP_PRINT_ATOM:
  224. define_value(TEP_PRINT_FLAGS, ev_name, cur_field_name, "0",
  225. args->atom.atom);
  226. zero_flag_atom = 0;
  227. break;
  228. case TEP_PRINT_FIELD:
  229. free(cur_field_name);
  230. cur_field_name = strdup(args->field.name);
  231. break;
  232. case TEP_PRINT_FLAGS:
  233. define_event_symbols(event, ev_name, args->flags.field);
  234. define_field(TEP_PRINT_FLAGS, ev_name, cur_field_name,
  235. args->flags.delim);
  236. define_values(TEP_PRINT_FLAGS, args->flags.flags, ev_name,
  237. cur_field_name);
  238. break;
  239. case TEP_PRINT_SYMBOL:
  240. define_event_symbols(event, ev_name, args->symbol.field);
  241. define_field(TEP_PRINT_SYMBOL, ev_name, cur_field_name, NULL);
  242. define_values(TEP_PRINT_SYMBOL, args->symbol.symbols, ev_name,
  243. cur_field_name);
  244. break;
  245. case TEP_PRINT_HEX:
  246. case TEP_PRINT_HEX_STR:
  247. define_event_symbols(event, ev_name, args->hex.field);
  248. define_event_symbols(event, ev_name, args->hex.size);
  249. break;
  250. case TEP_PRINT_INT_ARRAY:
  251. define_event_symbols(event, ev_name, args->int_array.field);
  252. define_event_symbols(event, ev_name, args->int_array.count);
  253. define_event_symbols(event, ev_name, args->int_array.el_size);
  254. break;
  255. case TEP_PRINT_STRING:
  256. break;
  257. case TEP_PRINT_TYPE:
  258. define_event_symbols(event, ev_name, args->typecast.item);
  259. break;
  260. case TEP_PRINT_OP:
  261. if (strcmp(args->op.op, ":") == 0)
  262. zero_flag_atom = 1;
  263. define_event_symbols(event, ev_name, args->op.left);
  264. define_event_symbols(event, ev_name, args->op.right);
  265. break;
  266. default:
  267. /* gcc warns for these? */
  268. case TEP_PRINT_BSTRING:
  269. case TEP_PRINT_DYNAMIC_ARRAY:
  270. case TEP_PRINT_DYNAMIC_ARRAY_LEN:
  271. case TEP_PRINT_FUNC:
  272. case TEP_PRINT_BITMASK:
  273. /* we should warn... */
  274. return;
  275. }
  276. if (args->next)
  277. define_event_symbols(event, ev_name, args->next);
  278. }
  279. static PyObject *get_field_numeric_entry(struct tep_event *event,
  280. struct tep_format_field *field, void *data)
  281. {
  282. bool is_array = field->flags & TEP_FIELD_IS_ARRAY;
  283. PyObject *obj = NULL, *list = NULL;
  284. unsigned long long val;
  285. unsigned int item_size, n_items, i;
  286. if (is_array) {
  287. list = PyList_New(field->arraylen);
  288. if (!list)
  289. Py_FatalError("couldn't create Python list");
  290. item_size = field->size / field->arraylen;
  291. n_items = field->arraylen;
  292. } else {
  293. item_size = field->size;
  294. n_items = 1;
  295. }
  296. for (i = 0; i < n_items; i++) {
  297. val = read_size(event, data + field->offset + i * item_size,
  298. item_size);
  299. if (field->flags & TEP_FIELD_IS_SIGNED) {
  300. if ((long long)val >= LONG_MIN &&
  301. (long long)val <= LONG_MAX)
  302. obj = _PyLong_FromLong(val);
  303. else
  304. obj = PyLong_FromLongLong(val);
  305. } else {
  306. if (val <= LONG_MAX)
  307. obj = _PyLong_FromLong(val);
  308. else
  309. obj = PyLong_FromUnsignedLongLong(val);
  310. }
  311. if (is_array)
  312. PyList_SET_ITEM(list, i, obj);
  313. }
  314. if (is_array)
  315. obj = list;
  316. return obj;
  317. }
  318. #endif
  319. static const char *get_dsoname(struct map *map)
  320. {
  321. const char *dsoname = "[unknown]";
  322. struct dso *dso = map ? map__dso(map) : NULL;
  323. if (dso) {
  324. if (symbol_conf.show_kernel_path && dso__long_name(dso))
  325. dsoname = dso__long_name(dso);
  326. else
  327. dsoname = dso__name(dso);
  328. }
  329. return dsoname;
  330. }
  331. static unsigned long get_offset(struct symbol *sym, struct addr_location *al)
  332. {
  333. unsigned long offset;
  334. if (al->addr < sym->end)
  335. offset = al->addr - sym->start;
  336. else
  337. offset = al->addr - map__start(al->map) - sym->start;
  338. return offset;
  339. }
  340. static PyObject *python_process_callchain(struct perf_sample *sample,
  341. struct evsel *evsel,
  342. struct addr_location *al)
  343. {
  344. PyObject *pylist;
  345. struct callchain_cursor *cursor;
  346. pylist = PyList_New(0);
  347. if (!pylist)
  348. Py_FatalError("couldn't create Python list");
  349. if (!symbol_conf.use_callchain || !sample->callchain)
  350. goto exit;
  351. cursor = get_tls_callchain_cursor();
  352. if (thread__resolve_callchain(al->thread, cursor, evsel,
  353. sample, NULL, NULL,
  354. scripting_max_stack) != 0) {
  355. pr_err("Failed to resolve callchain. Skipping\n");
  356. goto exit;
  357. }
  358. callchain_cursor_commit(cursor);
  359. while (1) {
  360. PyObject *pyelem;
  361. struct callchain_cursor_node *node;
  362. node = callchain_cursor_current(cursor);
  363. if (!node)
  364. break;
  365. pyelem = PyDict_New();
  366. if (!pyelem)
  367. Py_FatalError("couldn't create Python dictionary");
  368. pydict_set_item_string_decref(pyelem, "ip",
  369. PyLong_FromUnsignedLongLong(node->ip));
  370. if (node->ms.sym) {
  371. PyObject *pysym = PyDict_New();
  372. if (!pysym)
  373. Py_FatalError("couldn't create Python dictionary");
  374. pydict_set_item_string_decref(pysym, "start",
  375. PyLong_FromUnsignedLongLong(node->ms.sym->start));
  376. pydict_set_item_string_decref(pysym, "end",
  377. PyLong_FromUnsignedLongLong(node->ms.sym->end));
  378. pydict_set_item_string_decref(pysym, "binding",
  379. _PyLong_FromLong(node->ms.sym->binding));
  380. pydict_set_item_string_decref(pysym, "name",
  381. _PyUnicode_FromStringAndSize(node->ms.sym->name,
  382. node->ms.sym->namelen));
  383. pydict_set_item_string_decref(pyelem, "sym", pysym);
  384. if (node->ms.map) {
  385. struct map *map = node->ms.map;
  386. struct addr_location node_al;
  387. unsigned long offset;
  388. addr_location__init(&node_al);
  389. node_al.addr = map__map_ip(map, node->ip);
  390. node_al.map = map__get(map);
  391. offset = get_offset(node->ms.sym, &node_al);
  392. addr_location__exit(&node_al);
  393. pydict_set_item_string_decref(
  394. pyelem, "sym_off",
  395. PyLong_FromUnsignedLongLong(offset));
  396. }
  397. if (node->srcline && strcmp(":0", node->srcline)) {
  398. pydict_set_item_string_decref(
  399. pyelem, "sym_srcline",
  400. _PyUnicode_FromString(node->srcline));
  401. }
  402. }
  403. if (node->ms.map) {
  404. const char *dsoname = get_dsoname(node->ms.map);
  405. pydict_set_item_string_decref(pyelem, "dso",
  406. _PyUnicode_FromString(dsoname));
  407. }
  408. callchain_cursor_advance(cursor);
  409. PyList_Append(pylist, pyelem);
  410. Py_DECREF(pyelem);
  411. }
  412. exit:
  413. return pylist;
  414. }
  415. static PyObject *python_process_brstack(struct perf_sample *sample,
  416. struct thread *thread)
  417. {
  418. struct branch_stack *br = sample->branch_stack;
  419. struct branch_entry *entries = perf_sample__branch_entries(sample);
  420. PyObject *pylist;
  421. u64 i;
  422. pylist = PyList_New(0);
  423. if (!pylist)
  424. Py_FatalError("couldn't create Python list");
  425. if (!(br && br->nr))
  426. goto exit;
  427. for (i = 0; i < br->nr; i++) {
  428. PyObject *pyelem;
  429. struct addr_location al;
  430. const char *dsoname;
  431. pyelem = PyDict_New();
  432. if (!pyelem)
  433. Py_FatalError("couldn't create Python dictionary");
  434. pydict_set_item_string_decref(pyelem, "from",
  435. PyLong_FromUnsignedLongLong(entries[i].from));
  436. pydict_set_item_string_decref(pyelem, "to",
  437. PyLong_FromUnsignedLongLong(entries[i].to));
  438. pydict_set_item_string_decref(pyelem, "mispred",
  439. PyBool_FromLong(entries[i].flags.mispred));
  440. pydict_set_item_string_decref(pyelem, "predicted",
  441. PyBool_FromLong(entries[i].flags.predicted));
  442. pydict_set_item_string_decref(pyelem, "in_tx",
  443. PyBool_FromLong(entries[i].flags.in_tx));
  444. pydict_set_item_string_decref(pyelem, "abort",
  445. PyBool_FromLong(entries[i].flags.abort));
  446. pydict_set_item_string_decref(pyelem, "cycles",
  447. PyLong_FromUnsignedLongLong(entries[i].flags.cycles));
  448. addr_location__init(&al);
  449. thread__find_map_fb(thread, sample->cpumode,
  450. entries[i].from, &al);
  451. dsoname = get_dsoname(al.map);
  452. pydict_set_item_string_decref(pyelem, "from_dsoname",
  453. _PyUnicode_FromString(dsoname));
  454. thread__find_map_fb(thread, sample->cpumode,
  455. entries[i].to, &al);
  456. dsoname = get_dsoname(al.map);
  457. pydict_set_item_string_decref(pyelem, "to_dsoname",
  458. _PyUnicode_FromString(dsoname));
  459. addr_location__exit(&al);
  460. PyList_Append(pylist, pyelem);
  461. Py_DECREF(pyelem);
  462. }
  463. exit:
  464. return pylist;
  465. }
  466. static int get_symoff(struct symbol *sym, struct addr_location *al,
  467. bool print_off, char *bf, int size)
  468. {
  469. unsigned long offset;
  470. if (!sym || !sym->name[0])
  471. return scnprintf(bf, size, "%s", "[unknown]");
  472. if (!print_off)
  473. return scnprintf(bf, size, "%s", sym->name);
  474. offset = get_offset(sym, al);
  475. return scnprintf(bf, size, "%s+0x%x", sym->name, offset);
  476. }
  477. static int get_br_mspred(struct branch_flags *flags, char *bf, int size)
  478. {
  479. if (!flags->mispred && !flags->predicted)
  480. return scnprintf(bf, size, "%s", "-");
  481. if (flags->mispred)
  482. return scnprintf(bf, size, "%s", "M");
  483. return scnprintf(bf, size, "%s", "P");
  484. }
  485. static PyObject *python_process_brstacksym(struct perf_sample *sample,
  486. struct thread *thread)
  487. {
  488. struct branch_stack *br = sample->branch_stack;
  489. struct branch_entry *entries = perf_sample__branch_entries(sample);
  490. PyObject *pylist;
  491. u64 i;
  492. char bf[512];
  493. pylist = PyList_New(0);
  494. if (!pylist)
  495. Py_FatalError("couldn't create Python list");
  496. if (!(br && br->nr))
  497. goto exit;
  498. for (i = 0; i < br->nr; i++) {
  499. PyObject *pyelem;
  500. struct addr_location al;
  501. addr_location__init(&al);
  502. pyelem = PyDict_New();
  503. if (!pyelem)
  504. Py_FatalError("couldn't create Python dictionary");
  505. thread__find_symbol_fb(thread, sample->cpumode,
  506. entries[i].from, &al);
  507. get_symoff(al.sym, &al, true, bf, sizeof(bf));
  508. pydict_set_item_string_decref(pyelem, "from",
  509. _PyUnicode_FromString(bf));
  510. thread__find_symbol_fb(thread, sample->cpumode,
  511. entries[i].to, &al);
  512. get_symoff(al.sym, &al, true, bf, sizeof(bf));
  513. pydict_set_item_string_decref(pyelem, "to",
  514. _PyUnicode_FromString(bf));
  515. get_br_mspred(&entries[i].flags, bf, sizeof(bf));
  516. pydict_set_item_string_decref(pyelem, "pred",
  517. _PyUnicode_FromString(bf));
  518. if (entries[i].flags.in_tx) {
  519. pydict_set_item_string_decref(pyelem, "in_tx",
  520. _PyUnicode_FromString("X"));
  521. } else {
  522. pydict_set_item_string_decref(pyelem, "in_tx",
  523. _PyUnicode_FromString("-"));
  524. }
  525. if (entries[i].flags.abort) {
  526. pydict_set_item_string_decref(pyelem, "abort",
  527. _PyUnicode_FromString("A"));
  528. } else {
  529. pydict_set_item_string_decref(pyelem, "abort",
  530. _PyUnicode_FromString("-"));
  531. }
  532. PyList_Append(pylist, pyelem);
  533. Py_DECREF(pyelem);
  534. addr_location__exit(&al);
  535. }
  536. exit:
  537. return pylist;
  538. }
  539. static PyObject *get_sample_value_as_tuple(struct sample_read_value *value,
  540. u64 read_format)
  541. {
  542. PyObject *t;
  543. t = PyTuple_New(3);
  544. if (!t)
  545. Py_FatalError("couldn't create Python tuple");
  546. PyTuple_SetItem(t, 0, PyLong_FromUnsignedLongLong(value->id));
  547. PyTuple_SetItem(t, 1, PyLong_FromUnsignedLongLong(value->value));
  548. if (read_format & PERF_FORMAT_LOST)
  549. PyTuple_SetItem(t, 2, PyLong_FromUnsignedLongLong(value->lost));
  550. return t;
  551. }
  552. static void set_sample_read_in_dict(PyObject *dict_sample,
  553. struct perf_sample *sample,
  554. struct evsel *evsel)
  555. {
  556. u64 read_format = evsel->core.attr.read_format;
  557. PyObject *values;
  558. unsigned int i;
  559. if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
  560. pydict_set_item_string_decref(dict_sample, "time_enabled",
  561. PyLong_FromUnsignedLongLong(sample->read.time_enabled));
  562. }
  563. if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
  564. pydict_set_item_string_decref(dict_sample, "time_running",
  565. PyLong_FromUnsignedLongLong(sample->read.time_running));
  566. }
  567. if (read_format & PERF_FORMAT_GROUP)
  568. values = PyList_New(sample->read.group.nr);
  569. else
  570. values = PyList_New(1);
  571. if (!values)
  572. Py_FatalError("couldn't create Python list");
  573. if (read_format & PERF_FORMAT_GROUP) {
  574. struct sample_read_value *v = sample->read.group.values;
  575. i = 0;
  576. sample_read_group__for_each(v, sample->read.group.nr, read_format) {
  577. PyObject *t = get_sample_value_as_tuple(v, read_format);
  578. PyList_SET_ITEM(values, i, t);
  579. i++;
  580. }
  581. } else {
  582. PyObject *t = get_sample_value_as_tuple(&sample->read.one,
  583. read_format);
  584. PyList_SET_ITEM(values, 0, t);
  585. }
  586. pydict_set_item_string_decref(dict_sample, "values", values);
  587. }
  588. static void set_sample_datasrc_in_dict(PyObject *dict,
  589. struct perf_sample *sample)
  590. {
  591. struct mem_info *mi = mem_info__new();
  592. char decode[100];
  593. if (!mi)
  594. Py_FatalError("couldn't create mem-info");
  595. pydict_set_item_string_decref(dict, "datasrc",
  596. PyLong_FromUnsignedLongLong(sample->data_src));
  597. mem_info__data_src(mi)->val = sample->data_src;
  598. perf_script__meminfo_scnprintf(decode, 100, mi);
  599. mem_info__put(mi);
  600. pydict_set_item_string_decref(dict, "datasrc_decode",
  601. _PyUnicode_FromString(decode));
  602. }
  603. static void regs_map(struct regs_dump *regs, uint64_t mask, uint16_t e_machine, uint32_t e_flags,
  604. char *bf, int size)
  605. {
  606. unsigned int i = 0, r;
  607. int printed = 0;
  608. bf[0] = 0;
  609. if (size <= 0)
  610. return;
  611. if (!regs || !regs->regs)
  612. return;
  613. for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
  614. u64 val = regs->regs[i++];
  615. printed += scnprintf(bf + printed, size - printed,
  616. "%5s:0x%" PRIx64 " ",
  617. perf_reg_name(r, e_machine, e_flags), val);
  618. }
  619. }
  620. #define MAX_REG_SIZE 128
  621. static int set_regs_in_dict(PyObject *dict,
  622. struct perf_sample *sample,
  623. struct evsel *evsel,
  624. uint16_t e_machine,
  625. uint32_t e_flags)
  626. {
  627. struct perf_event_attr *attr = &evsel->core.attr;
  628. int size = (__sw_hweight64(attr->sample_regs_intr) * MAX_REG_SIZE) + 1;
  629. char *bf = NULL;
  630. if (sample->intr_regs) {
  631. bf = malloc(size);
  632. if (!bf)
  633. return -1;
  634. regs_map(sample->intr_regs, attr->sample_regs_intr, e_machine, e_flags, bf, size);
  635. pydict_set_item_string_decref(dict, "iregs",
  636. _PyUnicode_FromString(bf));
  637. }
  638. if (sample->user_regs) {
  639. if (!bf) {
  640. bf = malloc(size);
  641. if (!bf)
  642. return -1;
  643. }
  644. regs_map(sample->user_regs, attr->sample_regs_user, e_machine, e_flags, bf, size);
  645. pydict_set_item_string_decref(dict, "uregs",
  646. _PyUnicode_FromString(bf));
  647. }
  648. free(bf);
  649. return 0;
  650. }
  651. static void set_sym_in_dict(PyObject *dict, struct addr_location *al,
  652. const char *dso_field, const char *dso_bid_field,
  653. const char *dso_map_start, const char *dso_map_end,
  654. const char *sym_field, const char *symoff_field,
  655. const char *map_pgoff)
  656. {
  657. if (al->map) {
  658. char sbuild_id[SBUILD_ID_SIZE];
  659. struct dso *dso = map__dso(al->map);
  660. pydict_set_item_string_decref(dict, dso_field,
  661. _PyUnicode_FromString(dso__name(dso)));
  662. build_id__snprintf(dso__bid(dso), sbuild_id, sizeof(sbuild_id));
  663. pydict_set_item_string_decref(dict, dso_bid_field,
  664. _PyUnicode_FromString(sbuild_id));
  665. pydict_set_item_string_decref(dict, dso_map_start,
  666. PyLong_FromUnsignedLong(map__start(al->map)));
  667. pydict_set_item_string_decref(dict, dso_map_end,
  668. PyLong_FromUnsignedLong(map__end(al->map)));
  669. pydict_set_item_string_decref(dict, map_pgoff,
  670. PyLong_FromUnsignedLongLong(map__pgoff(al->map)));
  671. }
  672. if (al->sym) {
  673. pydict_set_item_string_decref(dict, sym_field,
  674. _PyUnicode_FromString(al->sym->name));
  675. pydict_set_item_string_decref(dict, symoff_field,
  676. PyLong_FromUnsignedLong(get_offset(al->sym, al)));
  677. }
  678. }
  679. static void set_sample_flags(PyObject *dict, u32 flags)
  680. {
  681. const char *ch = PERF_IP_FLAG_CHARS;
  682. char *p, str[33];
  683. for (p = str; *ch; ch++, flags >>= 1) {
  684. if (flags & 1)
  685. *p++ = *ch;
  686. }
  687. *p = 0;
  688. pydict_set_item_string_decref(dict, "flags", _PyUnicode_FromString(str));
  689. }
  690. static void python_process_sample_flags(struct perf_sample *sample, PyObject *dict_sample)
  691. {
  692. char flags_disp[SAMPLE_FLAGS_BUF_SIZE];
  693. set_sample_flags(dict_sample, sample->flags);
  694. perf_sample__sprintf_flags(sample->flags, flags_disp, sizeof(flags_disp));
  695. pydict_set_item_string_decref(dict_sample, "flags_disp",
  696. _PyUnicode_FromString(flags_disp));
  697. }
  698. static PyObject *get_perf_sample_dict(struct perf_sample *sample,
  699. struct evsel *evsel,
  700. struct addr_location *al,
  701. struct addr_location *addr_al,
  702. PyObject *callchain)
  703. {
  704. PyObject *dict, *dict_sample, *brstack, *brstacksym;
  705. uint16_t e_machine = EM_HOST;
  706. uint32_t e_flags = EF_HOST;
  707. dict = PyDict_New();
  708. if (!dict)
  709. Py_FatalError("couldn't create Python dictionary");
  710. dict_sample = PyDict_New();
  711. if (!dict_sample)
  712. Py_FatalError("couldn't create Python dictionary");
  713. pydict_set_item_string_decref(dict, "ev_name", _PyUnicode_FromString(evsel__name(evsel)));
  714. pydict_set_item_string_decref(dict, "attr", _PyBytes_FromStringAndSize((const char *)&evsel->core.attr, sizeof(evsel->core.attr)));
  715. pydict_set_item_string_decref(dict_sample, "id",
  716. PyLong_FromUnsignedLongLong(sample->id));
  717. pydict_set_item_string_decref(dict_sample, "stream_id",
  718. PyLong_FromUnsignedLongLong(sample->stream_id));
  719. pydict_set_item_string_decref(dict_sample, "pid",
  720. _PyLong_FromLong(sample->pid));
  721. pydict_set_item_string_decref(dict_sample, "tid",
  722. _PyLong_FromLong(sample->tid));
  723. pydict_set_item_string_decref(dict_sample, "cpu",
  724. _PyLong_FromLong(sample->cpu));
  725. pydict_set_item_string_decref(dict_sample, "ip",
  726. PyLong_FromUnsignedLongLong(sample->ip));
  727. pydict_set_item_string_decref(dict_sample, "time",
  728. PyLong_FromUnsignedLongLong(sample->time));
  729. pydict_set_item_string_decref(dict_sample, "period",
  730. PyLong_FromUnsignedLongLong(sample->period));
  731. pydict_set_item_string_decref(dict_sample, "phys_addr",
  732. PyLong_FromUnsignedLongLong(sample->phys_addr));
  733. pydict_set_item_string_decref(dict_sample, "addr",
  734. PyLong_FromUnsignedLongLong(sample->addr));
  735. set_sample_read_in_dict(dict_sample, sample, evsel);
  736. pydict_set_item_string_decref(dict_sample, "weight",
  737. PyLong_FromUnsignedLongLong(sample->weight));
  738. pydict_set_item_string_decref(dict_sample, "ins_lat",
  739. PyLong_FromUnsignedLong(sample->ins_lat));
  740. pydict_set_item_string_decref(dict_sample, "transaction",
  741. PyLong_FromUnsignedLongLong(sample->transaction));
  742. set_sample_datasrc_in_dict(dict_sample, sample);
  743. pydict_set_item_string_decref(dict, "sample", dict_sample);
  744. pydict_set_item_string_decref(dict, "raw_buf", _PyBytes_FromStringAndSize(
  745. (const char *)sample->raw_data, sample->raw_size));
  746. pydict_set_item_string_decref(dict, "comm",
  747. _PyUnicode_FromString(thread__comm_str(al->thread)));
  748. set_sym_in_dict(dict, al, "dso", "dso_bid", "dso_map_start", "dso_map_end",
  749. "symbol", "symoff", "map_pgoff");
  750. pydict_set_item_string_decref(dict, "callchain", callchain);
  751. brstack = python_process_brstack(sample, al->thread);
  752. pydict_set_item_string_decref(dict, "brstack", brstack);
  753. brstacksym = python_process_brstacksym(sample, al->thread);
  754. pydict_set_item_string_decref(dict, "brstacksym", brstacksym);
  755. if (sample->machine_pid) {
  756. pydict_set_item_string_decref(dict_sample, "machine_pid",
  757. _PyLong_FromLong(sample->machine_pid));
  758. pydict_set_item_string_decref(dict_sample, "vcpu",
  759. _PyLong_FromLong(sample->vcpu));
  760. }
  761. pydict_set_item_string_decref(dict_sample, "cpumode",
  762. _PyLong_FromLong((unsigned long)sample->cpumode));
  763. if (addr_al) {
  764. pydict_set_item_string_decref(dict_sample, "addr_correlates_sym",
  765. PyBool_FromLong(1));
  766. set_sym_in_dict(dict_sample, addr_al, "addr_dso", "addr_dso_bid",
  767. "addr_dso_map_start", "addr_dso_map_end",
  768. "addr_symbol", "addr_symoff", "addr_map_pgoff");
  769. }
  770. if (sample->flags)
  771. python_process_sample_flags(sample, dict_sample);
  772. /* Instructions per cycle (IPC) */
  773. if (sample->insn_cnt && sample->cyc_cnt) {
  774. pydict_set_item_string_decref(dict_sample, "insn_cnt",
  775. PyLong_FromUnsignedLongLong(sample->insn_cnt));
  776. pydict_set_item_string_decref(dict_sample, "cyc_cnt",
  777. PyLong_FromUnsignedLongLong(sample->cyc_cnt));
  778. }
  779. if (al->thread)
  780. e_machine = thread__e_machine(al->thread, /*machine=*/NULL, &e_flags);
  781. if (set_regs_in_dict(dict, sample, evsel, e_machine, e_flags))
  782. Py_FatalError("Failed to setting regs in dict");
  783. return dict;
  784. }
  785. #ifdef HAVE_LIBTRACEEVENT
  786. static void python_process_tracepoint(struct perf_sample *sample,
  787. struct evsel *evsel,
  788. struct addr_location *al,
  789. struct addr_location *addr_al)
  790. {
  791. struct tep_event *event;
  792. PyObject *handler, *context, *t, *obj = NULL, *callchain;
  793. PyObject *dict = NULL, *all_entries_dict = NULL;
  794. static char handler_name[256];
  795. struct tep_format_field *field;
  796. unsigned long s, ns;
  797. unsigned n = 0;
  798. int pid;
  799. int cpu = sample->cpu;
  800. void *data = sample->raw_data;
  801. unsigned long long nsecs = sample->time;
  802. const char *comm = thread__comm_str(al->thread);
  803. const char *default_handler_name = "trace_unhandled";
  804. DECLARE_BITMAP(events_defined, TRACE_EVENT_TYPE_MAX);
  805. bitmap_zero(events_defined, TRACE_EVENT_TYPE_MAX);
  806. event = evsel__tp_format(evsel);
  807. if (!event) {
  808. snprintf(handler_name, sizeof(handler_name),
  809. "ug! no event found for type %" PRIu64, (u64)evsel->core.attr.config);
  810. Py_FatalError(handler_name);
  811. }
  812. pid = raw_field_value(event, "common_pid", data);
  813. sprintf(handler_name, "%s__%s", event->system, event->name);
  814. if (!__test_and_set_bit(event->id, events_defined))
  815. define_event_symbols(event, handler_name, event->print_fmt.args);
  816. handler = get_handler(handler_name);
  817. if (!handler) {
  818. handler = get_handler(default_handler_name);
  819. if (!handler)
  820. return;
  821. dict = PyDict_New();
  822. if (!dict)
  823. Py_FatalError("couldn't create Python dict");
  824. }
  825. t = PyTuple_New(MAX_FIELDS);
  826. if (!t)
  827. Py_FatalError("couldn't create Python tuple");
  828. s = nsecs / NSEC_PER_SEC;
  829. ns = nsecs - s * NSEC_PER_SEC;
  830. context = _PyCapsule_New(scripting_context, NULL, NULL);
  831. PyTuple_SetItem(t, n++, _PyUnicode_FromString(handler_name));
  832. PyTuple_SetItem(t, n++, context);
  833. /* ip unwinding */
  834. callchain = python_process_callchain(sample, evsel, al);
  835. /* Need an additional reference for the perf_sample dict */
  836. Py_INCREF(callchain);
  837. if (!dict) {
  838. PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
  839. PyTuple_SetItem(t, n++, _PyLong_FromLong(s));
  840. PyTuple_SetItem(t, n++, _PyLong_FromLong(ns));
  841. PyTuple_SetItem(t, n++, _PyLong_FromLong(pid));
  842. PyTuple_SetItem(t, n++, _PyUnicode_FromString(comm));
  843. PyTuple_SetItem(t, n++, callchain);
  844. } else {
  845. pydict_set_item_string_decref(dict, "common_cpu", _PyLong_FromLong(cpu));
  846. pydict_set_item_string_decref(dict, "common_s", _PyLong_FromLong(s));
  847. pydict_set_item_string_decref(dict, "common_ns", _PyLong_FromLong(ns));
  848. pydict_set_item_string_decref(dict, "common_pid", _PyLong_FromLong(pid));
  849. pydict_set_item_string_decref(dict, "common_comm", _PyUnicode_FromString(comm));
  850. pydict_set_item_string_decref(dict, "common_callchain", callchain);
  851. }
  852. for (field = event->format.fields; field; field = field->next) {
  853. unsigned int offset, len;
  854. unsigned long long val;
  855. if (field->flags & TEP_FIELD_IS_ARRAY) {
  856. offset = field->offset;
  857. len = field->size;
  858. if (field->flags & TEP_FIELD_IS_DYNAMIC) {
  859. val = tep_read_number(scripting_context->pevent,
  860. data + offset, len);
  861. offset = val;
  862. len = offset >> 16;
  863. offset &= 0xffff;
  864. if (tep_field_is_relative(field->flags))
  865. offset += field->offset + field->size;
  866. }
  867. if (field->flags & TEP_FIELD_IS_STRING &&
  868. is_printable_array(data + offset, len)) {
  869. obj = _PyUnicode_FromString((char *) data + offset);
  870. } else {
  871. obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
  872. field->flags &= ~TEP_FIELD_IS_STRING;
  873. }
  874. } else { /* FIELD_IS_NUMERIC */
  875. obj = get_field_numeric_entry(event, field, data);
  876. }
  877. if (!dict)
  878. PyTuple_SetItem(t, n++, obj);
  879. else
  880. pydict_set_item_string_decref(dict, field->name, obj);
  881. }
  882. if (dict)
  883. PyTuple_SetItem(t, n++, dict);
  884. if (get_argument_count(handler) == (int) n + 1) {
  885. all_entries_dict = get_perf_sample_dict(sample, evsel, al, addr_al,
  886. callchain);
  887. PyTuple_SetItem(t, n++, all_entries_dict);
  888. } else {
  889. Py_DECREF(callchain);
  890. }
  891. if (_PyTuple_Resize(&t, n) == -1)
  892. Py_FatalError("error resizing Python tuple");
  893. if (!dict)
  894. call_object(handler, t, handler_name);
  895. else
  896. call_object(handler, t, default_handler_name);
  897. Py_DECREF(t);
  898. }
  899. #else
  900. static void python_process_tracepoint(struct perf_sample *sample __maybe_unused,
  901. struct evsel *evsel __maybe_unused,
  902. struct addr_location *al __maybe_unused,
  903. struct addr_location *addr_al __maybe_unused)
  904. {
  905. fprintf(stderr, "Tracepoint events are not supported because "
  906. "perf is not linked with libtraceevent.\n");
  907. }
  908. #endif
  909. static PyObject *tuple_new(unsigned int sz)
  910. {
  911. PyObject *t;
  912. t = PyTuple_New(sz);
  913. if (!t)
  914. Py_FatalError("couldn't create Python tuple");
  915. return t;
  916. }
  917. static int tuple_set_s64(PyObject *t, unsigned int pos, s64 val)
  918. {
  919. #if BITS_PER_LONG == 64
  920. return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
  921. #endif
  922. #if BITS_PER_LONG == 32
  923. return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
  924. #endif
  925. }
  926. /*
  927. * Databases support only signed 64-bit numbers, so even though we are
  928. * exporting a u64, it must be as s64.
  929. */
  930. #define tuple_set_d64 tuple_set_s64
  931. static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
  932. {
  933. #if BITS_PER_LONG == 64
  934. return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
  935. #endif
  936. #if BITS_PER_LONG == 32
  937. return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLongLong(val));
  938. #endif
  939. }
  940. static int tuple_set_u32(PyObject *t, unsigned int pos, u32 val)
  941. {
  942. return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
  943. }
  944. static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
  945. {
  946. return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
  947. }
  948. static int tuple_set_bool(PyObject *t, unsigned int pos, bool val)
  949. {
  950. return PyTuple_SetItem(t, pos, PyBool_FromLong(val));
  951. }
  952. static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
  953. {
  954. return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
  955. }
  956. static int tuple_set_bytes(PyObject *t, unsigned int pos, void *bytes,
  957. unsigned int sz)
  958. {
  959. return PyTuple_SetItem(t, pos, _PyBytes_FromStringAndSize(bytes, sz));
  960. }
  961. static int python_export_evsel(struct db_export *dbe, struct evsel *evsel)
  962. {
  963. struct tables *tables = container_of(dbe, struct tables, dbe);
  964. PyObject *t;
  965. t = tuple_new(2);
  966. tuple_set_d64(t, 0, evsel->db_id);
  967. tuple_set_string(t, 1, evsel__name(evsel));
  968. call_object(tables->evsel_handler, t, "evsel_table");
  969. Py_DECREF(t);
  970. return 0;
  971. }
  972. static int python_export_machine(struct db_export *dbe,
  973. struct machine *machine)
  974. {
  975. struct tables *tables = container_of(dbe, struct tables, dbe);
  976. PyObject *t;
  977. t = tuple_new(3);
  978. tuple_set_d64(t, 0, machine->db_id);
  979. tuple_set_s32(t, 1, machine->pid);
  980. tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
  981. call_object(tables->machine_handler, t, "machine_table");
  982. Py_DECREF(t);
  983. return 0;
  984. }
  985. static int python_export_thread(struct db_export *dbe, struct thread *thread,
  986. u64 main_thread_db_id, struct machine *machine)
  987. {
  988. struct tables *tables = container_of(dbe, struct tables, dbe);
  989. PyObject *t;
  990. t = tuple_new(5);
  991. tuple_set_d64(t, 0, thread__db_id(thread));
  992. tuple_set_d64(t, 1, machine->db_id);
  993. tuple_set_d64(t, 2, main_thread_db_id);
  994. tuple_set_s32(t, 3, thread__pid(thread));
  995. tuple_set_s32(t, 4, thread__tid(thread));
  996. call_object(tables->thread_handler, t, "thread_table");
  997. Py_DECREF(t);
  998. return 0;
  999. }
  1000. static int python_export_comm(struct db_export *dbe, struct comm *comm,
  1001. struct thread *thread)
  1002. {
  1003. struct tables *tables = container_of(dbe, struct tables, dbe);
  1004. PyObject *t;
  1005. t = tuple_new(5);
  1006. tuple_set_d64(t, 0, comm->db_id);
  1007. tuple_set_string(t, 1, comm__str(comm));
  1008. tuple_set_d64(t, 2, thread__db_id(thread));
  1009. tuple_set_d64(t, 3, comm->start);
  1010. tuple_set_s32(t, 4, comm->exec);
  1011. call_object(tables->comm_handler, t, "comm_table");
  1012. Py_DECREF(t);
  1013. return 0;
  1014. }
  1015. static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
  1016. struct comm *comm, struct thread *thread)
  1017. {
  1018. struct tables *tables = container_of(dbe, struct tables, dbe);
  1019. PyObject *t;
  1020. t = tuple_new(3);
  1021. tuple_set_d64(t, 0, db_id);
  1022. tuple_set_d64(t, 1, comm->db_id);
  1023. tuple_set_d64(t, 2, thread__db_id(thread));
  1024. call_object(tables->comm_thread_handler, t, "comm_thread_table");
  1025. Py_DECREF(t);
  1026. return 0;
  1027. }
  1028. static int python_export_dso(struct db_export *dbe, struct dso *dso,
  1029. struct machine *machine)
  1030. {
  1031. struct tables *tables = container_of(dbe, struct tables, dbe);
  1032. char sbuild_id[SBUILD_ID_SIZE];
  1033. PyObject *t;
  1034. build_id__snprintf(dso__bid(dso), sbuild_id, sizeof(sbuild_id));
  1035. t = tuple_new(5);
  1036. tuple_set_d64(t, 0, dso__db_id(dso));
  1037. tuple_set_d64(t, 1, machine->db_id);
  1038. tuple_set_string(t, 2, dso__short_name(dso));
  1039. tuple_set_string(t, 3, dso__long_name(dso));
  1040. tuple_set_string(t, 4, sbuild_id);
  1041. call_object(tables->dso_handler, t, "dso_table");
  1042. Py_DECREF(t);
  1043. return 0;
  1044. }
  1045. static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
  1046. struct dso *dso)
  1047. {
  1048. struct tables *tables = container_of(dbe, struct tables, dbe);
  1049. u64 *sym_db_id = symbol__priv(sym);
  1050. PyObject *t;
  1051. t = tuple_new(6);
  1052. tuple_set_d64(t, 0, *sym_db_id);
  1053. tuple_set_d64(t, 1, dso__db_id(dso));
  1054. tuple_set_d64(t, 2, sym->start);
  1055. tuple_set_d64(t, 3, sym->end);
  1056. tuple_set_s32(t, 4, sym->binding);
  1057. tuple_set_string(t, 5, sym->name);
  1058. call_object(tables->symbol_handler, t, "symbol_table");
  1059. Py_DECREF(t);
  1060. return 0;
  1061. }
  1062. static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
  1063. const char *name)
  1064. {
  1065. struct tables *tables = container_of(dbe, struct tables, dbe);
  1066. PyObject *t;
  1067. t = tuple_new(2);
  1068. tuple_set_s32(t, 0, branch_type);
  1069. tuple_set_string(t, 1, name);
  1070. call_object(tables->branch_type_handler, t, "branch_type_table");
  1071. Py_DECREF(t);
  1072. return 0;
  1073. }
  1074. static void python_export_sample_table(struct db_export *dbe,
  1075. struct export_sample *es)
  1076. {
  1077. struct tables *tables = container_of(dbe, struct tables, dbe);
  1078. PyObject *t;
  1079. t = tuple_new(28);
  1080. tuple_set_d64(t, 0, es->db_id);
  1081. tuple_set_d64(t, 1, es->evsel->db_id);
  1082. tuple_set_d64(t, 2, maps__machine(thread__maps(es->al->thread))->db_id);
  1083. tuple_set_d64(t, 3, thread__db_id(es->al->thread));
  1084. tuple_set_d64(t, 4, es->comm_db_id);
  1085. tuple_set_d64(t, 5, es->dso_db_id);
  1086. tuple_set_d64(t, 6, es->sym_db_id);
  1087. tuple_set_d64(t, 7, es->offset);
  1088. tuple_set_d64(t, 8, es->sample->ip);
  1089. tuple_set_d64(t, 9, es->sample->time);
  1090. tuple_set_s32(t, 10, es->sample->cpu);
  1091. tuple_set_d64(t, 11, es->addr_dso_db_id);
  1092. tuple_set_d64(t, 12, es->addr_sym_db_id);
  1093. tuple_set_d64(t, 13, es->addr_offset);
  1094. tuple_set_d64(t, 14, es->sample->addr);
  1095. tuple_set_d64(t, 15, es->sample->period);
  1096. tuple_set_d64(t, 16, es->sample->weight);
  1097. tuple_set_d64(t, 17, es->sample->transaction);
  1098. tuple_set_d64(t, 18, es->sample->data_src);
  1099. tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
  1100. tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
  1101. tuple_set_d64(t, 21, es->call_path_id);
  1102. tuple_set_d64(t, 22, es->sample->insn_cnt);
  1103. tuple_set_d64(t, 23, es->sample->cyc_cnt);
  1104. tuple_set_s32(t, 24, es->sample->flags);
  1105. tuple_set_d64(t, 25, es->sample->id);
  1106. tuple_set_d64(t, 26, es->sample->stream_id);
  1107. tuple_set_u32(t, 27, es->sample->ins_lat);
  1108. call_object(tables->sample_handler, t, "sample_table");
  1109. Py_DECREF(t);
  1110. }
  1111. static void python_export_synth(struct db_export *dbe, struct export_sample *es)
  1112. {
  1113. struct tables *tables = container_of(dbe, struct tables, dbe);
  1114. PyObject *t;
  1115. t = tuple_new(3);
  1116. tuple_set_d64(t, 0, es->db_id);
  1117. tuple_set_d64(t, 1, es->evsel->core.attr.config);
  1118. tuple_set_bytes(t, 2, es->sample->raw_data, es->sample->raw_size);
  1119. call_object(tables->synth_handler, t, "synth_data");
  1120. Py_DECREF(t);
  1121. }
  1122. static int python_export_sample(struct db_export *dbe,
  1123. struct export_sample *es)
  1124. {
  1125. struct tables *tables = container_of(dbe, struct tables, dbe);
  1126. python_export_sample_table(dbe, es);
  1127. if (es->evsel->core.attr.type == PERF_TYPE_SYNTH && tables->synth_handler)
  1128. python_export_synth(dbe, es);
  1129. return 0;
  1130. }
  1131. static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
  1132. {
  1133. struct tables *tables = container_of(dbe, struct tables, dbe);
  1134. PyObject *t;
  1135. u64 parent_db_id, sym_db_id;
  1136. parent_db_id = cp->parent ? cp->parent->db_id : 0;
  1137. sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
  1138. t = tuple_new(4);
  1139. tuple_set_d64(t, 0, cp->db_id);
  1140. tuple_set_d64(t, 1, parent_db_id);
  1141. tuple_set_d64(t, 2, sym_db_id);
  1142. tuple_set_d64(t, 3, cp->ip);
  1143. call_object(tables->call_path_handler, t, "call_path_table");
  1144. Py_DECREF(t);
  1145. return 0;
  1146. }
  1147. static int python_export_call_return(struct db_export *dbe,
  1148. struct call_return *cr)
  1149. {
  1150. struct tables *tables = container_of(dbe, struct tables, dbe);
  1151. u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
  1152. PyObject *t;
  1153. t = tuple_new(14);
  1154. tuple_set_d64(t, 0, cr->db_id);
  1155. tuple_set_d64(t, 1, thread__db_id(cr->thread));
  1156. tuple_set_d64(t, 2, comm_db_id);
  1157. tuple_set_d64(t, 3, cr->cp->db_id);
  1158. tuple_set_d64(t, 4, cr->call_time);
  1159. tuple_set_d64(t, 5, cr->return_time);
  1160. tuple_set_d64(t, 6, cr->branch_count);
  1161. tuple_set_d64(t, 7, cr->call_ref);
  1162. tuple_set_d64(t, 8, cr->return_ref);
  1163. tuple_set_d64(t, 9, cr->cp->parent->db_id);
  1164. tuple_set_s32(t, 10, cr->flags);
  1165. tuple_set_d64(t, 11, cr->parent_db_id);
  1166. tuple_set_d64(t, 12, cr->insn_count);
  1167. tuple_set_d64(t, 13, cr->cyc_count);
  1168. call_object(tables->call_return_handler, t, "call_return_table");
  1169. Py_DECREF(t);
  1170. return 0;
  1171. }
  1172. static int python_export_context_switch(struct db_export *dbe, u64 db_id,
  1173. struct machine *machine,
  1174. struct perf_sample *sample,
  1175. u64 th_out_id, u64 comm_out_id,
  1176. u64 th_in_id, u64 comm_in_id, int flags)
  1177. {
  1178. struct tables *tables = container_of(dbe, struct tables, dbe);
  1179. PyObject *t;
  1180. t = tuple_new(9);
  1181. tuple_set_d64(t, 0, db_id);
  1182. tuple_set_d64(t, 1, machine->db_id);
  1183. tuple_set_d64(t, 2, sample->time);
  1184. tuple_set_s32(t, 3, sample->cpu);
  1185. tuple_set_d64(t, 4, th_out_id);
  1186. tuple_set_d64(t, 5, comm_out_id);
  1187. tuple_set_d64(t, 6, th_in_id);
  1188. tuple_set_d64(t, 7, comm_in_id);
  1189. tuple_set_s32(t, 8, flags);
  1190. call_object(tables->context_switch_handler, t, "context_switch");
  1191. Py_DECREF(t);
  1192. return 0;
  1193. }
  1194. static int python_process_call_return(struct call_return *cr, u64 *parent_db_id,
  1195. void *data)
  1196. {
  1197. struct db_export *dbe = data;
  1198. return db_export__call_return(dbe, cr, parent_db_id);
  1199. }
  1200. static void python_process_general_event(struct perf_sample *sample,
  1201. struct evsel *evsel,
  1202. struct addr_location *al,
  1203. struct addr_location *addr_al)
  1204. {
  1205. PyObject *handler, *t, *dict, *callchain;
  1206. static char handler_name[64];
  1207. unsigned n = 0;
  1208. snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
  1209. handler = get_handler(handler_name);
  1210. if (!handler)
  1211. return;
  1212. /*
  1213. * Use the MAX_FIELDS to make the function expandable, though
  1214. * currently there is only one item for the tuple.
  1215. */
  1216. t = PyTuple_New(MAX_FIELDS);
  1217. if (!t)
  1218. Py_FatalError("couldn't create Python tuple");
  1219. /* ip unwinding */
  1220. callchain = python_process_callchain(sample, evsel, al);
  1221. dict = get_perf_sample_dict(sample, evsel, al, addr_al, callchain);
  1222. PyTuple_SetItem(t, n++, dict);
  1223. if (_PyTuple_Resize(&t, n) == -1)
  1224. Py_FatalError("error resizing Python tuple");
  1225. call_object(handler, t, handler_name);
  1226. Py_DECREF(t);
  1227. }
  1228. static void python_process_event(union perf_event *event,
  1229. struct perf_sample *sample,
  1230. struct evsel *evsel,
  1231. struct addr_location *al,
  1232. struct addr_location *addr_al)
  1233. {
  1234. struct tables *tables = &tables_global;
  1235. scripting_context__update(scripting_context, event, sample, evsel, al, addr_al);
  1236. switch (evsel->core.attr.type) {
  1237. case PERF_TYPE_TRACEPOINT:
  1238. python_process_tracepoint(sample, evsel, al, addr_al);
  1239. break;
  1240. /* Reserve for future process_hw/sw/raw APIs */
  1241. default:
  1242. if (tables->db_export_mode)
  1243. db_export__sample(&tables->dbe, event, sample, evsel, al, addr_al);
  1244. else
  1245. python_process_general_event(sample, evsel, al, addr_al);
  1246. }
  1247. }
  1248. static void python_process_throttle(union perf_event *event,
  1249. struct perf_sample *sample,
  1250. struct machine *machine)
  1251. {
  1252. const char *handler_name;
  1253. PyObject *handler, *t;
  1254. if (event->header.type == PERF_RECORD_THROTTLE)
  1255. handler_name = "throttle";
  1256. else
  1257. handler_name = "unthrottle";
  1258. handler = get_handler(handler_name);
  1259. if (!handler)
  1260. return;
  1261. t = tuple_new(6);
  1262. if (!t)
  1263. return;
  1264. tuple_set_u64(t, 0, event->throttle.time);
  1265. tuple_set_u64(t, 1, event->throttle.id);
  1266. tuple_set_u64(t, 2, event->throttle.stream_id);
  1267. tuple_set_s32(t, 3, sample->cpu);
  1268. tuple_set_s32(t, 4, sample->pid);
  1269. tuple_set_s32(t, 5, sample->tid);
  1270. call_object(handler, t, handler_name);
  1271. Py_DECREF(t);
  1272. }
  1273. static void python_do_process_switch(union perf_event *event,
  1274. struct perf_sample *sample,
  1275. struct machine *machine)
  1276. {
  1277. const char *handler_name = "context_switch";
  1278. bool out = event->header.misc & PERF_RECORD_MISC_SWITCH_OUT;
  1279. bool out_preempt = out && (event->header.misc & PERF_RECORD_MISC_SWITCH_OUT_PREEMPT);
  1280. pid_t np_pid = -1, np_tid = -1;
  1281. PyObject *handler, *t;
  1282. handler = get_handler(handler_name);
  1283. if (!handler)
  1284. return;
  1285. if (event->header.type == PERF_RECORD_SWITCH_CPU_WIDE) {
  1286. np_pid = event->context_switch.next_prev_pid;
  1287. np_tid = event->context_switch.next_prev_tid;
  1288. }
  1289. t = tuple_new(11);
  1290. if (!t)
  1291. return;
  1292. tuple_set_u64(t, 0, sample->time);
  1293. tuple_set_s32(t, 1, sample->cpu);
  1294. tuple_set_s32(t, 2, sample->pid);
  1295. tuple_set_s32(t, 3, sample->tid);
  1296. tuple_set_s32(t, 4, np_pid);
  1297. tuple_set_s32(t, 5, np_tid);
  1298. tuple_set_s32(t, 6, machine->pid);
  1299. tuple_set_bool(t, 7, out);
  1300. tuple_set_bool(t, 8, out_preempt);
  1301. tuple_set_s32(t, 9, sample->machine_pid);
  1302. tuple_set_s32(t, 10, sample->vcpu);
  1303. call_object(handler, t, handler_name);
  1304. Py_DECREF(t);
  1305. }
  1306. static void python_process_switch(union perf_event *event,
  1307. struct perf_sample *sample,
  1308. struct machine *machine)
  1309. {
  1310. struct tables *tables = &tables_global;
  1311. if (tables->db_export_mode)
  1312. db_export__switch(&tables->dbe, event, sample, machine);
  1313. else
  1314. python_do_process_switch(event, sample, machine);
  1315. }
  1316. static void python_process_auxtrace_error(struct perf_session *session __maybe_unused,
  1317. union perf_event *event)
  1318. {
  1319. struct perf_record_auxtrace_error *e = &event->auxtrace_error;
  1320. u8 cpumode = e->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
  1321. const char *handler_name = "auxtrace_error";
  1322. unsigned long long tm = e->time;
  1323. const char *msg = e->msg;
  1324. PyObject *handler, *t;
  1325. handler = get_handler(handler_name);
  1326. if (!handler)
  1327. return;
  1328. if (!e->fmt) {
  1329. tm = 0;
  1330. msg = (const char *)&e->time;
  1331. }
  1332. t = tuple_new(11);
  1333. tuple_set_u32(t, 0, e->type);
  1334. tuple_set_u32(t, 1, e->code);
  1335. tuple_set_s32(t, 2, e->cpu);
  1336. tuple_set_s32(t, 3, e->pid);
  1337. tuple_set_s32(t, 4, e->tid);
  1338. tuple_set_u64(t, 5, e->ip);
  1339. tuple_set_u64(t, 6, tm);
  1340. tuple_set_string(t, 7, msg);
  1341. tuple_set_u32(t, 8, cpumode);
  1342. tuple_set_s32(t, 9, e->machine_pid);
  1343. tuple_set_s32(t, 10, e->vcpu);
  1344. call_object(handler, t, handler_name);
  1345. Py_DECREF(t);
  1346. }
  1347. static void get_handler_name(char *str, size_t size,
  1348. struct evsel *evsel)
  1349. {
  1350. char *p = str;
  1351. scnprintf(str, size, "stat__%s", evsel__name(evsel));
  1352. while ((p = strchr(p, ':'))) {
  1353. *p = '_';
  1354. p++;
  1355. }
  1356. }
  1357. static void
  1358. process_stat(struct evsel *counter, struct perf_cpu cpu, int thread, u64 tstamp,
  1359. struct perf_counts_values *count)
  1360. {
  1361. PyObject *handler, *t;
  1362. static char handler_name[256];
  1363. int n = 0;
  1364. t = PyTuple_New(MAX_FIELDS);
  1365. if (!t)
  1366. Py_FatalError("couldn't create Python tuple");
  1367. get_handler_name(handler_name, sizeof(handler_name),
  1368. counter);
  1369. handler = get_handler(handler_name);
  1370. if (!handler) {
  1371. pr_debug("can't find python handler %s\n", handler_name);
  1372. return;
  1373. }
  1374. PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu.cpu));
  1375. PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
  1376. tuple_set_u64(t, n++, tstamp);
  1377. tuple_set_u64(t, n++, count->val);
  1378. tuple_set_u64(t, n++, count->ena);
  1379. tuple_set_u64(t, n++, count->run);
  1380. if (_PyTuple_Resize(&t, n) == -1)
  1381. Py_FatalError("error resizing Python tuple");
  1382. call_object(handler, t, handler_name);
  1383. Py_DECREF(t);
  1384. }
  1385. static void python_process_stat(struct perf_stat_config *config,
  1386. struct evsel *counter, u64 tstamp)
  1387. {
  1388. struct perf_thread_map *threads = counter->core.threads;
  1389. struct perf_cpu_map *cpus = counter->core.cpus;
  1390. for (int thread = 0; thread < perf_thread_map__nr(threads); thread++) {
  1391. int idx;
  1392. struct perf_cpu cpu;
  1393. perf_cpu_map__for_each_cpu(cpu, idx, cpus) {
  1394. process_stat(counter, cpu,
  1395. perf_thread_map__pid(threads, thread), tstamp,
  1396. perf_counts(counter->counts, idx, thread));
  1397. }
  1398. }
  1399. }
  1400. static void python_process_stat_interval(u64 tstamp)
  1401. {
  1402. PyObject *handler, *t;
  1403. static const char handler_name[] = "stat__interval";
  1404. int n = 0;
  1405. t = PyTuple_New(MAX_FIELDS);
  1406. if (!t)
  1407. Py_FatalError("couldn't create Python tuple");
  1408. handler = get_handler(handler_name);
  1409. if (!handler) {
  1410. pr_debug("can't find python handler %s\n", handler_name);
  1411. return;
  1412. }
  1413. tuple_set_u64(t, n++, tstamp);
  1414. if (_PyTuple_Resize(&t, n) == -1)
  1415. Py_FatalError("error resizing Python tuple");
  1416. call_object(handler, t, handler_name);
  1417. Py_DECREF(t);
  1418. }
  1419. static int perf_script_context_init(void)
  1420. {
  1421. PyObject *perf_script_context;
  1422. PyObject *perf_trace_context;
  1423. PyObject *dict;
  1424. int ret;
  1425. perf_trace_context = PyImport_AddModule("perf_trace_context");
  1426. if (!perf_trace_context)
  1427. return -1;
  1428. dict = PyModule_GetDict(perf_trace_context);
  1429. if (!dict)
  1430. return -1;
  1431. perf_script_context = _PyCapsule_New(scripting_context, NULL, NULL);
  1432. if (!perf_script_context)
  1433. return -1;
  1434. ret = PyDict_SetItemString(dict, "perf_script_context", perf_script_context);
  1435. if (!ret)
  1436. ret = PyDict_SetItemString(main_dict, "perf_script_context", perf_script_context);
  1437. Py_DECREF(perf_script_context);
  1438. return ret;
  1439. }
  1440. static int run_start_sub(void)
  1441. {
  1442. main_module = PyImport_AddModule("__main__");
  1443. if (main_module == NULL)
  1444. return -1;
  1445. Py_INCREF(main_module);
  1446. main_dict = PyModule_GetDict(main_module);
  1447. if (main_dict == NULL)
  1448. goto error;
  1449. Py_INCREF(main_dict);
  1450. if (perf_script_context_init())
  1451. goto error;
  1452. try_call_object("trace_begin", NULL);
  1453. return 0;
  1454. error:
  1455. Py_XDECREF(main_dict);
  1456. Py_XDECREF(main_module);
  1457. return -1;
  1458. }
  1459. #define SET_TABLE_HANDLER_(name, handler_name, table_name) do { \
  1460. tables->handler_name = get_handler(#table_name); \
  1461. if (tables->handler_name) \
  1462. tables->dbe.export_ ## name = python_export_ ## name; \
  1463. } while (0)
  1464. #define SET_TABLE_HANDLER(name) \
  1465. SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
  1466. static void set_table_handlers(struct tables *tables)
  1467. {
  1468. const char *perf_db_export_mode = "perf_db_export_mode";
  1469. const char *perf_db_export_calls = "perf_db_export_calls";
  1470. const char *perf_db_export_callchains = "perf_db_export_callchains";
  1471. PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
  1472. bool export_calls = false;
  1473. bool export_callchains = false;
  1474. int ret;
  1475. memset(tables, 0, sizeof(struct tables));
  1476. if (db_export__init(&tables->dbe))
  1477. Py_FatalError("failed to initialize export");
  1478. db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
  1479. if (!db_export_mode)
  1480. return;
  1481. ret = PyObject_IsTrue(db_export_mode);
  1482. if (ret == -1)
  1483. handler_call_die(perf_db_export_mode);
  1484. if (!ret)
  1485. return;
  1486. /* handle export calls */
  1487. tables->dbe.crp = NULL;
  1488. db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
  1489. if (db_export_calls) {
  1490. ret = PyObject_IsTrue(db_export_calls);
  1491. if (ret == -1)
  1492. handler_call_die(perf_db_export_calls);
  1493. export_calls = !!ret;
  1494. }
  1495. if (export_calls) {
  1496. tables->dbe.crp =
  1497. call_return_processor__new(python_process_call_return,
  1498. &tables->dbe);
  1499. if (!tables->dbe.crp)
  1500. Py_FatalError("failed to create calls processor");
  1501. }
  1502. /* handle export callchains */
  1503. tables->dbe.cpr = NULL;
  1504. db_export_callchains = PyDict_GetItemString(main_dict,
  1505. perf_db_export_callchains);
  1506. if (db_export_callchains) {
  1507. ret = PyObject_IsTrue(db_export_callchains);
  1508. if (ret == -1)
  1509. handler_call_die(perf_db_export_callchains);
  1510. export_callchains = !!ret;
  1511. }
  1512. if (export_callchains) {
  1513. /*
  1514. * Attempt to use the call path root from the call return
  1515. * processor, if the call return processor is in use. Otherwise,
  1516. * we allocate a new call path root. This prevents exporting
  1517. * duplicate call path ids when both are in use simultaneously.
  1518. */
  1519. if (tables->dbe.crp)
  1520. tables->dbe.cpr = tables->dbe.crp->cpr;
  1521. else
  1522. tables->dbe.cpr = call_path_root__new();
  1523. if (!tables->dbe.cpr)
  1524. Py_FatalError("failed to create call path root");
  1525. }
  1526. tables->db_export_mode = true;
  1527. /*
  1528. * Reserve per symbol space for symbol->db_id via symbol__priv()
  1529. */
  1530. symbol_conf.priv_size = sizeof(u64);
  1531. SET_TABLE_HANDLER(evsel);
  1532. SET_TABLE_HANDLER(machine);
  1533. SET_TABLE_HANDLER(thread);
  1534. SET_TABLE_HANDLER(comm);
  1535. SET_TABLE_HANDLER(comm_thread);
  1536. SET_TABLE_HANDLER(dso);
  1537. SET_TABLE_HANDLER(symbol);
  1538. SET_TABLE_HANDLER(branch_type);
  1539. SET_TABLE_HANDLER(sample);
  1540. SET_TABLE_HANDLER(call_path);
  1541. SET_TABLE_HANDLER(call_return);
  1542. SET_TABLE_HANDLER(context_switch);
  1543. /*
  1544. * Synthesized events are samples but with architecture-specific data
  1545. * stored in sample->raw_data. They are exported via
  1546. * python_export_sample() and consequently do not need a separate export
  1547. * callback.
  1548. */
  1549. tables->synth_handler = get_handler("synth_data");
  1550. }
  1551. static void _free_command_line(wchar_t **command_line, int num)
  1552. {
  1553. int i;
  1554. for (i = 0; i < num; i++)
  1555. PyMem_RawFree(command_line[i]);
  1556. free(command_line);
  1557. }
  1558. /*
  1559. * Start trace script
  1560. */
  1561. static int python_start_script(const char *script, int argc, const char **argv,
  1562. struct perf_session *session)
  1563. {
  1564. struct tables *tables = &tables_global;
  1565. wchar_t **command_line;
  1566. char buf[PATH_MAX];
  1567. int i, err = 0;
  1568. FILE *fp;
  1569. scripting_context->session = session;
  1570. command_line = malloc((argc + 1) * sizeof(wchar_t *));
  1571. if (!command_line)
  1572. return -1;
  1573. command_line[0] = Py_DecodeLocale(script, NULL);
  1574. for (i = 1; i < argc + 1; i++)
  1575. command_line[i] = Py_DecodeLocale(argv[i - 1], NULL);
  1576. PyImport_AppendInittab("perf_trace_context", PyInit_perf_trace_context);
  1577. Py_Initialize();
  1578. PySys_SetArgv(argc + 1, command_line);
  1579. fp = fopen(script, "r");
  1580. if (!fp) {
  1581. sprintf(buf, "Can't open python script \"%s\"", script);
  1582. perror(buf);
  1583. err = -1;
  1584. goto error;
  1585. }
  1586. err = PyRun_SimpleFile(fp, script);
  1587. if (err) {
  1588. fprintf(stderr, "Error running python script %s\n", script);
  1589. goto error;
  1590. }
  1591. err = run_start_sub();
  1592. if (err) {
  1593. fprintf(stderr, "Error starting python script %s\n", script);
  1594. goto error;
  1595. }
  1596. set_table_handlers(tables);
  1597. if (tables->db_export_mode) {
  1598. err = db_export__branch_types(&tables->dbe);
  1599. if (err)
  1600. goto error;
  1601. }
  1602. _free_command_line(command_line, argc + 1);
  1603. return err;
  1604. error:
  1605. Py_Finalize();
  1606. _free_command_line(command_line, argc + 1);
  1607. return err;
  1608. }
  1609. static int python_flush_script(void)
  1610. {
  1611. return 0;
  1612. }
  1613. /*
  1614. * Stop trace script
  1615. */
  1616. static int python_stop_script(void)
  1617. {
  1618. struct tables *tables = &tables_global;
  1619. try_call_object("trace_end", NULL);
  1620. db_export__exit(&tables->dbe);
  1621. Py_XDECREF(main_dict);
  1622. Py_XDECREF(main_module);
  1623. Py_Finalize();
  1624. return 0;
  1625. }
  1626. #ifdef HAVE_LIBTRACEEVENT
  1627. static int python_generate_script(struct tep_handle *pevent, const char *outfile)
  1628. {
  1629. int i, not_first, count, nr_events;
  1630. struct tep_event **all_events;
  1631. struct tep_event *event = NULL;
  1632. struct tep_format_field *f;
  1633. char fname[PATH_MAX];
  1634. FILE *ofp;
  1635. sprintf(fname, "%s.py", outfile);
  1636. ofp = fopen(fname, "w");
  1637. if (ofp == NULL) {
  1638. fprintf(stderr, "couldn't open %s\n", fname);
  1639. return -1;
  1640. }
  1641. fprintf(ofp, "# perf script event handlers, "
  1642. "generated by perf script -g python\n");
  1643. fprintf(ofp, "# Licensed under the terms of the GNU GPL"
  1644. " License version 2\n\n");
  1645. fprintf(ofp, "# The common_* event handler fields are the most useful "
  1646. "fields common to\n");
  1647. fprintf(ofp, "# all events. They don't necessarily correspond to "
  1648. "the 'common_*' fields\n");
  1649. fprintf(ofp, "# in the format files. Those fields not available as "
  1650. "handler params can\n");
  1651. fprintf(ofp, "# be retrieved using Python functions of the form "
  1652. "common_*(context).\n");
  1653. fprintf(ofp, "# See the perf-script-python Documentation for the list "
  1654. "of available functions.\n\n");
  1655. fprintf(ofp, "from __future__ import print_function\n\n");
  1656. fprintf(ofp, "import os\n");
  1657. fprintf(ofp, "import sys\n\n");
  1658. fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
  1659. fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
  1660. fprintf(ofp, "\nfrom perf_trace_context import *\n");
  1661. fprintf(ofp, "from Core import *\n\n\n");
  1662. fprintf(ofp, "def trace_begin():\n");
  1663. fprintf(ofp, "\tprint(\"in trace_begin\")\n\n");
  1664. fprintf(ofp, "def trace_end():\n");
  1665. fprintf(ofp, "\tprint(\"in trace_end\")\n\n");
  1666. nr_events = tep_get_events_count(pevent);
  1667. all_events = tep_list_events(pevent, TEP_EVENT_SORT_ID);
  1668. for (i = 0; all_events && i < nr_events; i++) {
  1669. event = all_events[i];
  1670. fprintf(ofp, "def %s__%s(", event->system, event->name);
  1671. fprintf(ofp, "event_name, ");
  1672. fprintf(ofp, "context, ");
  1673. fprintf(ofp, "common_cpu,\n");
  1674. fprintf(ofp, "\tcommon_secs, ");
  1675. fprintf(ofp, "common_nsecs, ");
  1676. fprintf(ofp, "common_pid, ");
  1677. fprintf(ofp, "common_comm,\n\t");
  1678. fprintf(ofp, "common_callchain, ");
  1679. not_first = 0;
  1680. count = 0;
  1681. for (f = event->format.fields; f; f = f->next) {
  1682. if (not_first++)
  1683. fprintf(ofp, ", ");
  1684. if (++count % 5 == 0)
  1685. fprintf(ofp, "\n\t");
  1686. fprintf(ofp, "%s", f->name);
  1687. }
  1688. if (not_first++)
  1689. fprintf(ofp, ", ");
  1690. if (++count % 5 == 0)
  1691. fprintf(ofp, "\n\t\t");
  1692. fprintf(ofp, "perf_sample_dict");
  1693. fprintf(ofp, "):\n");
  1694. fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
  1695. "common_secs, common_nsecs,\n\t\t\t"
  1696. "common_pid, common_comm)\n\n");
  1697. fprintf(ofp, "\t\tprint(\"");
  1698. not_first = 0;
  1699. count = 0;
  1700. for (f = event->format.fields; f; f = f->next) {
  1701. if (not_first++)
  1702. fprintf(ofp, ", ");
  1703. if (count && count % 3 == 0) {
  1704. fprintf(ofp, "\" \\\n\t\t\"");
  1705. }
  1706. count++;
  1707. fprintf(ofp, "%s=", f->name);
  1708. if (f->flags & TEP_FIELD_IS_STRING ||
  1709. f->flags & TEP_FIELD_IS_FLAG ||
  1710. f->flags & TEP_FIELD_IS_ARRAY ||
  1711. f->flags & TEP_FIELD_IS_SYMBOLIC)
  1712. fprintf(ofp, "%%s");
  1713. else if (f->flags & TEP_FIELD_IS_SIGNED)
  1714. fprintf(ofp, "%%d");
  1715. else
  1716. fprintf(ofp, "%%u");
  1717. }
  1718. fprintf(ofp, "\" %% \\\n\t\t(");
  1719. not_first = 0;
  1720. count = 0;
  1721. for (f = event->format.fields; f; f = f->next) {
  1722. if (not_first++)
  1723. fprintf(ofp, ", ");
  1724. if (++count % 5 == 0)
  1725. fprintf(ofp, "\n\t\t");
  1726. if (f->flags & TEP_FIELD_IS_FLAG) {
  1727. if ((count - 1) % 5 != 0) {
  1728. fprintf(ofp, "\n\t\t");
  1729. count = 4;
  1730. }
  1731. fprintf(ofp, "flag_str(\"");
  1732. fprintf(ofp, "%s__%s\", ", event->system,
  1733. event->name);
  1734. fprintf(ofp, "\"%s\", %s)", f->name,
  1735. f->name);
  1736. } else if (f->flags & TEP_FIELD_IS_SYMBOLIC) {
  1737. if ((count - 1) % 5 != 0) {
  1738. fprintf(ofp, "\n\t\t");
  1739. count = 4;
  1740. }
  1741. fprintf(ofp, "symbol_str(\"");
  1742. fprintf(ofp, "%s__%s\", ", event->system,
  1743. event->name);
  1744. fprintf(ofp, "\"%s\", %s)", f->name,
  1745. f->name);
  1746. } else
  1747. fprintf(ofp, "%s", f->name);
  1748. }
  1749. fprintf(ofp, "))\n\n");
  1750. fprintf(ofp, "\t\tprint('Sample: {'+"
  1751. "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
  1752. fprintf(ofp, "\t\tfor node in common_callchain:");
  1753. fprintf(ofp, "\n\t\t\tif 'sym' in node:");
  1754. fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x] %%s%%s%%s%%s\" %% (");
  1755. fprintf(ofp, "\n\t\t\t\t\tnode['ip'], node['sym']['name'],");
  1756. fprintf(ofp, "\n\t\t\t\t\t\"+0x{:x}\".format(node['sym_off']) if 'sym_off' in node else \"\",");
  1757. fprintf(ofp, "\n\t\t\t\t\t\" ({})\".format(node['dso']) if 'dso' in node else \"\",");
  1758. fprintf(ofp, "\n\t\t\t\t\t\" \" + node['sym_srcline'] if 'sym_srcline' in node else \"\"))");
  1759. fprintf(ofp, "\n\t\t\telse:");
  1760. fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x]\" %% (node['ip']))\n\n");
  1761. fprintf(ofp, "\t\tprint()\n\n");
  1762. }
  1763. fprintf(ofp, "def trace_unhandled(event_name, context, "
  1764. "event_fields_dict, perf_sample_dict):\n");
  1765. fprintf(ofp, "\t\tprint(get_dict_as_string(event_fields_dict))\n");
  1766. fprintf(ofp, "\t\tprint('Sample: {'+"
  1767. "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
  1768. fprintf(ofp, "def print_header("
  1769. "event_name, cpu, secs, nsecs, pid, comm):\n"
  1770. "\tprint(\"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
  1771. "(event_name, cpu, secs, nsecs, pid, comm), end=\"\")\n\n");
  1772. fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
  1773. "\treturn delimiter.join"
  1774. "(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
  1775. fclose(ofp);
  1776. fprintf(stderr, "generated Python script: %s\n", fname);
  1777. return 0;
  1778. }
  1779. #else
  1780. static int python_generate_script(struct tep_handle *pevent __maybe_unused,
  1781. const char *outfile __maybe_unused)
  1782. {
  1783. fprintf(stderr, "Generating Python perf-script is not supported."
  1784. " Install libtraceevent and rebuild perf to enable it.\n"
  1785. "For example:\n # apt install libtraceevent-dev (ubuntu)"
  1786. "\n # yum install libtraceevent-devel (Fedora)"
  1787. "\n etc.\n");
  1788. return -1;
  1789. }
  1790. #endif
  1791. struct scripting_ops python_scripting_ops = {
  1792. .name = "Python",
  1793. .dirname = "python",
  1794. .start_script = python_start_script,
  1795. .flush_script = python_flush_script,
  1796. .stop_script = python_stop_script,
  1797. .process_event = python_process_event,
  1798. .process_switch = python_process_switch,
  1799. .process_auxtrace_error = python_process_auxtrace_error,
  1800. .process_stat = python_process_stat,
  1801. .process_stat_interval = python_process_stat_interval,
  1802. .process_throttle = python_process_throttle,
  1803. .generate_script = python_generate_script,
  1804. };