trace-event-python.c 15 KB

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