trace-event-python.c 33 KB

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