2 * trace-event-python. Feed trace events to an embedded Python interpreter.
4 * Copyright (C) 2010 Tom Zanussi <tzanussi@gmail.com>
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.
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.
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
29 #include "../../perf.h"
34 #include "../thread.h"
35 #include "../trace-event.h"
36 #include "../machine.h"
38 PyMODINIT_FUNC initperf_trace_context(void);
40 #define FTRACE_MAX_EVENT \
41 ((1 << (sizeof(unsigned short) * 8)) - 1)
43 struct event_format *events[FTRACE_MAX_EVENT];
46 #define N_COMMON_FIELDS 7
48 extern struct scripting_context *scripting_context;
50 static char *cur_field_name;
51 static int zero_flag_atom;
53 static PyObject *main_module, *main_dict;
55 static void handler_call_die(const char *handler_name) NORETURN;
56 static void handler_call_die(const char *handler_name)
59 Py_FatalError("problem in Python trace event handler");
60 // Py_FatalError does not return
61 // but we have to make the compiler happy
66 * Insert val into into the dictionary and decrement the reference counter.
67 * This is necessary for dictionaries since PyDict_SetItemString() does not
68 * steal a reference, as opposed to PyTuple_SetItem().
70 static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
72 PyDict_SetItemString(dict, key, val);
76 static void define_value(enum print_arg_type field_type,
78 const char *field_name,
79 const char *field_value,
80 const char *field_str)
82 const char *handler_name = "define_flag_value";
83 PyObject *handler, *t, *retval;
84 unsigned long long value;
87 if (field_type == PRINT_SYMBOL)
88 handler_name = "define_symbolic_value";
92 Py_FatalError("couldn't create Python tuple");
94 value = eval_flag(field_value);
96 PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
97 PyTuple_SetItem(t, n++, PyString_FromString(field_name));
98 PyTuple_SetItem(t, n++, PyInt_FromLong(value));
99 PyTuple_SetItem(t, n++, PyString_FromString(field_str));
101 handler = PyDict_GetItemString(main_dict, handler_name);
102 if (handler && PyCallable_Check(handler)) {
103 retval = PyObject_CallObject(handler, t);
105 handler_call_die(handler_name);
112 static void define_values(enum print_arg_type field_type,
113 struct print_flag_sym *field,
115 const char *field_name)
117 define_value(field_type, ev_name, field_name, field->value,
121 define_values(field_type, field->next, ev_name, field_name);
124 static void define_field(enum print_arg_type field_type,
126 const char *field_name,
129 const char *handler_name = "define_flag_field";
130 PyObject *handler, *t, *retval;
133 if (field_type == PRINT_SYMBOL)
134 handler_name = "define_symbolic_field";
136 if (field_type == PRINT_FLAGS)
141 Py_FatalError("couldn't create Python tuple");
143 PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
144 PyTuple_SetItem(t, n++, PyString_FromString(field_name));
145 if (field_type == PRINT_FLAGS)
146 PyTuple_SetItem(t, n++, PyString_FromString(delim));
148 handler = PyDict_GetItemString(main_dict, handler_name);
149 if (handler && PyCallable_Check(handler)) {
150 retval = PyObject_CallObject(handler, t);
152 handler_call_die(handler_name);
159 static void define_event_symbols(struct event_format *event,
161 struct print_arg *args)
163 switch (args->type) {
167 define_value(PRINT_FLAGS, ev_name, cur_field_name, "0",
172 free(cur_field_name);
173 cur_field_name = strdup(args->field.name);
176 define_event_symbols(event, ev_name, args->flags.field);
177 define_field(PRINT_FLAGS, ev_name, cur_field_name,
179 define_values(PRINT_FLAGS, args->flags.flags, ev_name,
183 define_event_symbols(event, ev_name, args->symbol.field);
184 define_field(PRINT_SYMBOL, ev_name, cur_field_name, NULL);
185 define_values(PRINT_SYMBOL, args->symbol.symbols, ev_name,
189 define_event_symbols(event, ev_name, args->hex.field);
190 define_event_symbols(event, ev_name, args->hex.size);
195 define_event_symbols(event, ev_name, args->typecast.item);
198 if (strcmp(args->op.op, ":") == 0)
200 define_event_symbols(event, ev_name, args->op.left);
201 define_event_symbols(event, ev_name, args->op.right);
204 /* gcc warns for these? */
206 case PRINT_DYNAMIC_ARRAY:
209 /* we should warn... */
214 define_event_symbols(event, ev_name, args->next);
217 static inline struct event_format *find_cache_event(struct perf_evsel *evsel)
219 static char ev_name[256];
220 struct event_format *event;
221 int type = evsel->attr.config;
224 * XXX: Do we really need to cache this since now we have evsel->tp_format
225 * cached already? Need to re-read this "cache" routine that as well calls
226 * define_event_symbols() :-\
231 events[type] = event = evsel->tp_format;
235 sprintf(ev_name, "%s__%s", event->system, event->name);
237 define_event_symbols(event, ev_name, event->print_fmt.args);
242 static PyObject *get_field_numeric_entry(struct event_format *event,
243 struct format_field *field, void *data)
245 bool is_array = field->flags & FIELD_IS_ARRAY;
246 PyObject *obj, *list = NULL;
247 unsigned long long val;
248 unsigned int item_size, n_items, i;
251 list = PyList_New(field->arraylen);
252 item_size = field->size / field->arraylen;
253 n_items = field->arraylen;
255 item_size = field->size;
259 for (i = 0; i < n_items; i++) {
261 val = read_size(event, data + field->offset + i * item_size,
263 if (field->flags & FIELD_IS_SIGNED) {
264 if ((long long)val >= LONG_MIN &&
265 (long long)val <= LONG_MAX)
266 obj = PyInt_FromLong(val);
268 obj = PyLong_FromLongLong(val);
271 obj = PyInt_FromLong(val);
273 obj = PyLong_FromUnsignedLongLong(val);
276 PyList_SET_ITEM(list, i, obj);
284 static PyObject *python_process_callchain(struct perf_sample *sample,
285 struct perf_evsel *evsel,
286 struct addr_location *al)
290 pylist = PyList_New(0);
292 Py_FatalError("couldn't create Python list");
294 if (!symbol_conf.use_callchain || !sample->callchain)
297 if (machine__resolve_callchain(al->machine, evsel, al->thread,
299 PERF_MAX_STACK_DEPTH) != 0) {
300 pr_err("Failed to resolve callchain. Skipping\n");
303 callchain_cursor_commit(&callchain_cursor);
308 struct callchain_cursor_node *node;
309 node = callchain_cursor_current(&callchain_cursor);
313 pyelem = PyDict_New();
315 Py_FatalError("couldn't create Python dictionary");
318 pydict_set_item_string_decref(pyelem, "ip",
319 PyLong_FromUnsignedLongLong(node->ip));
322 PyObject *pysym = PyDict_New();
324 Py_FatalError("couldn't create Python dictionary");
325 pydict_set_item_string_decref(pysym, "start",
326 PyLong_FromUnsignedLongLong(node->sym->start));
327 pydict_set_item_string_decref(pysym, "end",
328 PyLong_FromUnsignedLongLong(node->sym->end));
329 pydict_set_item_string_decref(pysym, "binding",
330 PyInt_FromLong(node->sym->binding));
331 pydict_set_item_string_decref(pysym, "name",
332 PyString_FromStringAndSize(node->sym->name,
333 node->sym->namelen));
334 pydict_set_item_string_decref(pyelem, "sym", pysym);
338 struct map *map = node->map;
339 const char *dsoname = "[unknown]";
340 if (map && map->dso && (map->dso->name || map->dso->long_name)) {
341 if (symbol_conf.show_kernel_path && map->dso->long_name)
342 dsoname = map->dso->long_name;
343 else if (map->dso->name)
344 dsoname = map->dso->name;
346 pydict_set_item_string_decref(pyelem, "dso",
347 PyString_FromString(dsoname));
350 callchain_cursor_advance(&callchain_cursor);
351 PyList_Append(pylist, pyelem);
360 static void python_process_tracepoint(struct perf_sample *sample,
361 struct perf_evsel *evsel,
362 struct thread *thread,
363 struct addr_location *al)
365 PyObject *handler, *retval, *context, *t, *obj, *callchain;
366 PyObject *dict = NULL;
367 static char handler_name[256];
368 struct format_field *field;
370 struct event_format *event;
373 int cpu = sample->cpu;
374 void *data = sample->raw_data;
375 unsigned long long nsecs = sample->time;
376 const char *comm = thread__comm_str(thread);
378 t = PyTuple_New(MAX_FIELDS);
380 Py_FatalError("couldn't create Python tuple");
382 event = find_cache_event(evsel);
384 die("ug! no event found for type %d", (int)evsel->attr.config);
386 pid = raw_field_value(event, "common_pid", data);
388 sprintf(handler_name, "%s__%s", event->system, event->name);
390 handler = PyDict_GetItemString(main_dict, handler_name);
391 if (handler && !PyCallable_Check(handler))
396 Py_FatalError("couldn't create Python dict");
398 s = nsecs / NSECS_PER_SEC;
399 ns = nsecs - s * NSECS_PER_SEC;
401 scripting_context->event_data = data;
402 scripting_context->pevent = evsel->tp_format->pevent;
404 context = PyCObject_FromVoidPtr(scripting_context, NULL);
406 PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
407 PyTuple_SetItem(t, n++, context);
410 callchain = python_process_callchain(sample, evsel, al);
413 PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
414 PyTuple_SetItem(t, n++, PyInt_FromLong(s));
415 PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
416 PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
417 PyTuple_SetItem(t, n++, PyString_FromString(comm));
418 PyTuple_SetItem(t, n++, callchain);
420 pydict_set_item_string_decref(dict, "common_cpu", PyInt_FromLong(cpu));
421 pydict_set_item_string_decref(dict, "common_s", PyInt_FromLong(s));
422 pydict_set_item_string_decref(dict, "common_ns", PyInt_FromLong(ns));
423 pydict_set_item_string_decref(dict, "common_pid", PyInt_FromLong(pid));
424 pydict_set_item_string_decref(dict, "common_comm", PyString_FromString(comm));
425 pydict_set_item_string_decref(dict, "common_callchain", callchain);
427 for (field = event->format.fields; field; field = field->next) {
428 if (field->flags & FIELD_IS_STRING) {
430 if (field->flags & FIELD_IS_DYNAMIC) {
431 offset = *(int *)(data + field->offset);
434 offset = field->offset;
435 obj = PyString_FromString((char *)data + offset);
436 } else { /* FIELD_IS_NUMERIC */
437 obj = get_field_numeric_entry(event, field, data);
440 PyTuple_SetItem(t, n++, obj);
442 pydict_set_item_string_decref(dict, field->name, obj);
447 PyTuple_SetItem(t, n++, dict);
449 if (_PyTuple_Resize(&t, n) == -1)
450 Py_FatalError("error resizing Python tuple");
453 retval = PyObject_CallObject(handler, t);
455 handler_call_die(handler_name);
458 handler = PyDict_GetItemString(main_dict, "trace_unhandled");
459 if (handler && PyCallable_Check(handler)) {
461 retval = PyObject_CallObject(handler, t);
463 handler_call_die("trace_unhandled");
472 static void python_process_general_event(struct perf_sample *sample,
473 struct perf_evsel *evsel,
474 struct thread *thread,
475 struct addr_location *al)
477 PyObject *handler, *retval, *t, *dict, *callchain, *dict_sample;
478 static char handler_name[64];
482 * Use the MAX_FIELDS to make the function expandable, though
483 * currently there is only one item for the tuple.
485 t = PyTuple_New(MAX_FIELDS);
487 Py_FatalError("couldn't create Python tuple");
491 Py_FatalError("couldn't create Python dictionary");
493 dict_sample = PyDict_New();
495 Py_FatalError("couldn't create Python dictionary");
497 snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
499 handler = PyDict_GetItemString(main_dict, handler_name);
500 if (!handler || !PyCallable_Check(handler))
503 pydict_set_item_string_decref(dict, "ev_name", PyString_FromString(perf_evsel__name(evsel)));
504 pydict_set_item_string_decref(dict, "attr", PyString_FromStringAndSize(
505 (const char *)&evsel->attr, sizeof(evsel->attr)));
507 pydict_set_item_string_decref(dict_sample, "pid",
508 PyInt_FromLong(sample->pid));
509 pydict_set_item_string_decref(dict_sample, "tid",
510 PyInt_FromLong(sample->tid));
511 pydict_set_item_string_decref(dict_sample, "cpu",
512 PyInt_FromLong(sample->cpu));
513 pydict_set_item_string_decref(dict_sample, "ip",
514 PyLong_FromUnsignedLongLong(sample->ip));
515 pydict_set_item_string_decref(dict_sample, "time",
516 PyLong_FromUnsignedLongLong(sample->time));
517 pydict_set_item_string_decref(dict_sample, "period",
518 PyLong_FromUnsignedLongLong(sample->period));
519 pydict_set_item_string_decref(dict, "sample", dict_sample);
521 pydict_set_item_string_decref(dict, "raw_buf", PyString_FromStringAndSize(
522 (const char *)sample->raw_data, sample->raw_size));
523 pydict_set_item_string_decref(dict, "comm",
524 PyString_FromString(thread__comm_str(thread)));
526 pydict_set_item_string_decref(dict, "dso",
527 PyString_FromString(al->map->dso->name));
530 pydict_set_item_string_decref(dict, "symbol",
531 PyString_FromString(al->sym->name));
535 callchain = python_process_callchain(sample, evsel, al);
536 pydict_set_item_string_decref(dict, "callchain", callchain);
538 PyTuple_SetItem(t, n++, dict);
539 if (_PyTuple_Resize(&t, n) == -1)
540 Py_FatalError("error resizing Python tuple");
542 retval = PyObject_CallObject(handler, t);
544 handler_call_die(handler_name);
551 static void python_process_event(union perf_event *event __maybe_unused,
552 struct perf_sample *sample,
553 struct perf_evsel *evsel,
554 struct thread *thread,
555 struct addr_location *al)
557 switch (evsel->attr.type) {
558 case PERF_TYPE_TRACEPOINT:
559 python_process_tracepoint(sample, evsel, thread, al);
561 /* Reserve for future process_hw/sw/raw APIs */
563 python_process_general_event(sample, evsel, thread, al);
567 static int run_start_sub(void)
569 PyObject *handler, *retval;
572 main_module = PyImport_AddModule("__main__");
573 if (main_module == NULL)
575 Py_INCREF(main_module);
577 main_dict = PyModule_GetDict(main_module);
578 if (main_dict == NULL) {
582 Py_INCREF(main_dict);
584 handler = PyDict_GetItemString(main_dict, "trace_begin");
585 if (handler == NULL || !PyCallable_Check(handler))
588 retval = PyObject_CallObject(handler, NULL);
590 handler_call_die("trace_begin");
595 Py_XDECREF(main_dict);
596 Py_XDECREF(main_module);
604 static int python_start_script(const char *script, int argc, const char **argv)
606 const char **command_line;
611 command_line = malloc((argc + 1) * sizeof(const char *));
612 command_line[0] = script;
613 for (i = 1; i < argc + 1; i++)
614 command_line[i] = argv[i - 1];
618 initperf_trace_context();
620 PySys_SetArgv(argc + 1, (char **)command_line);
622 fp = fopen(script, "r");
624 sprintf(buf, "Can't open python script \"%s\"", script);
630 err = PyRun_SimpleFile(fp, script);
632 fprintf(stderr, "Error running python script %s\n", script);
636 err = run_start_sub();
638 fprintf(stderr, "Error starting python script %s\n", script);
655 static int python_stop_script(void)
657 PyObject *handler, *retval;
660 handler = PyDict_GetItemString(main_dict, "trace_end");
661 if (handler == NULL || !PyCallable_Check(handler))
664 retval = PyObject_CallObject(handler, NULL);
666 handler_call_die("trace_end");
669 Py_XDECREF(main_dict);
670 Py_XDECREF(main_module);
676 static int python_generate_script(struct pevent *pevent, const char *outfile)
678 struct event_format *event = NULL;
679 struct format_field *f;
680 char fname[PATH_MAX];
681 int not_first, count;
684 sprintf(fname, "%s.py", outfile);
685 ofp = fopen(fname, "w");
687 fprintf(stderr, "couldn't open %s\n", fname);
690 fprintf(ofp, "# perf script event handlers, "
691 "generated by perf script -g python\n");
693 fprintf(ofp, "# Licensed under the terms of the GNU GPL"
694 " License version 2\n\n");
696 fprintf(ofp, "# The common_* event handler fields are the most useful "
697 "fields common to\n");
699 fprintf(ofp, "# all events. They don't necessarily correspond to "
700 "the 'common_*' fields\n");
702 fprintf(ofp, "# in the format files. Those fields not available as "
703 "handler params can\n");
705 fprintf(ofp, "# be retrieved using Python functions of the form "
706 "common_*(context).\n");
708 fprintf(ofp, "# See the perf-trace-python Documentation for the list "
709 "of available functions.\n\n");
711 fprintf(ofp, "import os\n");
712 fprintf(ofp, "import sys\n\n");
714 fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
715 fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
716 fprintf(ofp, "\nfrom perf_trace_context import *\n");
717 fprintf(ofp, "from Core import *\n\n\n");
719 fprintf(ofp, "def trace_begin():\n");
720 fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
722 fprintf(ofp, "def trace_end():\n");
723 fprintf(ofp, "\tprint \"in trace_end\"\n\n");
725 while ((event = trace_find_next_event(pevent, event))) {
726 fprintf(ofp, "def %s__%s(", event->system, event->name);
727 fprintf(ofp, "event_name, ");
728 fprintf(ofp, "context, ");
729 fprintf(ofp, "common_cpu,\n");
730 fprintf(ofp, "\tcommon_secs, ");
731 fprintf(ofp, "common_nsecs, ");
732 fprintf(ofp, "common_pid, ");
733 fprintf(ofp, "common_comm,\n\t");
734 fprintf(ofp, "common_callchain, ");
739 for (f = event->format.fields; f; f = f->next) {
742 if (++count % 5 == 0)
743 fprintf(ofp, "\n\t");
745 fprintf(ofp, "%s", f->name);
747 fprintf(ofp, "):\n");
749 fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
750 "common_secs, common_nsecs,\n\t\t\t"
751 "common_pid, common_comm)\n\n");
753 fprintf(ofp, "\t\tprint \"");
758 for (f = event->format.fields; f; f = f->next) {
761 if (count && count % 3 == 0) {
762 fprintf(ofp, "\" \\\n\t\t\"");
766 fprintf(ofp, "%s=", f->name);
767 if (f->flags & FIELD_IS_STRING ||
768 f->flags & FIELD_IS_FLAG ||
769 f->flags & FIELD_IS_ARRAY ||
770 f->flags & FIELD_IS_SYMBOLIC)
772 else if (f->flags & FIELD_IS_SIGNED)
778 fprintf(ofp, "\" %% \\\n\t\t(");
783 for (f = event->format.fields; f; f = f->next) {
787 if (++count % 5 == 0)
788 fprintf(ofp, "\n\t\t");
790 if (f->flags & FIELD_IS_FLAG) {
791 if ((count - 1) % 5 != 0) {
792 fprintf(ofp, "\n\t\t");
795 fprintf(ofp, "flag_str(\"");
796 fprintf(ofp, "%s__%s\", ", event->system,
798 fprintf(ofp, "\"%s\", %s)", f->name,
800 } else if (f->flags & FIELD_IS_SYMBOLIC) {
801 if ((count - 1) % 5 != 0) {
802 fprintf(ofp, "\n\t\t");
805 fprintf(ofp, "symbol_str(\"");
806 fprintf(ofp, "%s__%s\", ", event->system,
808 fprintf(ofp, "\"%s\", %s)", f->name,
811 fprintf(ofp, "%s", f->name);
814 fprintf(ofp, ")\n\n");
816 fprintf(ofp, "\t\tfor node in common_callchain:");
817 fprintf(ofp, "\n\t\t\tif 'sym' in node:");
818 fprintf(ofp, "\n\t\t\t\tprint \"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name'])");
819 fprintf(ofp, "\n\t\t\telse:");
820 fprintf(ofp, "\n\t\t\t\tprint \"\t[%%x]\" %% (node['ip'])\n\n");
821 fprintf(ofp, "\t\tprint \"\\n\"\n\n");
825 fprintf(ofp, "def trace_unhandled(event_name, context, "
826 "event_fields_dict):\n");
828 fprintf(ofp, "\t\tprint ' '.join(['%%s=%%s'%%(k,str(v))"
829 "for k,v in sorted(event_fields_dict.items())])\n\n");
831 fprintf(ofp, "def print_header("
832 "event_name, cpu, secs, nsecs, pid, comm):\n"
833 "\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
834 "(event_name, cpu, secs, nsecs, pid, comm),\n");
838 fprintf(stderr, "generated Python script: %s\n", fname);
843 struct scripting_ops python_scripting_ops = {
845 .start_script = python_start_script,
846 .stop_script = python_stop_script,
847 .process_event = python_process_event,
848 .generate_script = python_generate_script,