trace-event-python.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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_STRING:
  143. break;
  144. case PRINT_TYPE:
  145. define_event_symbols(event, ev_name, args->typecast.item);
  146. break;
  147. case PRINT_OP:
  148. if (strcmp(args->op.op, ":") == 0)
  149. zero_flag_atom = 1;
  150. define_event_symbols(event, ev_name, args->op.left);
  151. define_event_symbols(event, ev_name, args->op.right);
  152. break;
  153. default:
  154. /* gcc warns for these? */
  155. case PRINT_BSTRING:
  156. case PRINT_DYNAMIC_ARRAY:
  157. case PRINT_FUNC:
  158. /* we should warn... */
  159. return;
  160. }
  161. if (args->next)
  162. define_event_symbols(event, ev_name, args->next);
  163. }
  164. static inline struct event_format *find_cache_event(int type)
  165. {
  166. static char ev_name[256];
  167. struct event_format *event;
  168. if (events[type])
  169. return events[type];
  170. events[type] = event = trace_find_event(type);
  171. if (!event)
  172. return NULL;
  173. sprintf(ev_name, "%s__%s", event->system, event->name);
  174. define_event_symbols(event, ev_name, event->print_fmt.args);
  175. return event;
  176. }
  177. static void python_process_event(union perf_event *pevent __unused,
  178. struct perf_sample *sample,
  179. struct perf_evsel *evsel __unused,
  180. struct machine *machine __unused,
  181. struct thread *thread)
  182. {
  183. PyObject *handler, *retval, *context, *t, *obj, *dict = NULL;
  184. static char handler_name[256];
  185. struct format_field *field;
  186. unsigned long long val;
  187. unsigned long s, ns;
  188. struct event_format *event;
  189. unsigned n = 0;
  190. int type;
  191. int pid;
  192. int cpu = sample->cpu;
  193. void *data = sample->raw_data;
  194. unsigned long long nsecs = sample->time;
  195. char *comm = thread->comm;
  196. t = PyTuple_New(MAX_FIELDS);
  197. if (!t)
  198. Py_FatalError("couldn't create Python tuple");
  199. type = trace_parse_common_type(data);
  200. event = find_cache_event(type);
  201. if (!event)
  202. die("ug! no event found for type %d", type);
  203. pid = trace_parse_common_pid(data);
  204. sprintf(handler_name, "%s__%s", event->system, event->name);
  205. handler = PyDict_GetItemString(main_dict, handler_name);
  206. if (handler && !PyCallable_Check(handler))
  207. handler = NULL;
  208. if (!handler) {
  209. dict = PyDict_New();
  210. if (!dict)
  211. Py_FatalError("couldn't create Python dict");
  212. }
  213. s = nsecs / NSECS_PER_SEC;
  214. ns = nsecs - s * NSECS_PER_SEC;
  215. scripting_context->event_data = data;
  216. context = PyCObject_FromVoidPtr(scripting_context, NULL);
  217. PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
  218. PyTuple_SetItem(t, n++, context);
  219. if (handler) {
  220. PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
  221. PyTuple_SetItem(t, n++, PyInt_FromLong(s));
  222. PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
  223. PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
  224. PyTuple_SetItem(t, n++, PyString_FromString(comm));
  225. } else {
  226. PyDict_SetItemString(dict, "common_cpu", PyInt_FromLong(cpu));
  227. PyDict_SetItemString(dict, "common_s", PyInt_FromLong(s));
  228. PyDict_SetItemString(dict, "common_ns", PyInt_FromLong(ns));
  229. PyDict_SetItemString(dict, "common_pid", PyInt_FromLong(pid));
  230. PyDict_SetItemString(dict, "common_comm", PyString_FromString(comm));
  231. }
  232. for (field = event->format.fields; field; field = field->next) {
  233. if (field->flags & FIELD_IS_STRING) {
  234. int offset;
  235. if (field->flags & FIELD_IS_DYNAMIC) {
  236. offset = *(int *)(data + field->offset);
  237. offset &= 0xffff;
  238. } else
  239. offset = field->offset;
  240. obj = PyString_FromString((char *)data + offset);
  241. } else { /* FIELD_IS_NUMERIC */
  242. val = read_size(data + field->offset, field->size);
  243. if (field->flags & FIELD_IS_SIGNED) {
  244. if ((long long)val >= LONG_MIN &&
  245. (long long)val <= LONG_MAX)
  246. obj = PyInt_FromLong(val);
  247. else
  248. obj = PyLong_FromLongLong(val);
  249. } else {
  250. if (val <= LONG_MAX)
  251. obj = PyInt_FromLong(val);
  252. else
  253. obj = PyLong_FromUnsignedLongLong(val);
  254. }
  255. }
  256. if (handler)
  257. PyTuple_SetItem(t, n++, obj);
  258. else
  259. PyDict_SetItemString(dict, field->name, obj);
  260. }
  261. if (!handler)
  262. PyTuple_SetItem(t, n++, dict);
  263. if (_PyTuple_Resize(&t, n) == -1)
  264. Py_FatalError("error resizing Python tuple");
  265. if (handler) {
  266. retval = PyObject_CallObject(handler, t);
  267. if (retval == NULL)
  268. handler_call_die(handler_name);
  269. } else {
  270. handler = PyDict_GetItemString(main_dict, "trace_unhandled");
  271. if (handler && PyCallable_Check(handler)) {
  272. retval = PyObject_CallObject(handler, t);
  273. if (retval == NULL)
  274. handler_call_die("trace_unhandled");
  275. }
  276. Py_DECREF(dict);
  277. }
  278. Py_DECREF(t);
  279. }
  280. static int run_start_sub(void)
  281. {
  282. PyObject *handler, *retval;
  283. int err = 0;
  284. main_module = PyImport_AddModule("__main__");
  285. if (main_module == NULL)
  286. return -1;
  287. Py_INCREF(main_module);
  288. main_dict = PyModule_GetDict(main_module);
  289. if (main_dict == NULL) {
  290. err = -1;
  291. goto error;
  292. }
  293. Py_INCREF(main_dict);
  294. handler = PyDict_GetItemString(main_dict, "trace_begin");
  295. if (handler == NULL || !PyCallable_Check(handler))
  296. goto out;
  297. retval = PyObject_CallObject(handler, NULL);
  298. if (retval == NULL)
  299. handler_call_die("trace_begin");
  300. Py_DECREF(retval);
  301. return err;
  302. error:
  303. Py_XDECREF(main_dict);
  304. Py_XDECREF(main_module);
  305. out:
  306. return err;
  307. }
  308. /*
  309. * Start trace script
  310. */
  311. static int python_start_script(const char *script, int argc, const char **argv)
  312. {
  313. const char **command_line;
  314. char buf[PATH_MAX];
  315. int i, err = 0;
  316. FILE *fp;
  317. command_line = malloc((argc + 1) * sizeof(const char *));
  318. command_line[0] = script;
  319. for (i = 1; i < argc + 1; i++)
  320. command_line[i] = argv[i - 1];
  321. Py_Initialize();
  322. initperf_trace_context();
  323. PySys_SetArgv(argc + 1, (char **)command_line);
  324. fp = fopen(script, "r");
  325. if (!fp) {
  326. sprintf(buf, "Can't open python script \"%s\"", script);
  327. perror(buf);
  328. err = -1;
  329. goto error;
  330. }
  331. err = PyRun_SimpleFile(fp, script);
  332. if (err) {
  333. fprintf(stderr, "Error running python script %s\n", script);
  334. goto error;
  335. }
  336. err = run_start_sub();
  337. if (err) {
  338. fprintf(stderr, "Error starting python script %s\n", script);
  339. goto error;
  340. }
  341. free(command_line);
  342. return err;
  343. error:
  344. Py_Finalize();
  345. free(command_line);
  346. return err;
  347. }
  348. /*
  349. * Stop trace script
  350. */
  351. static int python_stop_script(void)
  352. {
  353. PyObject *handler, *retval;
  354. int err = 0;
  355. handler = PyDict_GetItemString(main_dict, "trace_end");
  356. if (handler == NULL || !PyCallable_Check(handler))
  357. goto out;
  358. retval = PyObject_CallObject(handler, NULL);
  359. if (retval == NULL)
  360. handler_call_die("trace_end");
  361. else
  362. Py_DECREF(retval);
  363. out:
  364. Py_XDECREF(main_dict);
  365. Py_XDECREF(main_module);
  366. Py_Finalize();
  367. return err;
  368. }
  369. static int python_generate_script(const char *outfile)
  370. {
  371. struct event_format *event = NULL;
  372. struct format_field *f;
  373. char fname[PATH_MAX];
  374. int not_first, count;
  375. FILE *ofp;
  376. sprintf(fname, "%s.py", outfile);
  377. ofp = fopen(fname, "w");
  378. if (ofp == NULL) {
  379. fprintf(stderr, "couldn't open %s\n", fname);
  380. return -1;
  381. }
  382. fprintf(ofp, "# perf script event handlers, "
  383. "generated by perf script -g python\n");
  384. fprintf(ofp, "# Licensed under the terms of the GNU GPL"
  385. " License version 2\n\n");
  386. fprintf(ofp, "# The common_* event handler fields are the most useful "
  387. "fields common to\n");
  388. fprintf(ofp, "# all events. They don't necessarily correspond to "
  389. "the 'common_*' fields\n");
  390. fprintf(ofp, "# in the format files. Those fields not available as "
  391. "handler params can\n");
  392. fprintf(ofp, "# be retrieved using Python functions of the form "
  393. "common_*(context).\n");
  394. fprintf(ofp, "# See the perf-trace-python Documentation for the list "
  395. "of available functions.\n\n");
  396. fprintf(ofp, "import os\n");
  397. fprintf(ofp, "import sys\n\n");
  398. fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
  399. fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
  400. fprintf(ofp, "\nfrom perf_trace_context import *\n");
  401. fprintf(ofp, "from Core import *\n\n\n");
  402. fprintf(ofp, "def trace_begin():\n");
  403. fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
  404. fprintf(ofp, "def trace_end():\n");
  405. fprintf(ofp, "\tprint \"in trace_end\"\n\n");
  406. while ((event = trace_find_next_event(event))) {
  407. fprintf(ofp, "def %s__%s(", event->system, event->name);
  408. fprintf(ofp, "event_name, ");
  409. fprintf(ofp, "context, ");
  410. fprintf(ofp, "common_cpu,\n");
  411. fprintf(ofp, "\tcommon_secs, ");
  412. fprintf(ofp, "common_nsecs, ");
  413. fprintf(ofp, "common_pid, ");
  414. fprintf(ofp, "common_comm,\n\t");
  415. not_first = 0;
  416. count = 0;
  417. for (f = event->format.fields; f; f = f->next) {
  418. if (not_first++)
  419. fprintf(ofp, ", ");
  420. if (++count % 5 == 0)
  421. fprintf(ofp, "\n\t");
  422. fprintf(ofp, "%s", f->name);
  423. }
  424. fprintf(ofp, "):\n");
  425. fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
  426. "common_secs, common_nsecs,\n\t\t\t"
  427. "common_pid, common_comm)\n\n");
  428. fprintf(ofp, "\t\tprint \"");
  429. not_first = 0;
  430. count = 0;
  431. for (f = event->format.fields; f; f = f->next) {
  432. if (not_first++)
  433. fprintf(ofp, ", ");
  434. if (count && count % 3 == 0) {
  435. fprintf(ofp, "\" \\\n\t\t\"");
  436. }
  437. count++;
  438. fprintf(ofp, "%s=", f->name);
  439. if (f->flags & FIELD_IS_STRING ||
  440. f->flags & FIELD_IS_FLAG ||
  441. f->flags & FIELD_IS_SYMBOLIC)
  442. fprintf(ofp, "%%s");
  443. else if (f->flags & FIELD_IS_SIGNED)
  444. fprintf(ofp, "%%d");
  445. else
  446. fprintf(ofp, "%%u");
  447. }
  448. fprintf(ofp, "\\n\" %% \\\n\t\t(");
  449. not_first = 0;
  450. count = 0;
  451. for (f = event->format.fields; f; f = f->next) {
  452. if (not_first++)
  453. fprintf(ofp, ", ");
  454. if (++count % 5 == 0)
  455. fprintf(ofp, "\n\t\t");
  456. if (f->flags & FIELD_IS_FLAG) {
  457. if ((count - 1) % 5 != 0) {
  458. fprintf(ofp, "\n\t\t");
  459. count = 4;
  460. }
  461. fprintf(ofp, "flag_str(\"");
  462. fprintf(ofp, "%s__%s\", ", event->system,
  463. event->name);
  464. fprintf(ofp, "\"%s\", %s)", f->name,
  465. f->name);
  466. } else if (f->flags & FIELD_IS_SYMBOLIC) {
  467. if ((count - 1) % 5 != 0) {
  468. fprintf(ofp, "\n\t\t");
  469. count = 4;
  470. }
  471. fprintf(ofp, "symbol_str(\"");
  472. fprintf(ofp, "%s__%s\", ", event->system,
  473. event->name);
  474. fprintf(ofp, "\"%s\", %s)", f->name,
  475. f->name);
  476. } else
  477. fprintf(ofp, "%s", f->name);
  478. }
  479. fprintf(ofp, "),\n\n");
  480. }
  481. fprintf(ofp, "def trace_unhandled(event_name, context, "
  482. "event_fields_dict):\n");
  483. fprintf(ofp, "\t\tprint ' '.join(['%%s=%%s'%%(k,str(v))"
  484. "for k,v in sorted(event_fields_dict.items())])\n\n");
  485. fprintf(ofp, "def print_header("
  486. "event_name, cpu, secs, nsecs, pid, comm):\n"
  487. "\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
  488. "(event_name, cpu, secs, nsecs, pid, comm),\n");
  489. fclose(ofp);
  490. fprintf(stderr, "generated Python script: %s\n", fname);
  491. return 0;
  492. }
  493. struct scripting_ops python_scripting_ops = {
  494. .name = "Python",
  495. .start_script = python_start_script,
  496. .stop_script = python_stop_script,
  497. .process_event = python_process_event,
  498. .generate_script = python_generate_script,
  499. };