trace-event-python.c 40 KB

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