trace-event-python.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  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 <stdio.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <stdbool.h>
  26. #include <errno.h>
  27. #include "../../perf.h"
  28. #include "../debug.h"
  29. #include "../callchain.h"
  30. #include "../evsel.h"
  31. #include "../util.h"
  32. #include "../event.h"
  33. #include "../thread.h"
  34. #include "../comm.h"
  35. #include "../machine.h"
  36. #include "../db-export.h"
  37. #include "../thread-stack.h"
  38. #include "../trace-event.h"
  39. #include "../machine.h"
  40. PyMODINIT_FUNC initperf_trace_context(void);
  41. #define FTRACE_MAX_EVENT \
  42. ((1 << (sizeof(unsigned short) * 8)) - 1)
  43. struct event_format *events[FTRACE_MAX_EVENT];
  44. #define MAX_FIELDS 64
  45. #define N_COMMON_FIELDS 7
  46. extern struct scripting_context *scripting_context;
  47. static char *cur_field_name;
  48. static int zero_flag_atom;
  49. static PyObject *main_module, *main_dict;
  50. struct tables {
  51. struct db_export dbe;
  52. PyObject *evsel_handler;
  53. PyObject *machine_handler;
  54. PyObject *thread_handler;
  55. PyObject *comm_handler;
  56. PyObject *comm_thread_handler;
  57. PyObject *dso_handler;
  58. PyObject *symbol_handler;
  59. PyObject *branch_type_handler;
  60. PyObject *sample_handler;
  61. PyObject *call_path_handler;
  62. PyObject *call_return_handler;
  63. bool db_export_mode;
  64. };
  65. static struct tables tables_global;
  66. static void handler_call_die(const char *handler_name) NORETURN;
  67. static void handler_call_die(const char *handler_name)
  68. {
  69. PyErr_Print();
  70. Py_FatalError("problem in Python trace event handler");
  71. // Py_FatalError does not return
  72. // but we have to make the compiler happy
  73. abort();
  74. }
  75. /*
  76. * Insert val into into the dictionary and decrement the reference counter.
  77. * This is necessary for dictionaries since PyDict_SetItemString() does not
  78. * steal a reference, as opposed to PyTuple_SetItem().
  79. */
  80. static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
  81. {
  82. PyDict_SetItemString(dict, key, val);
  83. Py_DECREF(val);
  84. }
  85. static PyObject *get_handler(const char *handler_name)
  86. {
  87. PyObject *handler;
  88. handler = PyDict_GetItemString(main_dict, handler_name);
  89. if (handler && !PyCallable_Check(handler))
  90. return NULL;
  91. return handler;
  92. }
  93. static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
  94. {
  95. PyObject *retval;
  96. retval = PyObject_CallObject(handler, args);
  97. if (retval == NULL)
  98. handler_call_die(die_msg);
  99. Py_DECREF(retval);
  100. }
  101. static void try_call_object(const char *handler_name, PyObject *args)
  102. {
  103. PyObject *handler;
  104. handler = get_handler(handler_name);
  105. if (handler)
  106. call_object(handler, args, handler_name);
  107. }
  108. static void define_value(enum print_arg_type field_type,
  109. const char *ev_name,
  110. const char *field_name,
  111. const char *field_value,
  112. const char *field_str)
  113. {
  114. const char *handler_name = "define_flag_value";
  115. PyObject *t;
  116. unsigned long long value;
  117. unsigned n = 0;
  118. if (field_type == PRINT_SYMBOL)
  119. handler_name = "define_symbolic_value";
  120. t = PyTuple_New(4);
  121. if (!t)
  122. Py_FatalError("couldn't create Python tuple");
  123. value = eval_flag(field_value);
  124. PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
  125. PyTuple_SetItem(t, n++, PyString_FromString(field_name));
  126. PyTuple_SetItem(t, n++, PyInt_FromLong(value));
  127. PyTuple_SetItem(t, n++, PyString_FromString(field_str));
  128. try_call_object(handler_name, t);
  129. Py_DECREF(t);
  130. }
  131. static void define_values(enum print_arg_type field_type,
  132. struct print_flag_sym *field,
  133. const char *ev_name,
  134. const char *field_name)
  135. {
  136. define_value(field_type, ev_name, field_name, field->value,
  137. field->str);
  138. if (field->next)
  139. define_values(field_type, field->next, ev_name, field_name);
  140. }
  141. static void define_field(enum print_arg_type field_type,
  142. const char *ev_name,
  143. const char *field_name,
  144. const char *delim)
  145. {
  146. const char *handler_name = "define_flag_field";
  147. PyObject *t;
  148. unsigned n = 0;
  149. if (field_type == PRINT_SYMBOL)
  150. handler_name = "define_symbolic_field";
  151. if (field_type == PRINT_FLAGS)
  152. t = PyTuple_New(3);
  153. else
  154. t = PyTuple_New(2);
  155. if (!t)
  156. Py_FatalError("couldn't create Python tuple");
  157. PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
  158. PyTuple_SetItem(t, n++, PyString_FromString(field_name));
  159. if (field_type == PRINT_FLAGS)
  160. PyTuple_SetItem(t, n++, PyString_FromString(delim));
  161. try_call_object(handler_name, t);
  162. Py_DECREF(t);
  163. }
  164. static void define_event_symbols(struct event_format *event,
  165. const char *ev_name,
  166. struct print_arg *args)
  167. {
  168. switch (args->type) {
  169. case PRINT_NULL:
  170. break;
  171. case PRINT_ATOM:
  172. define_value(PRINT_FLAGS, ev_name, cur_field_name, "0",
  173. args->atom.atom);
  174. zero_flag_atom = 0;
  175. break;
  176. case PRINT_FIELD:
  177. free(cur_field_name);
  178. cur_field_name = strdup(args->field.name);
  179. break;
  180. case PRINT_FLAGS:
  181. define_event_symbols(event, ev_name, args->flags.field);
  182. define_field(PRINT_FLAGS, ev_name, cur_field_name,
  183. args->flags.delim);
  184. define_values(PRINT_FLAGS, args->flags.flags, ev_name,
  185. cur_field_name);
  186. break;
  187. case PRINT_SYMBOL:
  188. define_event_symbols(event, ev_name, args->symbol.field);
  189. define_field(PRINT_SYMBOL, ev_name, cur_field_name, NULL);
  190. define_values(PRINT_SYMBOL, args->symbol.symbols, ev_name,
  191. cur_field_name);
  192. break;
  193. case PRINT_HEX:
  194. define_event_symbols(event, ev_name, args->hex.field);
  195. define_event_symbols(event, ev_name, args->hex.size);
  196. break;
  197. case PRINT_STRING:
  198. break;
  199. case PRINT_TYPE:
  200. define_event_symbols(event, ev_name, args->typecast.item);
  201. break;
  202. case PRINT_OP:
  203. if (strcmp(args->op.op, ":") == 0)
  204. zero_flag_atom = 1;
  205. define_event_symbols(event, ev_name, args->op.left);
  206. define_event_symbols(event, ev_name, args->op.right);
  207. break;
  208. default:
  209. /* gcc warns for these? */
  210. case PRINT_BSTRING:
  211. case PRINT_DYNAMIC_ARRAY:
  212. case PRINT_FUNC:
  213. case PRINT_BITMASK:
  214. /* we should warn... */
  215. return;
  216. }
  217. if (args->next)
  218. define_event_symbols(event, ev_name, args->next);
  219. }
  220. static inline struct event_format *find_cache_event(struct perf_evsel *evsel)
  221. {
  222. static char ev_name[256];
  223. struct event_format *event;
  224. int type = evsel->attr.config;
  225. /*
  226. * XXX: Do we really need to cache this since now we have evsel->tp_format
  227. * cached already? Need to re-read this "cache" routine that as well calls
  228. * define_event_symbols() :-\
  229. */
  230. if (events[type])
  231. return events[type];
  232. events[type] = event = evsel->tp_format;
  233. if (!event)
  234. return NULL;
  235. sprintf(ev_name, "%s__%s", event->system, event->name);
  236. define_event_symbols(event, ev_name, event->print_fmt.args);
  237. return event;
  238. }
  239. static PyObject *get_field_numeric_entry(struct event_format *event,
  240. struct format_field *field, void *data)
  241. {
  242. bool is_array = field->flags & FIELD_IS_ARRAY;
  243. PyObject *obj, *list = NULL;
  244. unsigned long long val;
  245. unsigned int item_size, n_items, i;
  246. if (is_array) {
  247. list = PyList_New(field->arraylen);
  248. item_size = field->size / field->arraylen;
  249. n_items = field->arraylen;
  250. } else {
  251. item_size = field->size;
  252. n_items = 1;
  253. }
  254. for (i = 0; i < n_items; i++) {
  255. val = read_size(event, data + field->offset + i * item_size,
  256. item_size);
  257. if (field->flags & FIELD_IS_SIGNED) {
  258. if ((long long)val >= LONG_MIN &&
  259. (long long)val <= LONG_MAX)
  260. obj = PyInt_FromLong(val);
  261. else
  262. obj = PyLong_FromLongLong(val);
  263. } else {
  264. if (val <= LONG_MAX)
  265. obj = PyInt_FromLong(val);
  266. else
  267. obj = PyLong_FromUnsignedLongLong(val);
  268. }
  269. if (is_array)
  270. PyList_SET_ITEM(list, i, obj);
  271. }
  272. if (is_array)
  273. obj = list;
  274. return obj;
  275. }
  276. static PyObject *python_process_callchain(struct perf_sample *sample,
  277. struct perf_evsel *evsel,
  278. struct addr_location *al)
  279. {
  280. PyObject *pylist;
  281. pylist = PyList_New(0);
  282. if (!pylist)
  283. Py_FatalError("couldn't create Python list");
  284. if (!symbol_conf.use_callchain || !sample->callchain)
  285. goto exit;
  286. if (thread__resolve_callchain(al->thread, evsel,
  287. sample, NULL, NULL,
  288. PERF_MAX_STACK_DEPTH) != 0) {
  289. pr_err("Failed to resolve callchain. Skipping\n");
  290. goto exit;
  291. }
  292. callchain_cursor_commit(&callchain_cursor);
  293. while (1) {
  294. PyObject *pyelem;
  295. struct callchain_cursor_node *node;
  296. node = callchain_cursor_current(&callchain_cursor);
  297. if (!node)
  298. break;
  299. pyelem = PyDict_New();
  300. if (!pyelem)
  301. Py_FatalError("couldn't create Python dictionary");
  302. pydict_set_item_string_decref(pyelem, "ip",
  303. PyLong_FromUnsignedLongLong(node->ip));
  304. if (node->sym) {
  305. PyObject *pysym = PyDict_New();
  306. if (!pysym)
  307. Py_FatalError("couldn't create Python dictionary");
  308. pydict_set_item_string_decref(pysym, "start",
  309. PyLong_FromUnsignedLongLong(node->sym->start));
  310. pydict_set_item_string_decref(pysym, "end",
  311. PyLong_FromUnsignedLongLong(node->sym->end));
  312. pydict_set_item_string_decref(pysym, "binding",
  313. PyInt_FromLong(node->sym->binding));
  314. pydict_set_item_string_decref(pysym, "name",
  315. PyString_FromStringAndSize(node->sym->name,
  316. node->sym->namelen));
  317. pydict_set_item_string_decref(pyelem, "sym", pysym);
  318. }
  319. if (node->map) {
  320. struct map *map = node->map;
  321. const char *dsoname = "[unknown]";
  322. if (map && map->dso && (map->dso->name || map->dso->long_name)) {
  323. if (symbol_conf.show_kernel_path && map->dso->long_name)
  324. dsoname = map->dso->long_name;
  325. else if (map->dso->name)
  326. dsoname = map->dso->name;
  327. }
  328. pydict_set_item_string_decref(pyelem, "dso",
  329. PyString_FromString(dsoname));
  330. }
  331. callchain_cursor_advance(&callchain_cursor);
  332. PyList_Append(pylist, pyelem);
  333. Py_DECREF(pyelem);
  334. }
  335. exit:
  336. return pylist;
  337. }
  338. static void python_process_tracepoint(struct perf_sample *sample,
  339. struct perf_evsel *evsel,
  340. struct thread *thread,
  341. struct addr_location *al)
  342. {
  343. PyObject *handler, *context, *t, *obj, *callchain;
  344. PyObject *dict = NULL;
  345. static char handler_name[256];
  346. struct format_field *field;
  347. unsigned long s, ns;
  348. struct event_format *event;
  349. unsigned n = 0;
  350. int pid;
  351. int cpu = sample->cpu;
  352. void *data = sample->raw_data;
  353. unsigned long long nsecs = sample->time;
  354. const char *comm = thread__comm_str(thread);
  355. t = PyTuple_New(MAX_FIELDS);
  356. if (!t)
  357. Py_FatalError("couldn't create Python tuple");
  358. event = find_cache_event(evsel);
  359. if (!event)
  360. die("ug! no event found for type %d", (int)evsel->attr.config);
  361. pid = raw_field_value(event, "common_pid", data);
  362. sprintf(handler_name, "%s__%s", event->system, event->name);
  363. handler = get_handler(handler_name);
  364. if (!handler) {
  365. dict = PyDict_New();
  366. if (!dict)
  367. Py_FatalError("couldn't create Python dict");
  368. }
  369. s = nsecs / NSECS_PER_SEC;
  370. ns = nsecs - s * NSECS_PER_SEC;
  371. scripting_context->event_data = data;
  372. scripting_context->pevent = evsel->tp_format->pevent;
  373. context = PyCObject_FromVoidPtr(scripting_context, NULL);
  374. PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
  375. PyTuple_SetItem(t, n++, context);
  376. /* ip unwinding */
  377. callchain = python_process_callchain(sample, evsel, al);
  378. if (handler) {
  379. PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
  380. PyTuple_SetItem(t, n++, PyInt_FromLong(s));
  381. PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
  382. PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
  383. PyTuple_SetItem(t, n++, PyString_FromString(comm));
  384. PyTuple_SetItem(t, n++, callchain);
  385. } else {
  386. pydict_set_item_string_decref(dict, "common_cpu", PyInt_FromLong(cpu));
  387. pydict_set_item_string_decref(dict, "common_s", PyInt_FromLong(s));
  388. pydict_set_item_string_decref(dict, "common_ns", PyInt_FromLong(ns));
  389. pydict_set_item_string_decref(dict, "common_pid", PyInt_FromLong(pid));
  390. pydict_set_item_string_decref(dict, "common_comm", PyString_FromString(comm));
  391. pydict_set_item_string_decref(dict, "common_callchain", callchain);
  392. }
  393. for (field = event->format.fields; field; field = field->next) {
  394. if (field->flags & FIELD_IS_STRING) {
  395. int offset;
  396. if (field->flags & FIELD_IS_DYNAMIC) {
  397. offset = *(int *)(data + field->offset);
  398. offset &= 0xffff;
  399. } else
  400. offset = field->offset;
  401. obj = PyString_FromString((char *)data + offset);
  402. } else { /* FIELD_IS_NUMERIC */
  403. obj = get_field_numeric_entry(event, field, data);
  404. }
  405. if (handler)
  406. PyTuple_SetItem(t, n++, obj);
  407. else
  408. pydict_set_item_string_decref(dict, field->name, obj);
  409. }
  410. if (!handler)
  411. PyTuple_SetItem(t, n++, dict);
  412. if (_PyTuple_Resize(&t, n) == -1)
  413. Py_FatalError("error resizing Python tuple");
  414. if (handler) {
  415. call_object(handler, t, handler_name);
  416. } else {
  417. try_call_object("trace_unhandled", t);
  418. Py_DECREF(dict);
  419. }
  420. Py_DECREF(t);
  421. }
  422. static PyObject *tuple_new(unsigned int sz)
  423. {
  424. PyObject *t;
  425. t = PyTuple_New(sz);
  426. if (!t)
  427. Py_FatalError("couldn't create Python tuple");
  428. return t;
  429. }
  430. static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
  431. {
  432. #if BITS_PER_LONG == 64
  433. return PyTuple_SetItem(t, pos, PyInt_FromLong(val));
  434. #endif
  435. #if BITS_PER_LONG == 32
  436. return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
  437. #endif
  438. }
  439. static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
  440. {
  441. return PyTuple_SetItem(t, pos, PyInt_FromLong(val));
  442. }
  443. static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
  444. {
  445. return PyTuple_SetItem(t, pos, PyString_FromString(s));
  446. }
  447. static int python_export_evsel(struct db_export *dbe, struct perf_evsel *evsel)
  448. {
  449. struct tables *tables = container_of(dbe, struct tables, dbe);
  450. PyObject *t;
  451. t = tuple_new(2);
  452. tuple_set_u64(t, 0, evsel->db_id);
  453. tuple_set_string(t, 1, perf_evsel__name(evsel));
  454. call_object(tables->evsel_handler, t, "evsel_table");
  455. Py_DECREF(t);
  456. return 0;
  457. }
  458. static int python_export_machine(struct db_export *dbe,
  459. struct machine *machine)
  460. {
  461. struct tables *tables = container_of(dbe, struct tables, dbe);
  462. PyObject *t;
  463. t = tuple_new(3);
  464. tuple_set_u64(t, 0, machine->db_id);
  465. tuple_set_s32(t, 1, machine->pid);
  466. tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
  467. call_object(tables->machine_handler, t, "machine_table");
  468. Py_DECREF(t);
  469. return 0;
  470. }
  471. static int python_export_thread(struct db_export *dbe, struct thread *thread,
  472. u64 main_thread_db_id, struct machine *machine)
  473. {
  474. struct tables *tables = container_of(dbe, struct tables, dbe);
  475. PyObject *t;
  476. t = tuple_new(5);
  477. tuple_set_u64(t, 0, thread->db_id);
  478. tuple_set_u64(t, 1, machine->db_id);
  479. tuple_set_u64(t, 2, main_thread_db_id);
  480. tuple_set_s32(t, 3, thread->pid_);
  481. tuple_set_s32(t, 4, thread->tid);
  482. call_object(tables->thread_handler, t, "thread_table");
  483. Py_DECREF(t);
  484. return 0;
  485. }
  486. static int python_export_comm(struct db_export *dbe, struct comm *comm)
  487. {
  488. struct tables *tables = container_of(dbe, struct tables, dbe);
  489. PyObject *t;
  490. t = tuple_new(2);
  491. tuple_set_u64(t, 0, comm->db_id);
  492. tuple_set_string(t, 1, comm__str(comm));
  493. call_object(tables->comm_handler, t, "comm_table");
  494. Py_DECREF(t);
  495. return 0;
  496. }
  497. static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
  498. struct comm *comm, struct thread *thread)
  499. {
  500. struct tables *tables = container_of(dbe, struct tables, dbe);
  501. PyObject *t;
  502. t = tuple_new(3);
  503. tuple_set_u64(t, 0, db_id);
  504. tuple_set_u64(t, 1, comm->db_id);
  505. tuple_set_u64(t, 2, thread->db_id);
  506. call_object(tables->comm_thread_handler, t, "comm_thread_table");
  507. Py_DECREF(t);
  508. return 0;
  509. }
  510. static int python_export_dso(struct db_export *dbe, struct dso *dso,
  511. struct machine *machine)
  512. {
  513. struct tables *tables = container_of(dbe, struct tables, dbe);
  514. char sbuild_id[BUILD_ID_SIZE * 2 + 1];
  515. PyObject *t;
  516. build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);
  517. t = tuple_new(5);
  518. tuple_set_u64(t, 0, dso->db_id);
  519. tuple_set_u64(t, 1, machine->db_id);
  520. tuple_set_string(t, 2, dso->short_name);
  521. tuple_set_string(t, 3, dso->long_name);
  522. tuple_set_string(t, 4, sbuild_id);
  523. call_object(tables->dso_handler, t, "dso_table");
  524. Py_DECREF(t);
  525. return 0;
  526. }
  527. static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
  528. struct dso *dso)
  529. {
  530. struct tables *tables = container_of(dbe, struct tables, dbe);
  531. u64 *sym_db_id = symbol__priv(sym);
  532. PyObject *t;
  533. t = tuple_new(6);
  534. tuple_set_u64(t, 0, *sym_db_id);
  535. tuple_set_u64(t, 1, dso->db_id);
  536. tuple_set_u64(t, 2, sym->start);
  537. tuple_set_u64(t, 3, sym->end);
  538. tuple_set_s32(t, 4, sym->binding);
  539. tuple_set_string(t, 5, sym->name);
  540. call_object(tables->symbol_handler, t, "symbol_table");
  541. Py_DECREF(t);
  542. return 0;
  543. }
  544. static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
  545. const char *name)
  546. {
  547. struct tables *tables = container_of(dbe, struct tables, dbe);
  548. PyObject *t;
  549. t = tuple_new(2);
  550. tuple_set_s32(t, 0, branch_type);
  551. tuple_set_string(t, 1, name);
  552. call_object(tables->branch_type_handler, t, "branch_type_table");
  553. Py_DECREF(t);
  554. return 0;
  555. }
  556. static int python_export_sample(struct db_export *dbe,
  557. struct export_sample *es)
  558. {
  559. struct tables *tables = container_of(dbe, struct tables, dbe);
  560. PyObject *t;
  561. t = tuple_new(21);
  562. tuple_set_u64(t, 0, es->db_id);
  563. tuple_set_u64(t, 1, es->evsel->db_id);
  564. tuple_set_u64(t, 2, es->al->machine->db_id);
  565. tuple_set_u64(t, 3, es->thread->db_id);
  566. tuple_set_u64(t, 4, es->comm_db_id);
  567. tuple_set_u64(t, 5, es->dso_db_id);
  568. tuple_set_u64(t, 6, es->sym_db_id);
  569. tuple_set_u64(t, 7, es->offset);
  570. tuple_set_u64(t, 8, es->sample->ip);
  571. tuple_set_u64(t, 9, es->sample->time);
  572. tuple_set_s32(t, 10, es->sample->cpu);
  573. tuple_set_u64(t, 11, es->addr_dso_db_id);
  574. tuple_set_u64(t, 12, es->addr_sym_db_id);
  575. tuple_set_u64(t, 13, es->addr_offset);
  576. tuple_set_u64(t, 14, es->sample->addr);
  577. tuple_set_u64(t, 15, es->sample->period);
  578. tuple_set_u64(t, 16, es->sample->weight);
  579. tuple_set_u64(t, 17, es->sample->transaction);
  580. tuple_set_u64(t, 18, es->sample->data_src);
  581. tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
  582. tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
  583. call_object(tables->sample_handler, t, "sample_table");
  584. Py_DECREF(t);
  585. return 0;
  586. }
  587. static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
  588. {
  589. struct tables *tables = container_of(dbe, struct tables, dbe);
  590. PyObject *t;
  591. u64 parent_db_id, sym_db_id;
  592. parent_db_id = cp->parent ? cp->parent->db_id : 0;
  593. sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
  594. t = tuple_new(4);
  595. tuple_set_u64(t, 0, cp->db_id);
  596. tuple_set_u64(t, 1, parent_db_id);
  597. tuple_set_u64(t, 2, sym_db_id);
  598. tuple_set_u64(t, 3, cp->ip);
  599. call_object(tables->call_path_handler, t, "call_path_table");
  600. Py_DECREF(t);
  601. return 0;
  602. }
  603. static int python_export_call_return(struct db_export *dbe,
  604. struct call_return *cr)
  605. {
  606. struct tables *tables = container_of(dbe, struct tables, dbe);
  607. u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
  608. PyObject *t;
  609. t = tuple_new(11);
  610. tuple_set_u64(t, 0, cr->db_id);
  611. tuple_set_u64(t, 1, cr->thread->db_id);
  612. tuple_set_u64(t, 2, comm_db_id);
  613. tuple_set_u64(t, 3, cr->cp->db_id);
  614. tuple_set_u64(t, 4, cr->call_time);
  615. tuple_set_u64(t, 5, cr->return_time);
  616. tuple_set_u64(t, 6, cr->branch_count);
  617. tuple_set_u64(t, 7, cr->call_ref);
  618. tuple_set_u64(t, 8, cr->return_ref);
  619. tuple_set_u64(t, 9, cr->cp->parent->db_id);
  620. tuple_set_s32(t, 10, cr->flags);
  621. call_object(tables->call_return_handler, t, "call_return_table");
  622. Py_DECREF(t);
  623. return 0;
  624. }
  625. static int python_process_call_return(struct call_return *cr, void *data)
  626. {
  627. struct db_export *dbe = data;
  628. return db_export__call_return(dbe, cr);
  629. }
  630. static void python_process_general_event(struct perf_sample *sample,
  631. struct perf_evsel *evsel,
  632. struct thread *thread,
  633. struct addr_location *al)
  634. {
  635. PyObject *handler, *t, *dict, *callchain, *dict_sample;
  636. static char handler_name[64];
  637. unsigned n = 0;
  638. /*
  639. * Use the MAX_FIELDS to make the function expandable, though
  640. * currently there is only one item for the tuple.
  641. */
  642. t = PyTuple_New(MAX_FIELDS);
  643. if (!t)
  644. Py_FatalError("couldn't create Python tuple");
  645. dict = PyDict_New();
  646. if (!dict)
  647. Py_FatalError("couldn't create Python dictionary");
  648. dict_sample = PyDict_New();
  649. if (!dict_sample)
  650. Py_FatalError("couldn't create Python dictionary");
  651. snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
  652. handler = get_handler(handler_name);
  653. if (!handler)
  654. goto exit;
  655. pydict_set_item_string_decref(dict, "ev_name", PyString_FromString(perf_evsel__name(evsel)));
  656. pydict_set_item_string_decref(dict, "attr", PyString_FromStringAndSize(
  657. (const char *)&evsel->attr, sizeof(evsel->attr)));
  658. pydict_set_item_string_decref(dict_sample, "pid",
  659. PyInt_FromLong(sample->pid));
  660. pydict_set_item_string_decref(dict_sample, "tid",
  661. PyInt_FromLong(sample->tid));
  662. pydict_set_item_string_decref(dict_sample, "cpu",
  663. PyInt_FromLong(sample->cpu));
  664. pydict_set_item_string_decref(dict_sample, "ip",
  665. PyLong_FromUnsignedLongLong(sample->ip));
  666. pydict_set_item_string_decref(dict_sample, "time",
  667. PyLong_FromUnsignedLongLong(sample->time));
  668. pydict_set_item_string_decref(dict_sample, "period",
  669. PyLong_FromUnsignedLongLong(sample->period));
  670. pydict_set_item_string_decref(dict, "sample", dict_sample);
  671. pydict_set_item_string_decref(dict, "raw_buf", PyString_FromStringAndSize(
  672. (const char *)sample->raw_data, sample->raw_size));
  673. pydict_set_item_string_decref(dict, "comm",
  674. PyString_FromString(thread__comm_str(thread)));
  675. if (al->map) {
  676. pydict_set_item_string_decref(dict, "dso",
  677. PyString_FromString(al->map->dso->name));
  678. }
  679. if (al->sym) {
  680. pydict_set_item_string_decref(dict, "symbol",
  681. PyString_FromString(al->sym->name));
  682. }
  683. /* ip unwinding */
  684. callchain = python_process_callchain(sample, evsel, al);
  685. pydict_set_item_string_decref(dict, "callchain", callchain);
  686. PyTuple_SetItem(t, n++, dict);
  687. if (_PyTuple_Resize(&t, n) == -1)
  688. Py_FatalError("error resizing Python tuple");
  689. call_object(handler, t, handler_name);
  690. exit:
  691. Py_DECREF(dict);
  692. Py_DECREF(t);
  693. }
  694. static void python_process_event(union perf_event *event,
  695. struct perf_sample *sample,
  696. struct perf_evsel *evsel,
  697. struct thread *thread,
  698. struct addr_location *al)
  699. {
  700. struct tables *tables = &tables_global;
  701. switch (evsel->attr.type) {
  702. case PERF_TYPE_TRACEPOINT:
  703. python_process_tracepoint(sample, evsel, thread, al);
  704. break;
  705. /* Reserve for future process_hw/sw/raw APIs */
  706. default:
  707. if (tables->db_export_mode)
  708. db_export__sample(&tables->dbe, event, sample, evsel,
  709. thread, al);
  710. else
  711. python_process_general_event(sample, evsel, thread, al);
  712. }
  713. }
  714. static int run_start_sub(void)
  715. {
  716. main_module = PyImport_AddModule("__main__");
  717. if (main_module == NULL)
  718. return -1;
  719. Py_INCREF(main_module);
  720. main_dict = PyModule_GetDict(main_module);
  721. if (main_dict == NULL)
  722. goto error;
  723. Py_INCREF(main_dict);
  724. try_call_object("trace_begin", NULL);
  725. return 0;
  726. error:
  727. Py_XDECREF(main_dict);
  728. Py_XDECREF(main_module);
  729. return -1;
  730. }
  731. #define SET_TABLE_HANDLER_(name, handler_name, table_name) do { \
  732. tables->handler_name = get_handler(#table_name); \
  733. if (tables->handler_name) \
  734. tables->dbe.export_ ## name = python_export_ ## name; \
  735. } while (0)
  736. #define SET_TABLE_HANDLER(name) \
  737. SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
  738. static void set_table_handlers(struct tables *tables)
  739. {
  740. const char *perf_db_export_mode = "perf_db_export_mode";
  741. const char *perf_db_export_calls = "perf_db_export_calls";
  742. PyObject *db_export_mode, *db_export_calls;
  743. bool export_calls = false;
  744. int ret;
  745. memset(tables, 0, sizeof(struct tables));
  746. if (db_export__init(&tables->dbe))
  747. Py_FatalError("failed to initialize export");
  748. db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
  749. if (!db_export_mode)
  750. return;
  751. ret = PyObject_IsTrue(db_export_mode);
  752. if (ret == -1)
  753. handler_call_die(perf_db_export_mode);
  754. if (!ret)
  755. return;
  756. tables->dbe.crp = NULL;
  757. db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
  758. if (db_export_calls) {
  759. ret = PyObject_IsTrue(db_export_calls);
  760. if (ret == -1)
  761. handler_call_die(perf_db_export_calls);
  762. export_calls = !!ret;
  763. }
  764. if (export_calls) {
  765. tables->dbe.crp =
  766. call_return_processor__new(python_process_call_return,
  767. &tables->dbe);
  768. if (!tables->dbe.crp)
  769. Py_FatalError("failed to create calls processor");
  770. }
  771. tables->db_export_mode = true;
  772. /*
  773. * Reserve per symbol space for symbol->db_id via symbol__priv()
  774. */
  775. symbol_conf.priv_size = sizeof(u64);
  776. SET_TABLE_HANDLER(evsel);
  777. SET_TABLE_HANDLER(machine);
  778. SET_TABLE_HANDLER(thread);
  779. SET_TABLE_HANDLER(comm);
  780. SET_TABLE_HANDLER(comm_thread);
  781. SET_TABLE_HANDLER(dso);
  782. SET_TABLE_HANDLER(symbol);
  783. SET_TABLE_HANDLER(branch_type);
  784. SET_TABLE_HANDLER(sample);
  785. SET_TABLE_HANDLER(call_path);
  786. SET_TABLE_HANDLER(call_return);
  787. }
  788. /*
  789. * Start trace script
  790. */
  791. static int python_start_script(const char *script, int argc, const char **argv)
  792. {
  793. struct tables *tables = &tables_global;
  794. const char **command_line;
  795. char buf[PATH_MAX];
  796. int i, err = 0;
  797. FILE *fp;
  798. command_line = malloc((argc + 1) * sizeof(const char *));
  799. command_line[0] = script;
  800. for (i = 1; i < argc + 1; i++)
  801. command_line[i] = argv[i - 1];
  802. Py_Initialize();
  803. initperf_trace_context();
  804. PySys_SetArgv(argc + 1, (char **)command_line);
  805. fp = fopen(script, "r");
  806. if (!fp) {
  807. sprintf(buf, "Can't open python script \"%s\"", script);
  808. perror(buf);
  809. err = -1;
  810. goto error;
  811. }
  812. err = PyRun_SimpleFile(fp, script);
  813. if (err) {
  814. fprintf(stderr, "Error running python script %s\n", script);
  815. goto error;
  816. }
  817. err = run_start_sub();
  818. if (err) {
  819. fprintf(stderr, "Error starting python script %s\n", script);
  820. goto error;
  821. }
  822. free(command_line);
  823. set_table_handlers(tables);
  824. if (tables->db_export_mode) {
  825. err = db_export__branch_types(&tables->dbe);
  826. if (err)
  827. goto error;
  828. }
  829. return err;
  830. error:
  831. Py_Finalize();
  832. free(command_line);
  833. return err;
  834. }
  835. static int python_flush_script(void)
  836. {
  837. struct tables *tables = &tables_global;
  838. return db_export__flush(&tables->dbe);
  839. }
  840. /*
  841. * Stop trace script
  842. */
  843. static int python_stop_script(void)
  844. {
  845. struct tables *tables = &tables_global;
  846. try_call_object("trace_end", NULL);
  847. db_export__exit(&tables->dbe);
  848. Py_XDECREF(main_dict);
  849. Py_XDECREF(main_module);
  850. Py_Finalize();
  851. return 0;
  852. }
  853. static int python_generate_script(struct pevent *pevent, const char *outfile)
  854. {
  855. struct event_format *event = NULL;
  856. struct format_field *f;
  857. char fname[PATH_MAX];
  858. int not_first, count;
  859. FILE *ofp;
  860. sprintf(fname, "%s.py", outfile);
  861. ofp = fopen(fname, "w");
  862. if (ofp == NULL) {
  863. fprintf(stderr, "couldn't open %s\n", fname);
  864. return -1;
  865. }
  866. fprintf(ofp, "# perf script event handlers, "
  867. "generated by perf script -g python\n");
  868. fprintf(ofp, "# Licensed under the terms of the GNU GPL"
  869. " License version 2\n\n");
  870. fprintf(ofp, "# The common_* event handler fields are the most useful "
  871. "fields common to\n");
  872. fprintf(ofp, "# all events. They don't necessarily correspond to "
  873. "the 'common_*' fields\n");
  874. fprintf(ofp, "# in the format files. Those fields not available as "
  875. "handler params can\n");
  876. fprintf(ofp, "# be retrieved using Python functions of the form "
  877. "common_*(context).\n");
  878. fprintf(ofp, "# See the perf-trace-python Documentation for the list "
  879. "of available functions.\n\n");
  880. fprintf(ofp, "import os\n");
  881. fprintf(ofp, "import sys\n\n");
  882. fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
  883. fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
  884. fprintf(ofp, "\nfrom perf_trace_context import *\n");
  885. fprintf(ofp, "from Core import *\n\n\n");
  886. fprintf(ofp, "def trace_begin():\n");
  887. fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
  888. fprintf(ofp, "def trace_end():\n");
  889. fprintf(ofp, "\tprint \"in trace_end\"\n\n");
  890. while ((event = trace_find_next_event(pevent, event))) {
  891. fprintf(ofp, "def %s__%s(", event->system, event->name);
  892. fprintf(ofp, "event_name, ");
  893. fprintf(ofp, "context, ");
  894. fprintf(ofp, "common_cpu,\n");
  895. fprintf(ofp, "\tcommon_secs, ");
  896. fprintf(ofp, "common_nsecs, ");
  897. fprintf(ofp, "common_pid, ");
  898. fprintf(ofp, "common_comm,\n\t");
  899. fprintf(ofp, "common_callchain, ");
  900. not_first = 0;
  901. count = 0;
  902. for (f = event->format.fields; f; f = f->next) {
  903. if (not_first++)
  904. fprintf(ofp, ", ");
  905. if (++count % 5 == 0)
  906. fprintf(ofp, "\n\t");
  907. fprintf(ofp, "%s", f->name);
  908. }
  909. fprintf(ofp, "):\n");
  910. fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
  911. "common_secs, common_nsecs,\n\t\t\t"
  912. "common_pid, common_comm)\n\n");
  913. fprintf(ofp, "\t\tprint \"");
  914. not_first = 0;
  915. count = 0;
  916. for (f = event->format.fields; f; f = f->next) {
  917. if (not_first++)
  918. fprintf(ofp, ", ");
  919. if (count && count % 3 == 0) {
  920. fprintf(ofp, "\" \\\n\t\t\"");
  921. }
  922. count++;
  923. fprintf(ofp, "%s=", f->name);
  924. if (f->flags & FIELD_IS_STRING ||
  925. f->flags & FIELD_IS_FLAG ||
  926. f->flags & FIELD_IS_ARRAY ||
  927. f->flags & FIELD_IS_SYMBOLIC)
  928. fprintf(ofp, "%%s");
  929. else if (f->flags & FIELD_IS_SIGNED)
  930. fprintf(ofp, "%%d");
  931. else
  932. fprintf(ofp, "%%u");
  933. }
  934. fprintf(ofp, "\" %% \\\n\t\t(");
  935. not_first = 0;
  936. count = 0;
  937. for (f = event->format.fields; f; f = f->next) {
  938. if (not_first++)
  939. fprintf(ofp, ", ");
  940. if (++count % 5 == 0)
  941. fprintf(ofp, "\n\t\t");
  942. if (f->flags & FIELD_IS_FLAG) {
  943. if ((count - 1) % 5 != 0) {
  944. fprintf(ofp, "\n\t\t");
  945. count = 4;
  946. }
  947. fprintf(ofp, "flag_str(\"");
  948. fprintf(ofp, "%s__%s\", ", event->system,
  949. event->name);
  950. fprintf(ofp, "\"%s\", %s)", f->name,
  951. f->name);
  952. } else if (f->flags & FIELD_IS_SYMBOLIC) {
  953. if ((count - 1) % 5 != 0) {
  954. fprintf(ofp, "\n\t\t");
  955. count = 4;
  956. }
  957. fprintf(ofp, "symbol_str(\"");
  958. fprintf(ofp, "%s__%s\", ", event->system,
  959. event->name);
  960. fprintf(ofp, "\"%s\", %s)", f->name,
  961. f->name);
  962. } else
  963. fprintf(ofp, "%s", f->name);
  964. }
  965. fprintf(ofp, ")\n\n");
  966. fprintf(ofp, "\t\tfor node in common_callchain:");
  967. fprintf(ofp, "\n\t\t\tif 'sym' in node:");
  968. fprintf(ofp, "\n\t\t\t\tprint \"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name'])");
  969. fprintf(ofp, "\n\t\t\telse:");
  970. fprintf(ofp, "\n\t\t\t\tprint \"\t[%%x]\" %% (node['ip'])\n\n");
  971. fprintf(ofp, "\t\tprint \"\\n\"\n\n");
  972. }
  973. fprintf(ofp, "def trace_unhandled(event_name, context, "
  974. "event_fields_dict):\n");
  975. fprintf(ofp, "\t\tprint ' '.join(['%%s=%%s'%%(k,str(v))"
  976. "for k,v in sorted(event_fields_dict.items())])\n\n");
  977. fprintf(ofp, "def print_header("
  978. "event_name, cpu, secs, nsecs, pid, comm):\n"
  979. "\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
  980. "(event_name, cpu, secs, nsecs, pid, comm),\n");
  981. fclose(ofp);
  982. fprintf(stderr, "generated Python script: %s\n", fname);
  983. return 0;
  984. }
  985. struct scripting_ops python_scripting_ops = {
  986. .name = "Python",
  987. .start_script = python_start_script,
  988. .flush_script = python_flush_script,
  989. .stop_script = python_stop_script,
  990. .process_event = python_process_event,
  991. .generate_script = python_generate_script,
  992. };