trace-event-python.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  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 <stdbool.h>
  26. #include <errno.h>
  27. #include "../../perf.h"
  28. #include "../debug.h"
  29. #include "../callchain.h"
  30. #include "../evsel.h"
  31. #include "../util.h"
  32. #include "../event.h"
  33. #include "../thread.h"
  34. #include "../comm.h"
  35. #include "../machine.h"
  36. #include "../db-export.h"
  37. #include "../trace-event.h"
  38. #include "../machine.h"
  39. PyMODINIT_FUNC initperf_trace_context(void);
  40. #define FTRACE_MAX_EVENT \
  41. ((1 << (sizeof(unsigned short) * 8)) - 1)
  42. struct event_format *events[FTRACE_MAX_EVENT];
  43. #define MAX_FIELDS 64
  44. #define N_COMMON_FIELDS 7
  45. extern struct scripting_context *scripting_context;
  46. static char *cur_field_name;
  47. static int zero_flag_atom;
  48. static PyObject *main_module, *main_dict;
  49. struct tables {
  50. struct db_export dbe;
  51. PyObject *evsel_handler;
  52. PyObject *machine_handler;
  53. PyObject *thread_handler;
  54. PyObject *comm_handler;
  55. PyObject *comm_thread_handler;
  56. PyObject *dso_handler;
  57. PyObject *symbol_handler;
  58. PyObject *sample_handler;
  59. bool db_export_mode;
  60. };
  61. static struct tables tables_global;
  62. static void handler_call_die(const char *handler_name) NORETURN;
  63. static void handler_call_die(const char *handler_name)
  64. {
  65. PyErr_Print();
  66. Py_FatalError("problem in Python trace event handler");
  67. // Py_FatalError does not return
  68. // but we have to make the compiler happy
  69. abort();
  70. }
  71. /*
  72. * Insert val into into the dictionary and decrement the reference counter.
  73. * This is necessary for dictionaries since PyDict_SetItemString() does not
  74. * steal a reference, as opposed to PyTuple_SetItem().
  75. */
  76. static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
  77. {
  78. PyDict_SetItemString(dict, key, val);
  79. Py_DECREF(val);
  80. }
  81. static PyObject *get_handler(const char *handler_name)
  82. {
  83. PyObject *handler;
  84. handler = PyDict_GetItemString(main_dict, handler_name);
  85. if (handler && !PyCallable_Check(handler))
  86. return NULL;
  87. return handler;
  88. }
  89. static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
  90. {
  91. PyObject *retval;
  92. retval = PyObject_CallObject(handler, args);
  93. if (retval == NULL)
  94. handler_call_die(die_msg);
  95. Py_DECREF(retval);
  96. }
  97. static void try_call_object(const char *handler_name, PyObject *args)
  98. {
  99. PyObject *handler;
  100. handler = get_handler(handler_name);
  101. if (handler)
  102. call_object(handler, args, handler_name);
  103. }
  104. static void define_value(enum print_arg_type field_type,
  105. const char *ev_name,
  106. const char *field_name,
  107. const char *field_value,
  108. const char *field_str)
  109. {
  110. const char *handler_name = "define_flag_value";
  111. PyObject *t;
  112. unsigned long long value;
  113. unsigned n = 0;
  114. if (field_type == PRINT_SYMBOL)
  115. handler_name = "define_symbolic_value";
  116. t = PyTuple_New(4);
  117. if (!t)
  118. Py_FatalError("couldn't create Python tuple");
  119. value = eval_flag(field_value);
  120. PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
  121. PyTuple_SetItem(t, n++, PyString_FromString(field_name));
  122. PyTuple_SetItem(t, n++, PyInt_FromLong(value));
  123. PyTuple_SetItem(t, n++, PyString_FromString(field_str));
  124. try_call_object(handler_name, t);
  125. Py_DECREF(t);
  126. }
  127. static void define_values(enum print_arg_type field_type,
  128. struct print_flag_sym *field,
  129. const char *ev_name,
  130. const char *field_name)
  131. {
  132. define_value(field_type, ev_name, field_name, field->value,
  133. field->str);
  134. if (field->next)
  135. define_values(field_type, field->next, ev_name, field_name);
  136. }
  137. static void define_field(enum print_arg_type field_type,
  138. const char *ev_name,
  139. const char *field_name,
  140. const char *delim)
  141. {
  142. const char *handler_name = "define_flag_field";
  143. PyObject *t;
  144. unsigned n = 0;
  145. if (field_type == PRINT_SYMBOL)
  146. handler_name = "define_symbolic_field";
  147. if (field_type == PRINT_FLAGS)
  148. t = PyTuple_New(3);
  149. else
  150. t = PyTuple_New(2);
  151. if (!t)
  152. Py_FatalError("couldn't create Python tuple");
  153. PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
  154. PyTuple_SetItem(t, n++, PyString_FromString(field_name));
  155. if (field_type == PRINT_FLAGS)
  156. PyTuple_SetItem(t, n++, PyString_FromString(delim));
  157. try_call_object(handler_name, t);
  158. Py_DECREF(t);
  159. }
  160. static void define_event_symbols(struct event_format *event,
  161. const char *ev_name,
  162. struct print_arg *args)
  163. {
  164. switch (args->type) {
  165. case PRINT_NULL:
  166. break;
  167. case PRINT_ATOM:
  168. define_value(PRINT_FLAGS, ev_name, cur_field_name, "0",
  169. args->atom.atom);
  170. zero_flag_atom = 0;
  171. break;
  172. case PRINT_FIELD:
  173. free(cur_field_name);
  174. cur_field_name = strdup(args->field.name);
  175. break;
  176. case PRINT_FLAGS:
  177. define_event_symbols(event, ev_name, args->flags.field);
  178. define_field(PRINT_FLAGS, ev_name, cur_field_name,
  179. args->flags.delim);
  180. define_values(PRINT_FLAGS, args->flags.flags, ev_name,
  181. cur_field_name);
  182. break;
  183. case PRINT_SYMBOL:
  184. define_event_symbols(event, ev_name, args->symbol.field);
  185. define_field(PRINT_SYMBOL, ev_name, cur_field_name, NULL);
  186. define_values(PRINT_SYMBOL, args->symbol.symbols, ev_name,
  187. cur_field_name);
  188. break;
  189. case PRINT_HEX:
  190. define_event_symbols(event, ev_name, args->hex.field);
  191. define_event_symbols(event, ev_name, args->hex.size);
  192. break;
  193. case PRINT_STRING:
  194. break;
  195. case PRINT_TYPE:
  196. define_event_symbols(event, ev_name, args->typecast.item);
  197. break;
  198. case PRINT_OP:
  199. if (strcmp(args->op.op, ":") == 0)
  200. zero_flag_atom = 1;
  201. define_event_symbols(event, ev_name, args->op.left);
  202. define_event_symbols(event, ev_name, args->op.right);
  203. break;
  204. default:
  205. /* gcc warns for these? */
  206. case PRINT_BSTRING:
  207. case PRINT_DYNAMIC_ARRAY:
  208. case PRINT_FUNC:
  209. case PRINT_BITMASK:
  210. /* we should warn... */
  211. return;
  212. }
  213. if (args->next)
  214. define_event_symbols(event, ev_name, args->next);
  215. }
  216. static inline struct event_format *find_cache_event(struct perf_evsel *evsel)
  217. {
  218. static char ev_name[256];
  219. struct event_format *event;
  220. int type = evsel->attr.config;
  221. /*
  222. * XXX: Do we really need to cache this since now we have evsel->tp_format
  223. * cached already? Need to re-read this "cache" routine that as well calls
  224. * define_event_symbols() :-\
  225. */
  226. if (events[type])
  227. return events[type];
  228. events[type] = event = evsel->tp_format;
  229. if (!event)
  230. return NULL;
  231. sprintf(ev_name, "%s__%s", event->system, event->name);
  232. define_event_symbols(event, ev_name, event->print_fmt.args);
  233. return event;
  234. }
  235. static PyObject *get_field_numeric_entry(struct event_format *event,
  236. struct format_field *field, void *data)
  237. {
  238. bool is_array = field->flags & FIELD_IS_ARRAY;
  239. PyObject *obj, *list = NULL;
  240. unsigned long long val;
  241. unsigned int item_size, n_items, i;
  242. if (is_array) {
  243. list = PyList_New(field->arraylen);
  244. item_size = field->size / field->arraylen;
  245. n_items = field->arraylen;
  246. } else {
  247. item_size = field->size;
  248. n_items = 1;
  249. }
  250. for (i = 0; i < n_items; i++) {
  251. val = read_size(event, data + field->offset + i * item_size,
  252. item_size);
  253. if (field->flags & FIELD_IS_SIGNED) {
  254. if ((long long)val >= LONG_MIN &&
  255. (long long)val <= LONG_MAX)
  256. obj = PyInt_FromLong(val);
  257. else
  258. obj = PyLong_FromLongLong(val);
  259. } else {
  260. if (val <= LONG_MAX)
  261. obj = PyInt_FromLong(val);
  262. else
  263. obj = PyLong_FromUnsignedLongLong(val);
  264. }
  265. if (is_array)
  266. PyList_SET_ITEM(list, i, obj);
  267. }
  268. if (is_array)
  269. obj = list;
  270. return obj;
  271. }
  272. static PyObject *python_process_callchain(struct perf_sample *sample,
  273. struct perf_evsel *evsel,
  274. struct addr_location *al)
  275. {
  276. PyObject *pylist;
  277. pylist = PyList_New(0);
  278. if (!pylist)
  279. Py_FatalError("couldn't create Python list");
  280. if (!symbol_conf.use_callchain || !sample->callchain)
  281. goto exit;
  282. if (thread__resolve_callchain(al->thread, evsel,
  283. sample, NULL, NULL,
  284. PERF_MAX_STACK_DEPTH) != 0) {
  285. pr_err("Failed to resolve callchain. Skipping\n");
  286. goto exit;
  287. }
  288. callchain_cursor_commit(&callchain_cursor);
  289. while (1) {
  290. PyObject *pyelem;
  291. struct callchain_cursor_node *node;
  292. node = callchain_cursor_current(&callchain_cursor);
  293. if (!node)
  294. break;
  295. pyelem = PyDict_New();
  296. if (!pyelem)
  297. Py_FatalError("couldn't create Python dictionary");
  298. pydict_set_item_string_decref(pyelem, "ip",
  299. PyLong_FromUnsignedLongLong(node->ip));
  300. if (node->sym) {
  301. PyObject *pysym = PyDict_New();
  302. if (!pysym)
  303. Py_FatalError("couldn't create Python dictionary");
  304. pydict_set_item_string_decref(pysym, "start",
  305. PyLong_FromUnsignedLongLong(node->sym->start));
  306. pydict_set_item_string_decref(pysym, "end",
  307. PyLong_FromUnsignedLongLong(node->sym->end));
  308. pydict_set_item_string_decref(pysym, "binding",
  309. PyInt_FromLong(node->sym->binding));
  310. pydict_set_item_string_decref(pysym, "name",
  311. PyString_FromStringAndSize(node->sym->name,
  312. node->sym->namelen));
  313. pydict_set_item_string_decref(pyelem, "sym", pysym);
  314. }
  315. if (node->map) {
  316. struct map *map = node->map;
  317. const char *dsoname = "[unknown]";
  318. if (map && map->dso && (map->dso->name || map->dso->long_name)) {
  319. if (symbol_conf.show_kernel_path && map->dso->long_name)
  320. dsoname = map->dso->long_name;
  321. else if (map->dso->name)
  322. dsoname = map->dso->name;
  323. }
  324. pydict_set_item_string_decref(pyelem, "dso",
  325. PyString_FromString(dsoname));
  326. }
  327. callchain_cursor_advance(&callchain_cursor);
  328. PyList_Append(pylist, pyelem);
  329. Py_DECREF(pyelem);
  330. }
  331. exit:
  332. return pylist;
  333. }
  334. static void python_process_tracepoint(struct perf_sample *sample,
  335. struct perf_evsel *evsel,
  336. struct thread *thread,
  337. struct addr_location *al)
  338. {
  339. PyObject *handler, *context, *t, *obj, *callchain;
  340. PyObject *dict = NULL;
  341. static char handler_name[256];
  342. struct format_field *field;
  343. unsigned long s, ns;
  344. struct event_format *event;
  345. unsigned n = 0;
  346. int pid;
  347. int cpu = sample->cpu;
  348. void *data = sample->raw_data;
  349. unsigned long long nsecs = sample->time;
  350. const char *comm = thread__comm_str(thread);
  351. t = PyTuple_New(MAX_FIELDS);
  352. if (!t)
  353. Py_FatalError("couldn't create Python tuple");
  354. event = find_cache_event(evsel);
  355. if (!event)
  356. die("ug! no event found for type %d", (int)evsel->attr.config);
  357. pid = raw_field_value(event, "common_pid", data);
  358. sprintf(handler_name, "%s__%s", event->system, event->name);
  359. handler = get_handler(handler_name);
  360. if (!handler) {
  361. dict = PyDict_New();
  362. if (!dict)
  363. Py_FatalError("couldn't create Python dict");
  364. }
  365. s = nsecs / NSECS_PER_SEC;
  366. ns = nsecs - s * NSECS_PER_SEC;
  367. scripting_context->event_data = data;
  368. scripting_context->pevent = evsel->tp_format->pevent;
  369. context = PyCObject_FromVoidPtr(scripting_context, NULL);
  370. PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
  371. PyTuple_SetItem(t, n++, context);
  372. /* ip unwinding */
  373. callchain = python_process_callchain(sample, evsel, al);
  374. if (handler) {
  375. PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
  376. PyTuple_SetItem(t, n++, PyInt_FromLong(s));
  377. PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
  378. PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
  379. PyTuple_SetItem(t, n++, PyString_FromString(comm));
  380. PyTuple_SetItem(t, n++, callchain);
  381. } else {
  382. pydict_set_item_string_decref(dict, "common_cpu", PyInt_FromLong(cpu));
  383. pydict_set_item_string_decref(dict, "common_s", PyInt_FromLong(s));
  384. pydict_set_item_string_decref(dict, "common_ns", PyInt_FromLong(ns));
  385. pydict_set_item_string_decref(dict, "common_pid", PyInt_FromLong(pid));
  386. pydict_set_item_string_decref(dict, "common_comm", PyString_FromString(comm));
  387. pydict_set_item_string_decref(dict, "common_callchain", callchain);
  388. }
  389. for (field = event->format.fields; field; field = field->next) {
  390. if (field->flags & FIELD_IS_STRING) {
  391. int offset;
  392. if (field->flags & FIELD_IS_DYNAMIC) {
  393. offset = *(int *)(data + field->offset);
  394. offset &= 0xffff;
  395. } else
  396. offset = field->offset;
  397. obj = PyString_FromString((char *)data + offset);
  398. } else { /* FIELD_IS_NUMERIC */
  399. obj = get_field_numeric_entry(event, field, data);
  400. }
  401. if (handler)
  402. PyTuple_SetItem(t, n++, obj);
  403. else
  404. pydict_set_item_string_decref(dict, field->name, obj);
  405. }
  406. if (!handler)
  407. PyTuple_SetItem(t, n++, dict);
  408. if (_PyTuple_Resize(&t, n) == -1)
  409. Py_FatalError("error resizing Python tuple");
  410. if (handler) {
  411. call_object(handler, t, handler_name);
  412. } else {
  413. try_call_object("trace_unhandled", t);
  414. Py_DECREF(dict);
  415. }
  416. Py_DECREF(t);
  417. }
  418. static PyObject *tuple_new(unsigned int sz)
  419. {
  420. PyObject *t;
  421. t = PyTuple_New(sz);
  422. if (!t)
  423. Py_FatalError("couldn't create Python tuple");
  424. return t;
  425. }
  426. static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
  427. {
  428. #if BITS_PER_LONG == 64
  429. return PyTuple_SetItem(t, pos, PyInt_FromLong(val));
  430. #endif
  431. #if BITS_PER_LONG == 32
  432. return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
  433. #endif
  434. }
  435. static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
  436. {
  437. return PyTuple_SetItem(t, pos, PyInt_FromLong(val));
  438. }
  439. static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
  440. {
  441. return PyTuple_SetItem(t, pos, PyString_FromString(s));
  442. }
  443. static int python_export_evsel(struct db_export *dbe, struct perf_evsel *evsel)
  444. {
  445. struct tables *tables = container_of(dbe, struct tables, dbe);
  446. PyObject *t;
  447. t = tuple_new(2);
  448. tuple_set_u64(t, 0, evsel->db_id);
  449. tuple_set_string(t, 1, perf_evsel__name(evsel));
  450. call_object(tables->evsel_handler, t, "evsel_table");
  451. Py_DECREF(t);
  452. return 0;
  453. }
  454. static int python_export_machine(struct db_export *dbe,
  455. struct machine *machine)
  456. {
  457. struct tables *tables = container_of(dbe, struct tables, dbe);
  458. PyObject *t;
  459. t = tuple_new(3);
  460. tuple_set_u64(t, 0, machine->db_id);
  461. tuple_set_s32(t, 1, machine->pid);
  462. tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
  463. call_object(tables->machine_handler, t, "machine_table");
  464. Py_DECREF(t);
  465. return 0;
  466. }
  467. static int python_export_thread(struct db_export *dbe, struct thread *thread,
  468. u64 main_thread_db_id, struct machine *machine)
  469. {
  470. struct tables *tables = container_of(dbe, struct tables, dbe);
  471. PyObject *t;
  472. t = tuple_new(5);
  473. tuple_set_u64(t, 0, thread->db_id);
  474. tuple_set_u64(t, 1, machine->db_id);
  475. tuple_set_u64(t, 2, main_thread_db_id);
  476. tuple_set_s32(t, 3, thread->pid_);
  477. tuple_set_s32(t, 4, thread->tid);
  478. call_object(tables->thread_handler, t, "thread_table");
  479. Py_DECREF(t);
  480. return 0;
  481. }
  482. static int python_export_comm(struct db_export *dbe, struct comm *comm)
  483. {
  484. struct tables *tables = container_of(dbe, struct tables, dbe);
  485. PyObject *t;
  486. t = tuple_new(2);
  487. tuple_set_u64(t, 0, comm->db_id);
  488. tuple_set_string(t, 1, comm__str(comm));
  489. call_object(tables->comm_handler, t, "comm_table");
  490. Py_DECREF(t);
  491. return 0;
  492. }
  493. static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
  494. struct comm *comm, struct thread *thread)
  495. {
  496. struct tables *tables = container_of(dbe, struct tables, dbe);
  497. PyObject *t;
  498. t = tuple_new(3);
  499. tuple_set_u64(t, 0, db_id);
  500. tuple_set_u64(t, 1, comm->db_id);
  501. tuple_set_u64(t, 2, thread->db_id);
  502. call_object(tables->comm_thread_handler, t, "comm_thread_table");
  503. Py_DECREF(t);
  504. return 0;
  505. }
  506. static int python_export_dso(struct db_export *dbe, struct dso *dso,
  507. struct machine *machine)
  508. {
  509. struct tables *tables = container_of(dbe, struct tables, dbe);
  510. char sbuild_id[BUILD_ID_SIZE * 2 + 1];
  511. PyObject *t;
  512. build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);
  513. t = tuple_new(5);
  514. tuple_set_u64(t, 0, dso->db_id);
  515. tuple_set_u64(t, 1, machine->db_id);
  516. tuple_set_string(t, 2, dso->short_name);
  517. tuple_set_string(t, 3, dso->long_name);
  518. tuple_set_string(t, 4, sbuild_id);
  519. call_object(tables->dso_handler, t, "dso_table");
  520. Py_DECREF(t);
  521. return 0;
  522. }
  523. static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
  524. struct dso *dso)
  525. {
  526. struct tables *tables = container_of(dbe, struct tables, dbe);
  527. u64 *sym_db_id = symbol__priv(sym);
  528. PyObject *t;
  529. t = tuple_new(6);
  530. tuple_set_u64(t, 0, *sym_db_id);
  531. tuple_set_u64(t, 1, dso->db_id);
  532. tuple_set_u64(t, 2, sym->start);
  533. tuple_set_u64(t, 3, sym->end);
  534. tuple_set_s32(t, 4, sym->binding);
  535. tuple_set_string(t, 5, sym->name);
  536. call_object(tables->symbol_handler, t, "symbol_table");
  537. Py_DECREF(t);
  538. return 0;
  539. }
  540. static int python_export_sample(struct db_export *dbe,
  541. struct export_sample *es)
  542. {
  543. struct tables *tables = container_of(dbe, struct tables, dbe);
  544. PyObject *t;
  545. t = tuple_new(19);
  546. tuple_set_u64(t, 0, es->db_id);
  547. tuple_set_u64(t, 1, es->evsel->db_id);
  548. tuple_set_u64(t, 2, es->al->machine->db_id);
  549. tuple_set_u64(t, 3, es->thread->db_id);
  550. tuple_set_u64(t, 4, es->comm_db_id);
  551. tuple_set_u64(t, 5, es->dso_db_id);
  552. tuple_set_u64(t, 6, es->sym_db_id);
  553. tuple_set_u64(t, 7, es->offset);
  554. tuple_set_u64(t, 8, es->sample->ip);
  555. tuple_set_u64(t, 9, es->sample->time);
  556. tuple_set_s32(t, 10, es->sample->cpu);
  557. tuple_set_u64(t, 11, es->addr_dso_db_id);
  558. tuple_set_u64(t, 12, es->addr_sym_db_id);
  559. tuple_set_u64(t, 13, es->addr_offset);
  560. tuple_set_u64(t, 14, es->sample->addr);
  561. tuple_set_u64(t, 15, es->sample->period);
  562. tuple_set_u64(t, 16, es->sample->weight);
  563. tuple_set_u64(t, 17, es->sample->transaction);
  564. tuple_set_u64(t, 18, es->sample->data_src);
  565. call_object(tables->sample_handler, t, "sample_table");
  566. Py_DECREF(t);
  567. return 0;
  568. }
  569. static void python_process_general_event(struct perf_sample *sample,
  570. struct perf_evsel *evsel,
  571. struct thread *thread,
  572. struct addr_location *al)
  573. {
  574. PyObject *handler, *t, *dict, *callchain, *dict_sample;
  575. static char handler_name[64];
  576. unsigned n = 0;
  577. /*
  578. * Use the MAX_FIELDS to make the function expandable, though
  579. * currently there is only one item for the tuple.
  580. */
  581. t = PyTuple_New(MAX_FIELDS);
  582. if (!t)
  583. Py_FatalError("couldn't create Python tuple");
  584. dict = PyDict_New();
  585. if (!dict)
  586. Py_FatalError("couldn't create Python dictionary");
  587. dict_sample = PyDict_New();
  588. if (!dict_sample)
  589. Py_FatalError("couldn't create Python dictionary");
  590. snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
  591. handler = get_handler(handler_name);
  592. if (!handler)
  593. goto exit;
  594. pydict_set_item_string_decref(dict, "ev_name", PyString_FromString(perf_evsel__name(evsel)));
  595. pydict_set_item_string_decref(dict, "attr", PyString_FromStringAndSize(
  596. (const char *)&evsel->attr, sizeof(evsel->attr)));
  597. pydict_set_item_string_decref(dict_sample, "pid",
  598. PyInt_FromLong(sample->pid));
  599. pydict_set_item_string_decref(dict_sample, "tid",
  600. PyInt_FromLong(sample->tid));
  601. pydict_set_item_string_decref(dict_sample, "cpu",
  602. PyInt_FromLong(sample->cpu));
  603. pydict_set_item_string_decref(dict_sample, "ip",
  604. PyLong_FromUnsignedLongLong(sample->ip));
  605. pydict_set_item_string_decref(dict_sample, "time",
  606. PyLong_FromUnsignedLongLong(sample->time));
  607. pydict_set_item_string_decref(dict_sample, "period",
  608. PyLong_FromUnsignedLongLong(sample->period));
  609. pydict_set_item_string_decref(dict, "sample", dict_sample);
  610. pydict_set_item_string_decref(dict, "raw_buf", PyString_FromStringAndSize(
  611. (const char *)sample->raw_data, sample->raw_size));
  612. pydict_set_item_string_decref(dict, "comm",
  613. PyString_FromString(thread__comm_str(thread)));
  614. if (al->map) {
  615. pydict_set_item_string_decref(dict, "dso",
  616. PyString_FromString(al->map->dso->name));
  617. }
  618. if (al->sym) {
  619. pydict_set_item_string_decref(dict, "symbol",
  620. PyString_FromString(al->sym->name));
  621. }
  622. /* ip unwinding */
  623. callchain = python_process_callchain(sample, evsel, al);
  624. pydict_set_item_string_decref(dict, "callchain", callchain);
  625. PyTuple_SetItem(t, n++, dict);
  626. if (_PyTuple_Resize(&t, n) == -1)
  627. Py_FatalError("error resizing Python tuple");
  628. call_object(handler, t, handler_name);
  629. exit:
  630. Py_DECREF(dict);
  631. Py_DECREF(t);
  632. }
  633. static void python_process_event(union perf_event *event,
  634. struct perf_sample *sample,
  635. struct perf_evsel *evsel,
  636. struct thread *thread,
  637. struct addr_location *al)
  638. {
  639. struct tables *tables = &tables_global;
  640. switch (evsel->attr.type) {
  641. case PERF_TYPE_TRACEPOINT:
  642. python_process_tracepoint(sample, evsel, thread, al);
  643. break;
  644. /* Reserve for future process_hw/sw/raw APIs */
  645. default:
  646. if (tables->db_export_mode)
  647. db_export__sample(&tables->dbe, event, sample, evsel,
  648. thread, al);
  649. else
  650. python_process_general_event(sample, evsel, thread, al);
  651. }
  652. }
  653. static int run_start_sub(void)
  654. {
  655. main_module = PyImport_AddModule("__main__");
  656. if (main_module == NULL)
  657. return -1;
  658. Py_INCREF(main_module);
  659. main_dict = PyModule_GetDict(main_module);
  660. if (main_dict == NULL)
  661. goto error;
  662. Py_INCREF(main_dict);
  663. try_call_object("trace_begin", NULL);
  664. return 0;
  665. error:
  666. Py_XDECREF(main_dict);
  667. Py_XDECREF(main_module);
  668. return -1;
  669. }
  670. #define SET_TABLE_HANDLER_(name, handler_name, table_name) do { \
  671. tables->handler_name = get_handler(#table_name); \
  672. if (tables->handler_name) \
  673. tables->dbe.export_ ## name = python_export_ ## name; \
  674. } while (0)
  675. #define SET_TABLE_HANDLER(name) \
  676. SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
  677. static void set_table_handlers(struct tables *tables)
  678. {
  679. const char *perf_db_export_mode = "perf_db_export_mode";
  680. PyObject *db_export_mode;
  681. int ret;
  682. memset(tables, 0, sizeof(struct tables));
  683. if (db_export__init(&tables->dbe))
  684. Py_FatalError("failed to initialize export");
  685. db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
  686. if (!db_export_mode)
  687. return;
  688. ret = PyObject_IsTrue(db_export_mode);
  689. if (ret == -1)
  690. handler_call_die(perf_db_export_mode);
  691. if (!ret)
  692. return;
  693. tables->db_export_mode = true;
  694. /*
  695. * Reserve per symbol space for symbol->db_id via symbol__priv()
  696. */
  697. symbol_conf.priv_size = sizeof(u64);
  698. SET_TABLE_HANDLER(evsel);
  699. SET_TABLE_HANDLER(machine);
  700. SET_TABLE_HANDLER(thread);
  701. SET_TABLE_HANDLER(comm);
  702. SET_TABLE_HANDLER(comm_thread);
  703. SET_TABLE_HANDLER(dso);
  704. SET_TABLE_HANDLER(symbol);
  705. SET_TABLE_HANDLER(sample);
  706. }
  707. /*
  708. * Start trace script
  709. */
  710. static int python_start_script(const char *script, int argc, const char **argv)
  711. {
  712. struct tables *tables = &tables_global;
  713. const char **command_line;
  714. char buf[PATH_MAX];
  715. int i, err = 0;
  716. FILE *fp;
  717. command_line = malloc((argc + 1) * sizeof(const char *));
  718. command_line[0] = script;
  719. for (i = 1; i < argc + 1; i++)
  720. command_line[i] = argv[i - 1];
  721. Py_Initialize();
  722. initperf_trace_context();
  723. PySys_SetArgv(argc + 1, (char **)command_line);
  724. fp = fopen(script, "r");
  725. if (!fp) {
  726. sprintf(buf, "Can't open python script \"%s\"", script);
  727. perror(buf);
  728. err = -1;
  729. goto error;
  730. }
  731. err = PyRun_SimpleFile(fp, script);
  732. if (err) {
  733. fprintf(stderr, "Error running python script %s\n", script);
  734. goto error;
  735. }
  736. err = run_start_sub();
  737. if (err) {
  738. fprintf(stderr, "Error starting python script %s\n", script);
  739. goto error;
  740. }
  741. free(command_line);
  742. set_table_handlers(tables);
  743. return err;
  744. error:
  745. Py_Finalize();
  746. free(command_line);
  747. return err;
  748. }
  749. static int python_flush_script(void)
  750. {
  751. return 0;
  752. }
  753. /*
  754. * Stop trace script
  755. */
  756. static int python_stop_script(void)
  757. {
  758. struct tables *tables = &tables_global;
  759. try_call_object("trace_end", NULL);
  760. db_export__exit(&tables->dbe);
  761. Py_XDECREF(main_dict);
  762. Py_XDECREF(main_module);
  763. Py_Finalize();
  764. return 0;
  765. }
  766. static int python_generate_script(struct pevent *pevent, const char *outfile)
  767. {
  768. struct event_format *event = NULL;
  769. struct format_field *f;
  770. char fname[PATH_MAX];
  771. int not_first, count;
  772. FILE *ofp;
  773. sprintf(fname, "%s.py", outfile);
  774. ofp = fopen(fname, "w");
  775. if (ofp == NULL) {
  776. fprintf(stderr, "couldn't open %s\n", fname);
  777. return -1;
  778. }
  779. fprintf(ofp, "# perf script event handlers, "
  780. "generated by perf script -g python\n");
  781. fprintf(ofp, "# Licensed under the terms of the GNU GPL"
  782. " License version 2\n\n");
  783. fprintf(ofp, "# The common_* event handler fields are the most useful "
  784. "fields common to\n");
  785. fprintf(ofp, "# all events. They don't necessarily correspond to "
  786. "the 'common_*' fields\n");
  787. fprintf(ofp, "# in the format files. Those fields not available as "
  788. "handler params can\n");
  789. fprintf(ofp, "# be retrieved using Python functions of the form "
  790. "common_*(context).\n");
  791. fprintf(ofp, "# See the perf-trace-python Documentation for the list "
  792. "of available functions.\n\n");
  793. fprintf(ofp, "import os\n");
  794. fprintf(ofp, "import sys\n\n");
  795. fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
  796. fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
  797. fprintf(ofp, "\nfrom perf_trace_context import *\n");
  798. fprintf(ofp, "from Core import *\n\n\n");
  799. fprintf(ofp, "def trace_begin():\n");
  800. fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
  801. fprintf(ofp, "def trace_end():\n");
  802. fprintf(ofp, "\tprint \"in trace_end\"\n\n");
  803. while ((event = trace_find_next_event(pevent, event))) {
  804. fprintf(ofp, "def %s__%s(", event->system, event->name);
  805. fprintf(ofp, "event_name, ");
  806. fprintf(ofp, "context, ");
  807. fprintf(ofp, "common_cpu,\n");
  808. fprintf(ofp, "\tcommon_secs, ");
  809. fprintf(ofp, "common_nsecs, ");
  810. fprintf(ofp, "common_pid, ");
  811. fprintf(ofp, "common_comm,\n\t");
  812. fprintf(ofp, "common_callchain, ");
  813. not_first = 0;
  814. count = 0;
  815. for (f = event->format.fields; f; f = f->next) {
  816. if (not_first++)
  817. fprintf(ofp, ", ");
  818. if (++count % 5 == 0)
  819. fprintf(ofp, "\n\t");
  820. fprintf(ofp, "%s", f->name);
  821. }
  822. fprintf(ofp, "):\n");
  823. fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
  824. "common_secs, common_nsecs,\n\t\t\t"
  825. "common_pid, common_comm)\n\n");
  826. fprintf(ofp, "\t\tprint \"");
  827. not_first = 0;
  828. count = 0;
  829. for (f = event->format.fields; f; f = f->next) {
  830. if (not_first++)
  831. fprintf(ofp, ", ");
  832. if (count && count % 3 == 0) {
  833. fprintf(ofp, "\" \\\n\t\t\"");
  834. }
  835. count++;
  836. fprintf(ofp, "%s=", f->name);
  837. if (f->flags & FIELD_IS_STRING ||
  838. f->flags & FIELD_IS_FLAG ||
  839. f->flags & FIELD_IS_ARRAY ||
  840. f->flags & FIELD_IS_SYMBOLIC)
  841. fprintf(ofp, "%%s");
  842. else if (f->flags & FIELD_IS_SIGNED)
  843. fprintf(ofp, "%%d");
  844. else
  845. fprintf(ofp, "%%u");
  846. }
  847. fprintf(ofp, "\" %% \\\n\t\t(");
  848. not_first = 0;
  849. count = 0;
  850. for (f = event->format.fields; f; f = f->next) {
  851. if (not_first++)
  852. fprintf(ofp, ", ");
  853. if (++count % 5 == 0)
  854. fprintf(ofp, "\n\t\t");
  855. if (f->flags & FIELD_IS_FLAG) {
  856. if ((count - 1) % 5 != 0) {
  857. fprintf(ofp, "\n\t\t");
  858. count = 4;
  859. }
  860. fprintf(ofp, "flag_str(\"");
  861. fprintf(ofp, "%s__%s\", ", event->system,
  862. event->name);
  863. fprintf(ofp, "\"%s\", %s)", f->name,
  864. f->name);
  865. } else if (f->flags & FIELD_IS_SYMBOLIC) {
  866. if ((count - 1) % 5 != 0) {
  867. fprintf(ofp, "\n\t\t");
  868. count = 4;
  869. }
  870. fprintf(ofp, "symbol_str(\"");
  871. fprintf(ofp, "%s__%s\", ", event->system,
  872. event->name);
  873. fprintf(ofp, "\"%s\", %s)", f->name,
  874. f->name);
  875. } else
  876. fprintf(ofp, "%s", f->name);
  877. }
  878. fprintf(ofp, ")\n\n");
  879. fprintf(ofp, "\t\tfor node in common_callchain:");
  880. fprintf(ofp, "\n\t\t\tif 'sym' in node:");
  881. fprintf(ofp, "\n\t\t\t\tprint \"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name'])");
  882. fprintf(ofp, "\n\t\t\telse:");
  883. fprintf(ofp, "\n\t\t\t\tprint \"\t[%%x]\" %% (node['ip'])\n\n");
  884. fprintf(ofp, "\t\tprint \"\\n\"\n\n");
  885. }
  886. fprintf(ofp, "def trace_unhandled(event_name, context, "
  887. "event_fields_dict):\n");
  888. fprintf(ofp, "\t\tprint ' '.join(['%%s=%%s'%%(k,str(v))"
  889. "for k,v in sorted(event_fields_dict.items())])\n\n");
  890. fprintf(ofp, "def print_header("
  891. "event_name, cpu, secs, nsecs, pid, comm):\n"
  892. "\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
  893. "(event_name, cpu, secs, nsecs, pid, comm),\n");
  894. fclose(ofp);
  895. fprintf(stderr, "generated Python script: %s\n", fname);
  896. return 0;
  897. }
  898. struct scripting_ops python_scripting_ops = {
  899. .name = "Python",
  900. .start_script = python_start_script,
  901. .flush_script = python_flush_script,
  902. .stop_script = python_stop_script,
  903. .process_event = python_process_event,
  904. .generate_script = python_generate_script,
  905. };