trace-event-python.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  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 <errno.h>
  26. #include "../../perf.h"
  27. #include "../debug.h"
  28. #include "../evsel.h"
  29. #include "../util.h"
  30. #include "../event.h"
  31. #include "../thread.h"
  32. #include "../trace-event.h"
  33. #include "../machine.h"
  34. PyMODINIT_FUNC initperf_trace_context(void);
  35. #define FTRACE_MAX_EVENT \
  36. ((1 << (sizeof(unsigned short) * 8)) - 1)
  37. struct event_format *events[FTRACE_MAX_EVENT];
  38. #define MAX_FIELDS 64
  39. #define N_COMMON_FIELDS 7
  40. extern struct scripting_context *scripting_context;
  41. static char *cur_field_name;
  42. static int zero_flag_atom;
  43. static PyObject *main_module, *main_dict;
  44. static void handler_call_die(const char *handler_name) NORETURN;
  45. static void handler_call_die(const char *handler_name)
  46. {
  47. PyErr_Print();
  48. Py_FatalError("problem in Python trace event handler");
  49. // Py_FatalError does not return
  50. // but we have to make the compiler happy
  51. abort();
  52. }
  53. /*
  54. * Insert val into into the dictionary and decrement the reference counter.
  55. * This is necessary for dictionaries since PyDict_SetItemString() does not
  56. * steal a reference, as opposed to PyTuple_SetItem().
  57. */
  58. static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
  59. {
  60. PyDict_SetItemString(dict, key, val);
  61. Py_DECREF(val);
  62. }
  63. static void define_value(enum print_arg_type field_type,
  64. const char *ev_name,
  65. const char *field_name,
  66. const char *field_value,
  67. const char *field_str)
  68. {
  69. const char *handler_name = "define_flag_value";
  70. PyObject *handler, *t, *retval;
  71. unsigned long long value;
  72. unsigned n = 0;
  73. if (field_type == PRINT_SYMBOL)
  74. handler_name = "define_symbolic_value";
  75. t = PyTuple_New(4);
  76. if (!t)
  77. Py_FatalError("couldn't create Python tuple");
  78. value = eval_flag(field_value);
  79. PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
  80. PyTuple_SetItem(t, n++, PyString_FromString(field_name));
  81. PyTuple_SetItem(t, n++, PyInt_FromLong(value));
  82. PyTuple_SetItem(t, n++, PyString_FromString(field_str));
  83. handler = PyDict_GetItemString(main_dict, handler_name);
  84. if (handler && PyCallable_Check(handler)) {
  85. retval = PyObject_CallObject(handler, t);
  86. if (retval == NULL)
  87. handler_call_die(handler_name);
  88. Py_DECREF(retval);
  89. }
  90. Py_DECREF(t);
  91. }
  92. static void define_values(enum print_arg_type field_type,
  93. struct print_flag_sym *field,
  94. const char *ev_name,
  95. const char *field_name)
  96. {
  97. define_value(field_type, ev_name, field_name, field->value,
  98. field->str);
  99. if (field->next)
  100. define_values(field_type, field->next, ev_name, field_name);
  101. }
  102. static void define_field(enum print_arg_type field_type,
  103. const char *ev_name,
  104. const char *field_name,
  105. const char *delim)
  106. {
  107. const char *handler_name = "define_flag_field";
  108. PyObject *handler, *t, *retval;
  109. unsigned n = 0;
  110. if (field_type == PRINT_SYMBOL)
  111. handler_name = "define_symbolic_field";
  112. if (field_type == PRINT_FLAGS)
  113. t = PyTuple_New(3);
  114. else
  115. t = PyTuple_New(2);
  116. if (!t)
  117. Py_FatalError("couldn't create Python tuple");
  118. PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
  119. PyTuple_SetItem(t, n++, PyString_FromString(field_name));
  120. if (field_type == PRINT_FLAGS)
  121. PyTuple_SetItem(t, n++, PyString_FromString(delim));
  122. handler = PyDict_GetItemString(main_dict, handler_name);
  123. if (handler && PyCallable_Check(handler)) {
  124. retval = PyObject_CallObject(handler, t);
  125. if (retval == NULL)
  126. handler_call_die(handler_name);
  127. Py_DECREF(retval);
  128. }
  129. Py_DECREF(t);
  130. }
  131. static void define_event_symbols(struct event_format *event,
  132. const char *ev_name,
  133. struct print_arg *args)
  134. {
  135. switch (args->type) {
  136. case PRINT_NULL:
  137. break;
  138. case PRINT_ATOM:
  139. define_value(PRINT_FLAGS, ev_name, cur_field_name, "0",
  140. args->atom.atom);
  141. zero_flag_atom = 0;
  142. break;
  143. case PRINT_FIELD:
  144. free(cur_field_name);
  145. cur_field_name = strdup(args->field.name);
  146. break;
  147. case PRINT_FLAGS:
  148. define_event_symbols(event, ev_name, args->flags.field);
  149. define_field(PRINT_FLAGS, ev_name, cur_field_name,
  150. args->flags.delim);
  151. define_values(PRINT_FLAGS, args->flags.flags, ev_name,
  152. cur_field_name);
  153. break;
  154. case PRINT_SYMBOL:
  155. define_event_symbols(event, ev_name, args->symbol.field);
  156. define_field(PRINT_SYMBOL, ev_name, cur_field_name, NULL);
  157. define_values(PRINT_SYMBOL, args->symbol.symbols, ev_name,
  158. cur_field_name);
  159. break;
  160. case PRINT_HEX:
  161. define_event_symbols(event, ev_name, args->hex.field);
  162. define_event_symbols(event, ev_name, args->hex.size);
  163. break;
  164. case PRINT_STRING:
  165. break;
  166. case PRINT_TYPE:
  167. define_event_symbols(event, ev_name, args->typecast.item);
  168. break;
  169. case PRINT_OP:
  170. if (strcmp(args->op.op, ":") == 0)
  171. zero_flag_atom = 1;
  172. define_event_symbols(event, ev_name, args->op.left);
  173. define_event_symbols(event, ev_name, args->op.right);
  174. break;
  175. default:
  176. /* gcc warns for these? */
  177. case PRINT_BSTRING:
  178. case PRINT_DYNAMIC_ARRAY:
  179. case PRINT_FUNC:
  180. case PRINT_BITMASK:
  181. /* we should warn... */
  182. return;
  183. }
  184. if (args->next)
  185. define_event_symbols(event, ev_name, args->next);
  186. }
  187. static inline struct event_format *find_cache_event(struct perf_evsel *evsel)
  188. {
  189. static char ev_name[256];
  190. struct event_format *event;
  191. int type = evsel->attr.config;
  192. /*
  193. * XXX: Do we really need to cache this since now we have evsel->tp_format
  194. * cached already? Need to re-read this "cache" routine that as well calls
  195. * define_event_symbols() :-\
  196. */
  197. if (events[type])
  198. return events[type];
  199. events[type] = event = evsel->tp_format;
  200. if (!event)
  201. return NULL;
  202. sprintf(ev_name, "%s__%s", event->system, event->name);
  203. define_event_symbols(event, ev_name, event->print_fmt.args);
  204. return event;
  205. }
  206. static PyObject *get_field_numeric_entry(struct event_format *event,
  207. struct format_field *field, void *data)
  208. {
  209. bool is_array = field->flags & FIELD_IS_ARRAY;
  210. PyObject *obj, *list = NULL;
  211. unsigned long long val;
  212. unsigned int item_size, n_items, i;
  213. if (is_array) {
  214. list = PyList_New(field->arraylen);
  215. item_size = field->size / field->arraylen;
  216. n_items = field->arraylen;
  217. } else {
  218. item_size = field->size;
  219. n_items = 1;
  220. }
  221. for (i = 0; i < n_items; i++) {
  222. val = read_size(event, data + field->offset + i * item_size,
  223. item_size);
  224. if (field->flags & FIELD_IS_SIGNED) {
  225. if ((long long)val >= LONG_MIN &&
  226. (long long)val <= LONG_MAX)
  227. obj = PyInt_FromLong(val);
  228. else
  229. obj = PyLong_FromLongLong(val);
  230. } else {
  231. if (val <= LONG_MAX)
  232. obj = PyInt_FromLong(val);
  233. else
  234. obj = PyLong_FromUnsignedLongLong(val);
  235. }
  236. if (is_array)
  237. PyList_SET_ITEM(list, i, obj);
  238. }
  239. if (is_array)
  240. obj = list;
  241. return obj;
  242. }
  243. static PyObject *python_process_callchain(struct perf_sample *sample,
  244. struct perf_evsel *evsel,
  245. struct addr_location *al)
  246. {
  247. PyObject *pylist;
  248. pylist = PyList_New(0);
  249. if (!pylist)
  250. Py_FatalError("couldn't create Python list");
  251. if (!symbol_conf.use_callchain || !sample->callchain)
  252. goto exit;
  253. if (machine__resolve_callchain(al->machine, evsel, al->thread,
  254. sample, NULL, NULL,
  255. PERF_MAX_STACK_DEPTH) != 0) {
  256. pr_err("Failed to resolve callchain. Skipping\n");
  257. goto exit;
  258. }
  259. callchain_cursor_commit(&callchain_cursor);
  260. while (1) {
  261. PyObject *pyelem;
  262. struct callchain_cursor_node *node;
  263. node = callchain_cursor_current(&callchain_cursor);
  264. if (!node)
  265. break;
  266. pyelem = PyDict_New();
  267. if (!pyelem)
  268. Py_FatalError("couldn't create Python dictionary");
  269. pydict_set_item_string_decref(pyelem, "ip",
  270. PyLong_FromUnsignedLongLong(node->ip));
  271. if (node->sym) {
  272. PyObject *pysym = PyDict_New();
  273. if (!pysym)
  274. Py_FatalError("couldn't create Python dictionary");
  275. pydict_set_item_string_decref(pysym, "start",
  276. PyLong_FromUnsignedLongLong(node->sym->start));
  277. pydict_set_item_string_decref(pysym, "end",
  278. PyLong_FromUnsignedLongLong(node->sym->end));
  279. pydict_set_item_string_decref(pysym, "binding",
  280. PyInt_FromLong(node->sym->binding));
  281. pydict_set_item_string_decref(pysym, "name",
  282. PyString_FromStringAndSize(node->sym->name,
  283. node->sym->namelen));
  284. pydict_set_item_string_decref(pyelem, "sym", pysym);
  285. }
  286. if (node->map) {
  287. struct map *map = node->map;
  288. const char *dsoname = "[unknown]";
  289. if (map && map->dso && (map->dso->name || map->dso->long_name)) {
  290. if (symbol_conf.show_kernel_path && map->dso->long_name)
  291. dsoname = map->dso->long_name;
  292. else if (map->dso->name)
  293. dsoname = map->dso->name;
  294. }
  295. pydict_set_item_string_decref(pyelem, "dso",
  296. PyString_FromString(dsoname));
  297. }
  298. callchain_cursor_advance(&callchain_cursor);
  299. PyList_Append(pylist, pyelem);
  300. Py_DECREF(pyelem);
  301. }
  302. exit:
  303. return pylist;
  304. }
  305. static void python_process_tracepoint(struct perf_sample *sample,
  306. struct perf_evsel *evsel,
  307. struct thread *thread,
  308. struct addr_location *al)
  309. {
  310. PyObject *handler, *retval, *context, *t, *obj, *callchain;
  311. PyObject *dict = NULL;
  312. static char handler_name[256];
  313. struct format_field *field;
  314. unsigned long s, ns;
  315. struct event_format *event;
  316. unsigned n = 0;
  317. int pid;
  318. int cpu = sample->cpu;
  319. void *data = sample->raw_data;
  320. unsigned long long nsecs = sample->time;
  321. const char *comm = thread__comm_str(thread);
  322. t = PyTuple_New(MAX_FIELDS);
  323. if (!t)
  324. Py_FatalError("couldn't create Python tuple");
  325. event = find_cache_event(evsel);
  326. if (!event)
  327. die("ug! no event found for type %d", (int)evsel->attr.config);
  328. pid = raw_field_value(event, "common_pid", data);
  329. sprintf(handler_name, "%s__%s", event->system, event->name);
  330. handler = PyDict_GetItemString(main_dict, handler_name);
  331. if (handler && !PyCallable_Check(handler))
  332. handler = NULL;
  333. if (!handler) {
  334. dict = PyDict_New();
  335. if (!dict)
  336. Py_FatalError("couldn't create Python dict");
  337. }
  338. s = nsecs / NSECS_PER_SEC;
  339. ns = nsecs - s * NSECS_PER_SEC;
  340. scripting_context->event_data = data;
  341. scripting_context->pevent = evsel->tp_format->pevent;
  342. context = PyCObject_FromVoidPtr(scripting_context, NULL);
  343. PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
  344. PyTuple_SetItem(t, n++, context);
  345. /* ip unwinding */
  346. callchain = python_process_callchain(sample, evsel, al);
  347. if (handler) {
  348. PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
  349. PyTuple_SetItem(t, n++, PyInt_FromLong(s));
  350. PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
  351. PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
  352. PyTuple_SetItem(t, n++, PyString_FromString(comm));
  353. PyTuple_SetItem(t, n++, callchain);
  354. } else {
  355. pydict_set_item_string_decref(dict, "common_cpu", PyInt_FromLong(cpu));
  356. pydict_set_item_string_decref(dict, "common_s", PyInt_FromLong(s));
  357. pydict_set_item_string_decref(dict, "common_ns", PyInt_FromLong(ns));
  358. pydict_set_item_string_decref(dict, "common_pid", PyInt_FromLong(pid));
  359. pydict_set_item_string_decref(dict, "common_comm", PyString_FromString(comm));
  360. pydict_set_item_string_decref(dict, "common_callchain", callchain);
  361. }
  362. for (field = event->format.fields; field; field = field->next) {
  363. if (field->flags & FIELD_IS_STRING) {
  364. int offset;
  365. if (field->flags & FIELD_IS_DYNAMIC) {
  366. offset = *(int *)(data + field->offset);
  367. offset &= 0xffff;
  368. } else
  369. offset = field->offset;
  370. obj = PyString_FromString((char *)data + offset);
  371. } else { /* FIELD_IS_NUMERIC */
  372. obj = get_field_numeric_entry(event, field, data);
  373. }
  374. if (handler)
  375. PyTuple_SetItem(t, n++, obj);
  376. else
  377. pydict_set_item_string_decref(dict, field->name, obj);
  378. }
  379. if (!handler)
  380. PyTuple_SetItem(t, n++, dict);
  381. if (_PyTuple_Resize(&t, n) == -1)
  382. Py_FatalError("error resizing Python tuple");
  383. if (handler) {
  384. retval = PyObject_CallObject(handler, t);
  385. if (retval == NULL)
  386. handler_call_die(handler_name);
  387. Py_DECREF(retval);
  388. } else {
  389. handler = PyDict_GetItemString(main_dict, "trace_unhandled");
  390. if (handler && PyCallable_Check(handler)) {
  391. retval = PyObject_CallObject(handler, t);
  392. if (retval == NULL)
  393. handler_call_die("trace_unhandled");
  394. Py_DECREF(retval);
  395. }
  396. Py_DECREF(dict);
  397. }
  398. Py_DECREF(t);
  399. }
  400. static void python_process_general_event(struct perf_sample *sample,
  401. struct perf_evsel *evsel,
  402. struct thread *thread,
  403. struct addr_location *al)
  404. {
  405. PyObject *handler, *retval, *t, *dict, *callchain, *dict_sample;
  406. static char handler_name[64];
  407. unsigned n = 0;
  408. /*
  409. * Use the MAX_FIELDS to make the function expandable, though
  410. * currently there is only one item for the tuple.
  411. */
  412. t = PyTuple_New(MAX_FIELDS);
  413. if (!t)
  414. Py_FatalError("couldn't create Python tuple");
  415. dict = PyDict_New();
  416. if (!dict)
  417. Py_FatalError("couldn't create Python dictionary");
  418. dict_sample = PyDict_New();
  419. if (!dict_sample)
  420. Py_FatalError("couldn't create Python dictionary");
  421. snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
  422. handler = PyDict_GetItemString(main_dict, handler_name);
  423. if (!handler || !PyCallable_Check(handler))
  424. goto exit;
  425. pydict_set_item_string_decref(dict, "ev_name", PyString_FromString(perf_evsel__name(evsel)));
  426. pydict_set_item_string_decref(dict, "attr", PyString_FromStringAndSize(
  427. (const char *)&evsel->attr, sizeof(evsel->attr)));
  428. pydict_set_item_string_decref(dict_sample, "pid",
  429. PyInt_FromLong(sample->pid));
  430. pydict_set_item_string_decref(dict_sample, "tid",
  431. PyInt_FromLong(sample->tid));
  432. pydict_set_item_string_decref(dict_sample, "cpu",
  433. PyInt_FromLong(sample->cpu));
  434. pydict_set_item_string_decref(dict_sample, "ip",
  435. PyLong_FromUnsignedLongLong(sample->ip));
  436. pydict_set_item_string_decref(dict_sample, "time",
  437. PyLong_FromUnsignedLongLong(sample->time));
  438. pydict_set_item_string_decref(dict_sample, "period",
  439. PyLong_FromUnsignedLongLong(sample->period));
  440. pydict_set_item_string_decref(dict, "sample", dict_sample);
  441. pydict_set_item_string_decref(dict, "raw_buf", PyString_FromStringAndSize(
  442. (const char *)sample->raw_data, sample->raw_size));
  443. pydict_set_item_string_decref(dict, "comm",
  444. PyString_FromString(thread__comm_str(thread)));
  445. if (al->map) {
  446. pydict_set_item_string_decref(dict, "dso",
  447. PyString_FromString(al->map->dso->name));
  448. }
  449. if (al->sym) {
  450. pydict_set_item_string_decref(dict, "symbol",
  451. PyString_FromString(al->sym->name));
  452. }
  453. /* ip unwinding */
  454. callchain = python_process_callchain(sample, evsel, al);
  455. pydict_set_item_string_decref(dict, "callchain", callchain);
  456. PyTuple_SetItem(t, n++, dict);
  457. if (_PyTuple_Resize(&t, n) == -1)
  458. Py_FatalError("error resizing Python tuple");
  459. retval = PyObject_CallObject(handler, t);
  460. if (retval == NULL)
  461. handler_call_die(handler_name);
  462. Py_DECREF(retval);
  463. exit:
  464. Py_DECREF(dict);
  465. Py_DECREF(t);
  466. }
  467. static void python_process_event(union perf_event *event __maybe_unused,
  468. struct perf_sample *sample,
  469. struct perf_evsel *evsel,
  470. struct thread *thread,
  471. struct addr_location *al)
  472. {
  473. switch (evsel->attr.type) {
  474. case PERF_TYPE_TRACEPOINT:
  475. python_process_tracepoint(sample, evsel, thread, al);
  476. break;
  477. /* Reserve for future process_hw/sw/raw APIs */
  478. default:
  479. python_process_general_event(sample, evsel, thread, al);
  480. }
  481. }
  482. static int run_start_sub(void)
  483. {
  484. PyObject *handler, *retval;
  485. int err = 0;
  486. main_module = PyImport_AddModule("__main__");
  487. if (main_module == NULL)
  488. return -1;
  489. Py_INCREF(main_module);
  490. main_dict = PyModule_GetDict(main_module);
  491. if (main_dict == NULL) {
  492. err = -1;
  493. goto error;
  494. }
  495. Py_INCREF(main_dict);
  496. handler = PyDict_GetItemString(main_dict, "trace_begin");
  497. if (handler == NULL || !PyCallable_Check(handler))
  498. goto out;
  499. retval = PyObject_CallObject(handler, NULL);
  500. if (retval == NULL)
  501. handler_call_die("trace_begin");
  502. Py_DECREF(retval);
  503. return err;
  504. error:
  505. Py_XDECREF(main_dict);
  506. Py_XDECREF(main_module);
  507. out:
  508. return err;
  509. }
  510. /*
  511. * Start trace script
  512. */
  513. static int python_start_script(const char *script, int argc, const char **argv)
  514. {
  515. const char **command_line;
  516. char buf[PATH_MAX];
  517. int i, err = 0;
  518. FILE *fp;
  519. command_line = malloc((argc + 1) * sizeof(const char *));
  520. command_line[0] = script;
  521. for (i = 1; i < argc + 1; i++)
  522. command_line[i] = argv[i - 1];
  523. Py_Initialize();
  524. initperf_trace_context();
  525. PySys_SetArgv(argc + 1, (char **)command_line);
  526. fp = fopen(script, "r");
  527. if (!fp) {
  528. sprintf(buf, "Can't open python script \"%s\"", script);
  529. perror(buf);
  530. err = -1;
  531. goto error;
  532. }
  533. err = PyRun_SimpleFile(fp, script);
  534. if (err) {
  535. fprintf(stderr, "Error running python script %s\n", script);
  536. goto error;
  537. }
  538. err = run_start_sub();
  539. if (err) {
  540. fprintf(stderr, "Error starting python script %s\n", script);
  541. goto error;
  542. }
  543. free(command_line);
  544. return err;
  545. error:
  546. Py_Finalize();
  547. free(command_line);
  548. return err;
  549. }
  550. /*
  551. * Stop trace script
  552. */
  553. static int python_stop_script(void)
  554. {
  555. PyObject *handler, *retval;
  556. int err = 0;
  557. handler = PyDict_GetItemString(main_dict, "trace_end");
  558. if (handler == NULL || !PyCallable_Check(handler))
  559. goto out;
  560. retval = PyObject_CallObject(handler, NULL);
  561. if (retval == NULL)
  562. handler_call_die("trace_end");
  563. Py_DECREF(retval);
  564. out:
  565. Py_XDECREF(main_dict);
  566. Py_XDECREF(main_module);
  567. Py_Finalize();
  568. return err;
  569. }
  570. static int python_generate_script(struct pevent *pevent, const char *outfile)
  571. {
  572. struct event_format *event = NULL;
  573. struct format_field *f;
  574. char fname[PATH_MAX];
  575. int not_first, count;
  576. FILE *ofp;
  577. sprintf(fname, "%s.py", outfile);
  578. ofp = fopen(fname, "w");
  579. if (ofp == NULL) {
  580. fprintf(stderr, "couldn't open %s\n", fname);
  581. return -1;
  582. }
  583. fprintf(ofp, "# perf script event handlers, "
  584. "generated by perf script -g python\n");
  585. fprintf(ofp, "# Licensed under the terms of the GNU GPL"
  586. " License version 2\n\n");
  587. fprintf(ofp, "# The common_* event handler fields are the most useful "
  588. "fields common to\n");
  589. fprintf(ofp, "# all events. They don't necessarily correspond to "
  590. "the 'common_*' fields\n");
  591. fprintf(ofp, "# in the format files. Those fields not available as "
  592. "handler params can\n");
  593. fprintf(ofp, "# be retrieved using Python functions of the form "
  594. "common_*(context).\n");
  595. fprintf(ofp, "# See the perf-trace-python Documentation for the list "
  596. "of available functions.\n\n");
  597. fprintf(ofp, "import os\n");
  598. fprintf(ofp, "import sys\n\n");
  599. fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
  600. fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
  601. fprintf(ofp, "\nfrom perf_trace_context import *\n");
  602. fprintf(ofp, "from Core import *\n\n\n");
  603. fprintf(ofp, "def trace_begin():\n");
  604. fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
  605. fprintf(ofp, "def trace_end():\n");
  606. fprintf(ofp, "\tprint \"in trace_end\"\n\n");
  607. while ((event = trace_find_next_event(pevent, event))) {
  608. fprintf(ofp, "def %s__%s(", event->system, event->name);
  609. fprintf(ofp, "event_name, ");
  610. fprintf(ofp, "context, ");
  611. fprintf(ofp, "common_cpu,\n");
  612. fprintf(ofp, "\tcommon_secs, ");
  613. fprintf(ofp, "common_nsecs, ");
  614. fprintf(ofp, "common_pid, ");
  615. fprintf(ofp, "common_comm,\n\t");
  616. fprintf(ofp, "common_callchain, ");
  617. not_first = 0;
  618. count = 0;
  619. for (f = event->format.fields; f; f = f->next) {
  620. if (not_first++)
  621. fprintf(ofp, ", ");
  622. if (++count % 5 == 0)
  623. fprintf(ofp, "\n\t");
  624. fprintf(ofp, "%s", f->name);
  625. }
  626. fprintf(ofp, "):\n");
  627. fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
  628. "common_secs, common_nsecs,\n\t\t\t"
  629. "common_pid, common_comm)\n\n");
  630. fprintf(ofp, "\t\tprint \"");
  631. not_first = 0;
  632. count = 0;
  633. for (f = event->format.fields; f; f = f->next) {
  634. if (not_first++)
  635. fprintf(ofp, ", ");
  636. if (count && count % 3 == 0) {
  637. fprintf(ofp, "\" \\\n\t\t\"");
  638. }
  639. count++;
  640. fprintf(ofp, "%s=", f->name);
  641. if (f->flags & FIELD_IS_STRING ||
  642. f->flags & FIELD_IS_FLAG ||
  643. f->flags & FIELD_IS_ARRAY ||
  644. f->flags & FIELD_IS_SYMBOLIC)
  645. fprintf(ofp, "%%s");
  646. else if (f->flags & FIELD_IS_SIGNED)
  647. fprintf(ofp, "%%d");
  648. else
  649. fprintf(ofp, "%%u");
  650. }
  651. fprintf(ofp, "\" %% \\\n\t\t(");
  652. not_first = 0;
  653. count = 0;
  654. for (f = event->format.fields; f; f = f->next) {
  655. if (not_first++)
  656. fprintf(ofp, ", ");
  657. if (++count % 5 == 0)
  658. fprintf(ofp, "\n\t\t");
  659. if (f->flags & FIELD_IS_FLAG) {
  660. if ((count - 1) % 5 != 0) {
  661. fprintf(ofp, "\n\t\t");
  662. count = 4;
  663. }
  664. fprintf(ofp, "flag_str(\"");
  665. fprintf(ofp, "%s__%s\", ", event->system,
  666. event->name);
  667. fprintf(ofp, "\"%s\", %s)", f->name,
  668. f->name);
  669. } else if (f->flags & FIELD_IS_SYMBOLIC) {
  670. if ((count - 1) % 5 != 0) {
  671. fprintf(ofp, "\n\t\t");
  672. count = 4;
  673. }
  674. fprintf(ofp, "symbol_str(\"");
  675. fprintf(ofp, "%s__%s\", ", event->system,
  676. event->name);
  677. fprintf(ofp, "\"%s\", %s)", f->name,
  678. f->name);
  679. } else
  680. fprintf(ofp, "%s", f->name);
  681. }
  682. fprintf(ofp, ")\n\n");
  683. fprintf(ofp, "\t\tfor node in common_callchain:");
  684. fprintf(ofp, "\n\t\t\tif 'sym' in node:");
  685. fprintf(ofp, "\n\t\t\t\tprint \"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name'])");
  686. fprintf(ofp, "\n\t\t\telse:");
  687. fprintf(ofp, "\n\t\t\t\tprint \"\t[%%x]\" %% (node['ip'])\n\n");
  688. fprintf(ofp, "\t\tprint \"\\n\"\n\n");
  689. }
  690. fprintf(ofp, "def trace_unhandled(event_name, context, "
  691. "event_fields_dict):\n");
  692. fprintf(ofp, "\t\tprint ' '.join(['%%s=%%s'%%(k,str(v))"
  693. "for k,v in sorted(event_fields_dict.items())])\n\n");
  694. fprintf(ofp, "def print_header("
  695. "event_name, cpu, secs, nsecs, pid, comm):\n"
  696. "\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
  697. "(event_name, cpu, secs, nsecs, pid, comm),\n");
  698. fclose(ofp);
  699. fprintf(stderr, "generated Python script: %s\n", fname);
  700. return 0;
  701. }
  702. struct scripting_ops python_scripting_ops = {
  703. .name = "Python",
  704. .start_script = python_start_script,
  705. .stop_script = python_stop_script,
  706. .process_event = python_process_event,
  707. .generate_script = python_generate_script,
  708. };