trace-event-python.c 39 KB

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