trace-event-python.c 29 KB

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