trace-event-python.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  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 "../evsel.h"
  28. #include "../util.h"
  29. #include "../event.h"
  30. #include "../thread.h"
  31. #include "../trace-event.h"
  32. #include "../evsel.h"
  33. PyMODINIT_FUNC initperf_trace_context(void);
  34. #define FTRACE_MAX_EVENT \
  35. ((1 << (sizeof(unsigned short) * 8)) - 1)
  36. struct event_format *events[FTRACE_MAX_EVENT];
  37. #define MAX_FIELDS 64
  38. #define N_COMMON_FIELDS 7
  39. extern struct scripting_context *scripting_context;
  40. static char *cur_field_name;
  41. static int zero_flag_atom;
  42. static PyObject *main_module, *main_dict;
  43. static void handler_call_die(const char *handler_name)
  44. {
  45. PyErr_Print();
  46. Py_FatalError("problem in Python trace event handler");
  47. }
  48. static void define_value(enum print_arg_type field_type,
  49. const char *ev_name,
  50. const char *field_name,
  51. const char *field_value,
  52. const char *field_str)
  53. {
  54. const char *handler_name = "define_flag_value";
  55. PyObject *handler, *t, *retval;
  56. unsigned long long value;
  57. unsigned n = 0;
  58. if (field_type == PRINT_SYMBOL)
  59. handler_name = "define_symbolic_value";
  60. t = PyTuple_New(4);
  61. if (!t)
  62. Py_FatalError("couldn't create Python tuple");
  63. value = eval_flag(field_value);
  64. PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
  65. PyTuple_SetItem(t, n++, PyString_FromString(field_name));
  66. PyTuple_SetItem(t, n++, PyInt_FromLong(value));
  67. PyTuple_SetItem(t, n++, PyString_FromString(field_str));
  68. handler = PyDict_GetItemString(main_dict, handler_name);
  69. if (handler && PyCallable_Check(handler)) {
  70. retval = PyObject_CallObject(handler, t);
  71. if (retval == NULL)
  72. handler_call_die(handler_name);
  73. }
  74. Py_DECREF(t);
  75. }
  76. static void define_values(enum print_arg_type field_type,
  77. struct print_flag_sym *field,
  78. const char *ev_name,
  79. const char *field_name)
  80. {
  81. define_value(field_type, ev_name, field_name, field->value,
  82. field->str);
  83. if (field->next)
  84. define_values(field_type, field->next, ev_name, field_name);
  85. }
  86. static void define_field(enum print_arg_type field_type,
  87. const char *ev_name,
  88. const char *field_name,
  89. const char *delim)
  90. {
  91. const char *handler_name = "define_flag_field";
  92. PyObject *handler, *t, *retval;
  93. unsigned n = 0;
  94. if (field_type == PRINT_SYMBOL)
  95. handler_name = "define_symbolic_field";
  96. if (field_type == PRINT_FLAGS)
  97. t = PyTuple_New(3);
  98. else
  99. t = PyTuple_New(2);
  100. if (!t)
  101. Py_FatalError("couldn't create Python tuple");
  102. PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
  103. PyTuple_SetItem(t, n++, PyString_FromString(field_name));
  104. if (field_type == PRINT_FLAGS)
  105. PyTuple_SetItem(t, n++, PyString_FromString(delim));
  106. handler = PyDict_GetItemString(main_dict, handler_name);
  107. if (handler && PyCallable_Check(handler)) {
  108. retval = PyObject_CallObject(handler, t);
  109. if (retval == NULL)
  110. handler_call_die(handler_name);
  111. }
  112. Py_DECREF(t);
  113. }
  114. static void define_event_symbols(struct event_format *event,
  115. const char *ev_name,
  116. struct print_arg *args)
  117. {
  118. switch (args->type) {
  119. case PRINT_NULL:
  120. break;
  121. case PRINT_ATOM:
  122. define_value(PRINT_FLAGS, ev_name, cur_field_name, "0",
  123. args->atom.atom);
  124. zero_flag_atom = 0;
  125. break;
  126. case PRINT_FIELD:
  127. if (cur_field_name)
  128. free(cur_field_name);
  129. cur_field_name = strdup(args->field.name);
  130. break;
  131. case PRINT_FLAGS:
  132. define_event_symbols(event, ev_name, args->flags.field);
  133. define_field(PRINT_FLAGS, ev_name, cur_field_name,
  134. args->flags.delim);
  135. define_values(PRINT_FLAGS, args->flags.flags, ev_name,
  136. cur_field_name);
  137. break;
  138. case PRINT_SYMBOL:
  139. define_event_symbols(event, ev_name, args->symbol.field);
  140. define_field(PRINT_SYMBOL, ev_name, cur_field_name, NULL);
  141. define_values(PRINT_SYMBOL, args->symbol.symbols, ev_name,
  142. cur_field_name);
  143. break;
  144. case PRINT_HEX:
  145. define_event_symbols(event, ev_name, args->hex.field);
  146. define_event_symbols(event, ev_name, args->hex.size);
  147. break;
  148. case PRINT_STRING:
  149. break;
  150. case PRINT_TYPE:
  151. define_event_symbols(event, ev_name, args->typecast.item);
  152. break;
  153. case PRINT_OP:
  154. if (strcmp(args->op.op, ":") == 0)
  155. zero_flag_atom = 1;
  156. define_event_symbols(event, ev_name, args->op.left);
  157. define_event_symbols(event, ev_name, args->op.right);
  158. break;
  159. default:
  160. /* gcc warns for these? */
  161. case PRINT_BSTRING:
  162. case PRINT_DYNAMIC_ARRAY:
  163. case PRINT_FUNC:
  164. /* we should warn... */
  165. return;
  166. }
  167. if (args->next)
  168. define_event_symbols(event, ev_name, args->next);
  169. }
  170. static inline struct event_format *find_cache_event(struct perf_evsel *evsel)
  171. {
  172. static char ev_name[256];
  173. struct event_format *event;
  174. int type = evsel->attr.config;
  175. /*
  176. * XXX: Do we really need to cache this since now we have evsel->tp_format
  177. * cached already? Need to re-read this "cache" routine that as well calls
  178. * define_event_symbols() :-\
  179. */
  180. if (events[type])
  181. return events[type];
  182. events[type] = event = evsel->tp_format;
  183. if (!event)
  184. return NULL;
  185. sprintf(ev_name, "%s__%s", event->system, event->name);
  186. define_event_symbols(event, ev_name, event->print_fmt.args);
  187. return event;
  188. }
  189. static void python_process_tracepoint(union perf_event *perf_event __unused,
  190. struct perf_sample *sample,
  191. struct perf_evsel *evsel,
  192. struct machine *machine __unused,
  193. struct addr_location *al)
  194. {
  195. PyObject *handler, *retval, *context, *t, *obj, *dict = NULL;
  196. static char handler_name[256];
  197. struct format_field *field;
  198. unsigned long long val;
  199. unsigned long s, ns;
  200. struct event_format *event;
  201. unsigned n = 0;
  202. int pid;
  203. int cpu = sample->cpu;
  204. void *data = sample->raw_data;
  205. unsigned long long nsecs = sample->time;
  206. struct thread *thread = al->thread;
  207. char *comm = thread->comm;
  208. t = PyTuple_New(MAX_FIELDS);
  209. if (!t)
  210. Py_FatalError("couldn't create Python tuple");
  211. event = find_cache_event(evsel);
  212. if (!event)
  213. die("ug! no event found for type %d", (int)evsel->attr.config);
  214. pid = raw_field_value(event, "common_pid", data);
  215. sprintf(handler_name, "%s__%s", event->system, event->name);
  216. handler = PyDict_GetItemString(main_dict, handler_name);
  217. if (handler && !PyCallable_Check(handler))
  218. handler = NULL;
  219. if (!handler) {
  220. dict = PyDict_New();
  221. if (!dict)
  222. Py_FatalError("couldn't create Python dict");
  223. }
  224. s = nsecs / NSECS_PER_SEC;
  225. ns = nsecs - s * NSECS_PER_SEC;
  226. scripting_context->event_data = data;
  227. context = PyCObject_FromVoidPtr(scripting_context, NULL);
  228. PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
  229. PyTuple_SetItem(t, n++, context);
  230. if (handler) {
  231. PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
  232. PyTuple_SetItem(t, n++, PyInt_FromLong(s));
  233. PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
  234. PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
  235. PyTuple_SetItem(t, n++, PyString_FromString(comm));
  236. } else {
  237. PyDict_SetItemString(dict, "common_cpu", PyInt_FromLong(cpu));
  238. PyDict_SetItemString(dict, "common_s", PyInt_FromLong(s));
  239. PyDict_SetItemString(dict, "common_ns", PyInt_FromLong(ns));
  240. PyDict_SetItemString(dict, "common_pid", PyInt_FromLong(pid));
  241. PyDict_SetItemString(dict, "common_comm", PyString_FromString(comm));
  242. }
  243. for (field = event->format.fields; field; field = field->next) {
  244. if (field->flags & FIELD_IS_STRING) {
  245. int offset;
  246. if (field->flags & FIELD_IS_DYNAMIC) {
  247. offset = *(int *)(data + field->offset);
  248. offset &= 0xffff;
  249. } else
  250. offset = field->offset;
  251. obj = PyString_FromString((char *)data + offset);
  252. } else { /* FIELD_IS_NUMERIC */
  253. val = read_size(event, data + field->offset,
  254. field->size);
  255. if (field->flags & FIELD_IS_SIGNED) {
  256. if ((long long)val >= LONG_MIN &&
  257. (long long)val <= LONG_MAX)
  258. obj = PyInt_FromLong(val);
  259. else
  260. obj = PyLong_FromLongLong(val);
  261. } else {
  262. if (val <= LONG_MAX)
  263. obj = PyInt_FromLong(val);
  264. else
  265. obj = PyLong_FromUnsignedLongLong(val);
  266. }
  267. }
  268. if (handler)
  269. PyTuple_SetItem(t, n++, obj);
  270. else
  271. PyDict_SetItemString(dict, field->name, obj);
  272. }
  273. if (!handler)
  274. PyTuple_SetItem(t, n++, dict);
  275. if (_PyTuple_Resize(&t, n) == -1)
  276. Py_FatalError("error resizing Python tuple");
  277. if (handler) {
  278. retval = PyObject_CallObject(handler, t);
  279. if (retval == NULL)
  280. handler_call_die(handler_name);
  281. } else {
  282. handler = PyDict_GetItemString(main_dict, "trace_unhandled");
  283. if (handler && PyCallable_Check(handler)) {
  284. retval = PyObject_CallObject(handler, t);
  285. if (retval == NULL)
  286. handler_call_die("trace_unhandled");
  287. }
  288. Py_DECREF(dict);
  289. }
  290. Py_DECREF(t);
  291. }
  292. static void python_process_general_event(union perf_event *perf_event __unused,
  293. struct perf_sample *sample,
  294. struct perf_evsel *evsel,
  295. struct machine *machine __unused,
  296. struct addr_location *al __unused)
  297. {
  298. PyObject *handler, *retval, *t;
  299. static char handler_name[64];
  300. unsigned n = 0;
  301. void *data = sample->raw_data;
  302. t = PyTuple_New(MAX_FIELDS);
  303. if (!t)
  304. Py_FatalError("couldn't create Python tuple");
  305. snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
  306. handler = PyDict_GetItemString(main_dict, handler_name);
  307. if (handler && !PyCallable_Check(handler)) {
  308. handler = NULL;
  309. goto exit;
  310. }
  311. /* Pass 4 parameters: event_attr, perf_sample, raw data, thread name */
  312. PyTuple_SetItem(t, n++, PyString_FromStringAndSize((void *)&evsel->attr, sizeof(evsel->attr)));
  313. PyTuple_SetItem(t, n++, PyString_FromStringAndSize((void *)sample, sizeof(*sample)));
  314. PyTuple_SetItem(t, n++, PyString_FromStringAndSize(data, sample->raw_size));
  315. if (_PyTuple_Resize(&t, n) == -1)
  316. Py_FatalError("error resizing Python tuple");
  317. retval = PyObject_CallObject(handler, t);
  318. if (retval == NULL)
  319. handler_call_die(handler_name);
  320. exit:
  321. Py_DECREF(t);
  322. }
  323. static void python_process_event(union perf_event *perf_event,
  324. struct perf_sample *sample,
  325. struct perf_evsel *evsel,
  326. struct machine *machine,
  327. struct addr_location *al)
  328. {
  329. switch (evsel->attr.type) {
  330. case PERF_TYPE_TRACEPOINT:
  331. python_process_tracepoint(perf_event, sample, evsel,
  332. machine, al);
  333. break;
  334. /* Reserve for future process_hw/sw/raw APIs */
  335. default:
  336. python_process_general_event(perf_event, sample, evsel,
  337. machine, al);
  338. }
  339. }
  340. static int run_start_sub(void)
  341. {
  342. PyObject *handler, *retval;
  343. int err = 0;
  344. main_module = PyImport_AddModule("__main__");
  345. if (main_module == NULL)
  346. return -1;
  347. Py_INCREF(main_module);
  348. main_dict = PyModule_GetDict(main_module);
  349. if (main_dict == NULL) {
  350. err = -1;
  351. goto error;
  352. }
  353. Py_INCREF(main_dict);
  354. handler = PyDict_GetItemString(main_dict, "trace_begin");
  355. if (handler == NULL || !PyCallable_Check(handler))
  356. goto out;
  357. retval = PyObject_CallObject(handler, NULL);
  358. if (retval == NULL)
  359. handler_call_die("trace_begin");
  360. Py_DECREF(retval);
  361. return err;
  362. error:
  363. Py_XDECREF(main_dict);
  364. Py_XDECREF(main_module);
  365. out:
  366. return err;
  367. }
  368. /*
  369. * Start trace script
  370. */
  371. static int python_start_script(const char *script, int argc, const char **argv)
  372. {
  373. const char **command_line;
  374. char buf[PATH_MAX];
  375. int i, err = 0;
  376. FILE *fp;
  377. command_line = malloc((argc + 1) * sizeof(const char *));
  378. command_line[0] = script;
  379. for (i = 1; i < argc + 1; i++)
  380. command_line[i] = argv[i - 1];
  381. Py_Initialize();
  382. initperf_trace_context();
  383. PySys_SetArgv(argc + 1, (char **)command_line);
  384. fp = fopen(script, "r");
  385. if (!fp) {
  386. sprintf(buf, "Can't open python script \"%s\"", script);
  387. perror(buf);
  388. err = -1;
  389. goto error;
  390. }
  391. err = PyRun_SimpleFile(fp, script);
  392. if (err) {
  393. fprintf(stderr, "Error running python script %s\n", script);
  394. goto error;
  395. }
  396. err = run_start_sub();
  397. if (err) {
  398. fprintf(stderr, "Error starting python script %s\n", script);
  399. goto error;
  400. }
  401. free(command_line);
  402. return err;
  403. error:
  404. Py_Finalize();
  405. free(command_line);
  406. return err;
  407. }
  408. /*
  409. * Stop trace script
  410. */
  411. static int python_stop_script(void)
  412. {
  413. PyObject *handler, *retval;
  414. int err = 0;
  415. handler = PyDict_GetItemString(main_dict, "trace_end");
  416. if (handler == NULL || !PyCallable_Check(handler))
  417. goto out;
  418. retval = PyObject_CallObject(handler, NULL);
  419. if (retval == NULL)
  420. handler_call_die("trace_end");
  421. else
  422. Py_DECREF(retval);
  423. out:
  424. Py_XDECREF(main_dict);
  425. Py_XDECREF(main_module);
  426. Py_Finalize();
  427. return err;
  428. }
  429. static int python_generate_script(struct pevent *pevent, const char *outfile)
  430. {
  431. struct event_format *event = NULL;
  432. struct format_field *f;
  433. char fname[PATH_MAX];
  434. int not_first, count;
  435. FILE *ofp;
  436. sprintf(fname, "%s.py", outfile);
  437. ofp = fopen(fname, "w");
  438. if (ofp == NULL) {
  439. fprintf(stderr, "couldn't open %s\n", fname);
  440. return -1;
  441. }
  442. fprintf(ofp, "# perf script event handlers, "
  443. "generated by perf script -g python\n");
  444. fprintf(ofp, "# Licensed under the terms of the GNU GPL"
  445. " License version 2\n\n");
  446. fprintf(ofp, "# The common_* event handler fields are the most useful "
  447. "fields common to\n");
  448. fprintf(ofp, "# all events. They don't necessarily correspond to "
  449. "the 'common_*' fields\n");
  450. fprintf(ofp, "# in the format files. Those fields not available as "
  451. "handler params can\n");
  452. fprintf(ofp, "# be retrieved using Python functions of the form "
  453. "common_*(context).\n");
  454. fprintf(ofp, "# See the perf-trace-python Documentation for the list "
  455. "of available functions.\n\n");
  456. fprintf(ofp, "import os\n");
  457. fprintf(ofp, "import sys\n\n");
  458. fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
  459. fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
  460. fprintf(ofp, "\nfrom perf_trace_context import *\n");
  461. fprintf(ofp, "from Core import *\n\n\n");
  462. fprintf(ofp, "def trace_begin():\n");
  463. fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
  464. fprintf(ofp, "def trace_end():\n");
  465. fprintf(ofp, "\tprint \"in trace_end\"\n\n");
  466. while ((event = trace_find_next_event(pevent, event))) {
  467. fprintf(ofp, "def %s__%s(", event->system, event->name);
  468. fprintf(ofp, "event_name, ");
  469. fprintf(ofp, "context, ");
  470. fprintf(ofp, "common_cpu,\n");
  471. fprintf(ofp, "\tcommon_secs, ");
  472. fprintf(ofp, "common_nsecs, ");
  473. fprintf(ofp, "common_pid, ");
  474. fprintf(ofp, "common_comm,\n\t");
  475. not_first = 0;
  476. count = 0;
  477. for (f = event->format.fields; f; f = f->next) {
  478. if (not_first++)
  479. fprintf(ofp, ", ");
  480. if (++count % 5 == 0)
  481. fprintf(ofp, "\n\t");
  482. fprintf(ofp, "%s", f->name);
  483. }
  484. fprintf(ofp, "):\n");
  485. fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
  486. "common_secs, common_nsecs,\n\t\t\t"
  487. "common_pid, common_comm)\n\n");
  488. fprintf(ofp, "\t\tprint \"");
  489. not_first = 0;
  490. count = 0;
  491. for (f = event->format.fields; f; f = f->next) {
  492. if (not_first++)
  493. fprintf(ofp, ", ");
  494. if (count && count % 3 == 0) {
  495. fprintf(ofp, "\" \\\n\t\t\"");
  496. }
  497. count++;
  498. fprintf(ofp, "%s=", f->name);
  499. if (f->flags & FIELD_IS_STRING ||
  500. f->flags & FIELD_IS_FLAG ||
  501. f->flags & FIELD_IS_SYMBOLIC)
  502. fprintf(ofp, "%%s");
  503. else if (f->flags & FIELD_IS_SIGNED)
  504. fprintf(ofp, "%%d");
  505. else
  506. fprintf(ofp, "%%u");
  507. }
  508. fprintf(ofp, "\\n\" %% \\\n\t\t(");
  509. not_first = 0;
  510. count = 0;
  511. for (f = event->format.fields; f; f = f->next) {
  512. if (not_first++)
  513. fprintf(ofp, ", ");
  514. if (++count % 5 == 0)
  515. fprintf(ofp, "\n\t\t");
  516. if (f->flags & FIELD_IS_FLAG) {
  517. if ((count - 1) % 5 != 0) {
  518. fprintf(ofp, "\n\t\t");
  519. count = 4;
  520. }
  521. fprintf(ofp, "flag_str(\"");
  522. fprintf(ofp, "%s__%s\", ", event->system,
  523. event->name);
  524. fprintf(ofp, "\"%s\", %s)", f->name,
  525. f->name);
  526. } else if (f->flags & FIELD_IS_SYMBOLIC) {
  527. if ((count - 1) % 5 != 0) {
  528. fprintf(ofp, "\n\t\t");
  529. count = 4;
  530. }
  531. fprintf(ofp, "symbol_str(\"");
  532. fprintf(ofp, "%s__%s\", ", event->system,
  533. event->name);
  534. fprintf(ofp, "\"%s\", %s)", f->name,
  535. f->name);
  536. } else
  537. fprintf(ofp, "%s", f->name);
  538. }
  539. fprintf(ofp, "),\n\n");
  540. }
  541. fprintf(ofp, "def trace_unhandled(event_name, context, "
  542. "event_fields_dict):\n");
  543. fprintf(ofp, "\t\tprint ' '.join(['%%s=%%s'%%(k,str(v))"
  544. "for k,v in sorted(event_fields_dict.items())])\n\n");
  545. fprintf(ofp, "def print_header("
  546. "event_name, cpu, secs, nsecs, pid, comm):\n"
  547. "\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
  548. "(event_name, cpu, secs, nsecs, pid, comm),\n");
  549. fclose(ofp);
  550. fprintf(stderr, "generated Python script: %s\n", fname);
  551. return 0;
  552. }
  553. struct scripting_ops python_scripting_ops = {
  554. .name = "Python",
  555. .start_script = python_start_script,
  556. .stop_script = python_stop_script,
  557. .process_event = python_process_event,
  558. .generate_script = python_generate_script,
  559. };