trace-event-python.c 46 KB

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