trace-event-python.c 15 KB

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