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 PyObject *get_handler(const char *handler_name)
80 handler = PyDict_GetItemString(main_dict, handler_name);
81 if (handler && !PyCallable_Check(handler))
86 static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
90 retval = PyObject_CallObject(handler, args);
92 handler_call_die(die_msg);
96 static void try_call_object(const char *handler_name, PyObject *args)
100 handler = get_handler(handler_name);
102 call_object(handler, args, handler_name);
105 static void define_value(enum print_arg_type field_type,
107 const char *field_name,
108 const char *field_value,
109 const char *field_str)
111 const char *handler_name = "define_flag_value";
113 unsigned long long value;
116 if (field_type == PRINT_SYMBOL)
117 handler_name = "define_symbolic_value";
121 Py_FatalError("couldn't create Python tuple");
123 value = eval_flag(field_value);
125 PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
126 PyTuple_SetItem(t, n++, PyString_FromString(field_name));
127 PyTuple_SetItem(t, n++, PyInt_FromLong(value));
128 PyTuple_SetItem(t, n++, PyString_FromString(field_str));
130 try_call_object(handler_name, t);
135 static void define_values(enum print_arg_type field_type,
136 struct print_flag_sym *field,
138 const char *field_name)
140 define_value(field_type, ev_name, field_name, field->value,
144 define_values(field_type, field->next, ev_name, field_name);
147 static void define_field(enum print_arg_type field_type,
149 const char *field_name,
152 const char *handler_name = "define_flag_field";
156 if (field_type == PRINT_SYMBOL)
157 handler_name = "define_symbolic_field";
159 if (field_type == PRINT_FLAGS)
164 Py_FatalError("couldn't create Python tuple");
166 PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
167 PyTuple_SetItem(t, n++, PyString_FromString(field_name));
168 if (field_type == PRINT_FLAGS)
169 PyTuple_SetItem(t, n++, PyString_FromString(delim));
171 try_call_object(handler_name, t);
176 static void define_event_symbols(struct event_format *event,
178 struct print_arg *args)
180 switch (args->type) {
184 define_value(PRINT_FLAGS, ev_name, cur_field_name, "0",
189 free(cur_field_name);
190 cur_field_name = strdup(args->field.name);
193 define_event_symbols(event, ev_name, args->flags.field);
194 define_field(PRINT_FLAGS, ev_name, cur_field_name,
196 define_values(PRINT_FLAGS, args->flags.flags, ev_name,
200 define_event_symbols(event, ev_name, args->symbol.field);
201 define_field(PRINT_SYMBOL, ev_name, cur_field_name, NULL);
202 define_values(PRINT_SYMBOL, args->symbol.symbols, ev_name,
206 define_event_symbols(event, ev_name, args->hex.field);
207 define_event_symbols(event, ev_name, args->hex.size);
212 define_event_symbols(event, ev_name, args->typecast.item);
215 if (strcmp(args->op.op, ":") == 0)
217 define_event_symbols(event, ev_name, args->op.left);
218 define_event_symbols(event, ev_name, args->op.right);
221 /* gcc warns for these? */
223 case PRINT_DYNAMIC_ARRAY:
226 /* we should warn... */
231 define_event_symbols(event, ev_name, args->next);
234 static inline struct event_format *find_cache_event(struct perf_evsel *evsel)
236 static char ev_name[256];
237 struct event_format *event;
238 int type = evsel->attr.config;
241 * XXX: Do we really need to cache this since now we have evsel->tp_format
242 * cached already? Need to re-read this "cache" routine that as well calls
243 * define_event_symbols() :-\
248 events[type] = event = evsel->tp_format;
252 sprintf(ev_name, "%s__%s", event->system, event->name);
254 define_event_symbols(event, ev_name, event->print_fmt.args);
259 static PyObject *get_field_numeric_entry(struct event_format *event,
260 struct format_field *field, void *data)
262 bool is_array = field->flags & FIELD_IS_ARRAY;
263 PyObject *obj, *list = NULL;
264 unsigned long long val;
265 unsigned int item_size, n_items, i;
268 list = PyList_New(field->arraylen);
269 item_size = field->size / field->arraylen;
270 n_items = field->arraylen;
272 item_size = field->size;
276 for (i = 0; i < n_items; i++) {
278 val = read_size(event, data + field->offset + i * item_size,
280 if (field->flags & FIELD_IS_SIGNED) {
281 if ((long long)val >= LONG_MIN &&
282 (long long)val <= LONG_MAX)
283 obj = PyInt_FromLong(val);
285 obj = PyLong_FromLongLong(val);
288 obj = PyInt_FromLong(val);
290 obj = PyLong_FromUnsignedLongLong(val);
293 PyList_SET_ITEM(list, i, obj);
301 static PyObject *python_process_callchain(struct perf_sample *sample,
302 struct perf_evsel *evsel,
303 struct addr_location *al)
307 pylist = PyList_New(0);
309 Py_FatalError("couldn't create Python list");
311 if (!symbol_conf.use_callchain || !sample->callchain)
314 if (machine__resolve_callchain(al->machine, evsel, al->thread,
316 PERF_MAX_STACK_DEPTH) != 0) {
317 pr_err("Failed to resolve callchain. Skipping\n");
320 callchain_cursor_commit(&callchain_cursor);
325 struct callchain_cursor_node *node;
326 node = callchain_cursor_current(&callchain_cursor);
330 pyelem = PyDict_New();
332 Py_FatalError("couldn't create Python dictionary");
335 pydict_set_item_string_decref(pyelem, "ip",
336 PyLong_FromUnsignedLongLong(node->ip));
339 PyObject *pysym = PyDict_New();
341 Py_FatalError("couldn't create Python dictionary");
342 pydict_set_item_string_decref(pysym, "start",
343 PyLong_FromUnsignedLongLong(node->sym->start));
344 pydict_set_item_string_decref(pysym, "end",
345 PyLong_FromUnsignedLongLong(node->sym->end));
346 pydict_set_item_string_decref(pysym, "binding",
347 PyInt_FromLong(node->sym->binding));
348 pydict_set_item_string_decref(pysym, "name",
349 PyString_FromStringAndSize(node->sym->name,
350 node->sym->namelen));
351 pydict_set_item_string_decref(pyelem, "sym", pysym);
355 struct map *map = node->map;
356 const char *dsoname = "[unknown]";
357 if (map && map->dso && (map->dso->name || map->dso->long_name)) {
358 if (symbol_conf.show_kernel_path && map->dso->long_name)
359 dsoname = map->dso->long_name;
360 else if (map->dso->name)
361 dsoname = map->dso->name;
363 pydict_set_item_string_decref(pyelem, "dso",
364 PyString_FromString(dsoname));
367 callchain_cursor_advance(&callchain_cursor);
368 PyList_Append(pylist, pyelem);
377 static void python_process_tracepoint(struct perf_sample *sample,
378 struct perf_evsel *evsel,
379 struct thread *thread,
380 struct addr_location *al)
382 PyObject *handler, *context, *t, *obj, *callchain;
383 PyObject *dict = NULL;
384 static char handler_name[256];
385 struct format_field *field;
387 struct event_format *event;
390 int cpu = sample->cpu;
391 void *data = sample->raw_data;
392 unsigned long long nsecs = sample->time;
393 const char *comm = thread__comm_str(thread);
395 t = PyTuple_New(MAX_FIELDS);
397 Py_FatalError("couldn't create Python tuple");
399 event = find_cache_event(evsel);
401 die("ug! no event found for type %d", (int)evsel->attr.config);
403 pid = raw_field_value(event, "common_pid", data);
405 sprintf(handler_name, "%s__%s", event->system, event->name);
407 handler = get_handler(handler_name);
411 Py_FatalError("couldn't create Python dict");
413 s = nsecs / NSECS_PER_SEC;
414 ns = nsecs - s * NSECS_PER_SEC;
416 scripting_context->event_data = data;
417 scripting_context->pevent = evsel->tp_format->pevent;
419 context = PyCObject_FromVoidPtr(scripting_context, NULL);
421 PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
422 PyTuple_SetItem(t, n++, context);
425 callchain = python_process_callchain(sample, evsel, al);
428 PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
429 PyTuple_SetItem(t, n++, PyInt_FromLong(s));
430 PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
431 PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
432 PyTuple_SetItem(t, n++, PyString_FromString(comm));
433 PyTuple_SetItem(t, n++, callchain);
435 pydict_set_item_string_decref(dict, "common_cpu", PyInt_FromLong(cpu));
436 pydict_set_item_string_decref(dict, "common_s", PyInt_FromLong(s));
437 pydict_set_item_string_decref(dict, "common_ns", PyInt_FromLong(ns));
438 pydict_set_item_string_decref(dict, "common_pid", PyInt_FromLong(pid));
439 pydict_set_item_string_decref(dict, "common_comm", PyString_FromString(comm));
440 pydict_set_item_string_decref(dict, "common_callchain", callchain);
442 for (field = event->format.fields; field; field = field->next) {
443 if (field->flags & FIELD_IS_STRING) {
445 if (field->flags & FIELD_IS_DYNAMIC) {
446 offset = *(int *)(data + field->offset);
449 offset = field->offset;
450 obj = PyString_FromString((char *)data + offset);
451 } else { /* FIELD_IS_NUMERIC */
452 obj = get_field_numeric_entry(event, field, data);
455 PyTuple_SetItem(t, n++, obj);
457 pydict_set_item_string_decref(dict, field->name, obj);
462 PyTuple_SetItem(t, n++, dict);
464 if (_PyTuple_Resize(&t, n) == -1)
465 Py_FatalError("error resizing Python tuple");
468 call_object(handler, t, handler_name);
470 try_call_object("trace_unhandled", t);
477 static void python_process_general_event(struct perf_sample *sample,
478 struct perf_evsel *evsel,
479 struct thread *thread,
480 struct addr_location *al)
482 PyObject *handler, *t, *dict, *callchain, *dict_sample;
483 static char handler_name[64];
487 * Use the MAX_FIELDS to make the function expandable, though
488 * currently there is only one item for the tuple.
490 t = PyTuple_New(MAX_FIELDS);
492 Py_FatalError("couldn't create Python tuple");
496 Py_FatalError("couldn't create Python dictionary");
498 dict_sample = PyDict_New();
500 Py_FatalError("couldn't create Python dictionary");
502 snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
504 handler = get_handler(handler_name);
508 pydict_set_item_string_decref(dict, "ev_name", PyString_FromString(perf_evsel__name(evsel)));
509 pydict_set_item_string_decref(dict, "attr", PyString_FromStringAndSize(
510 (const char *)&evsel->attr, sizeof(evsel->attr)));
512 pydict_set_item_string_decref(dict_sample, "pid",
513 PyInt_FromLong(sample->pid));
514 pydict_set_item_string_decref(dict_sample, "tid",
515 PyInt_FromLong(sample->tid));
516 pydict_set_item_string_decref(dict_sample, "cpu",
517 PyInt_FromLong(sample->cpu));
518 pydict_set_item_string_decref(dict_sample, "ip",
519 PyLong_FromUnsignedLongLong(sample->ip));
520 pydict_set_item_string_decref(dict_sample, "time",
521 PyLong_FromUnsignedLongLong(sample->time));
522 pydict_set_item_string_decref(dict_sample, "period",
523 PyLong_FromUnsignedLongLong(sample->period));
524 pydict_set_item_string_decref(dict, "sample", dict_sample);
526 pydict_set_item_string_decref(dict, "raw_buf", PyString_FromStringAndSize(
527 (const char *)sample->raw_data, sample->raw_size));
528 pydict_set_item_string_decref(dict, "comm",
529 PyString_FromString(thread__comm_str(thread)));
531 pydict_set_item_string_decref(dict, "dso",
532 PyString_FromString(al->map->dso->name));
535 pydict_set_item_string_decref(dict, "symbol",
536 PyString_FromString(al->sym->name));
540 callchain = python_process_callchain(sample, evsel, al);
541 pydict_set_item_string_decref(dict, "callchain", callchain);
543 PyTuple_SetItem(t, n++, dict);
544 if (_PyTuple_Resize(&t, n) == -1)
545 Py_FatalError("error resizing Python tuple");
547 call_object(handler, t, handler_name);
553 static void python_process_event(union perf_event *event __maybe_unused,
554 struct perf_sample *sample,
555 struct perf_evsel *evsel,
556 struct thread *thread,
557 struct addr_location *al)
559 switch (evsel->attr.type) {
560 case PERF_TYPE_TRACEPOINT:
561 python_process_tracepoint(sample, evsel, thread, al);
563 /* Reserve for future process_hw/sw/raw APIs */
565 python_process_general_event(sample, evsel, thread, al);
569 static int run_start_sub(void)
571 main_module = PyImport_AddModule("__main__");
572 if (main_module == NULL)
574 Py_INCREF(main_module);
576 main_dict = PyModule_GetDict(main_module);
577 if (main_dict == NULL)
579 Py_INCREF(main_dict);
581 try_call_object("trace_begin", NULL);
586 Py_XDECREF(main_dict);
587 Py_XDECREF(main_module);
594 static int python_start_script(const char *script, int argc, const char **argv)
596 const char **command_line;
601 command_line = malloc((argc + 1) * sizeof(const char *));
602 command_line[0] = script;
603 for (i = 1; i < argc + 1; i++)
604 command_line[i] = argv[i - 1];
608 initperf_trace_context();
610 PySys_SetArgv(argc + 1, (char **)command_line);
612 fp = fopen(script, "r");
614 sprintf(buf, "Can't open python script \"%s\"", script);
620 err = PyRun_SimpleFile(fp, script);
622 fprintf(stderr, "Error running python script %s\n", script);
626 err = run_start_sub();
628 fprintf(stderr, "Error starting python script %s\n", script);
645 static int python_stop_script(void)
647 try_call_object("trace_end", NULL);
649 Py_XDECREF(main_dict);
650 Py_XDECREF(main_module);
656 static int python_generate_script(struct pevent *pevent, const char *outfile)
658 struct event_format *event = NULL;
659 struct format_field *f;
660 char fname[PATH_MAX];
661 int not_first, count;
664 sprintf(fname, "%s.py", outfile);
665 ofp = fopen(fname, "w");
667 fprintf(stderr, "couldn't open %s\n", fname);
670 fprintf(ofp, "# perf script event handlers, "
671 "generated by perf script -g python\n");
673 fprintf(ofp, "# Licensed under the terms of the GNU GPL"
674 " License version 2\n\n");
676 fprintf(ofp, "# The common_* event handler fields are the most useful "
677 "fields common to\n");
679 fprintf(ofp, "# all events. They don't necessarily correspond to "
680 "the 'common_*' fields\n");
682 fprintf(ofp, "# in the format files. Those fields not available as "
683 "handler params can\n");
685 fprintf(ofp, "# be retrieved using Python functions of the form "
686 "common_*(context).\n");
688 fprintf(ofp, "# See the perf-trace-python Documentation for the list "
689 "of available functions.\n\n");
691 fprintf(ofp, "import os\n");
692 fprintf(ofp, "import sys\n\n");
694 fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
695 fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
696 fprintf(ofp, "\nfrom perf_trace_context import *\n");
697 fprintf(ofp, "from Core import *\n\n\n");
699 fprintf(ofp, "def trace_begin():\n");
700 fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
702 fprintf(ofp, "def trace_end():\n");
703 fprintf(ofp, "\tprint \"in trace_end\"\n\n");
705 while ((event = trace_find_next_event(pevent, event))) {
706 fprintf(ofp, "def %s__%s(", event->system, event->name);
707 fprintf(ofp, "event_name, ");
708 fprintf(ofp, "context, ");
709 fprintf(ofp, "common_cpu,\n");
710 fprintf(ofp, "\tcommon_secs, ");
711 fprintf(ofp, "common_nsecs, ");
712 fprintf(ofp, "common_pid, ");
713 fprintf(ofp, "common_comm,\n\t");
714 fprintf(ofp, "common_callchain, ");
719 for (f = event->format.fields; f; f = f->next) {
722 if (++count % 5 == 0)
723 fprintf(ofp, "\n\t");
725 fprintf(ofp, "%s", f->name);
727 fprintf(ofp, "):\n");
729 fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
730 "common_secs, common_nsecs,\n\t\t\t"
731 "common_pid, common_comm)\n\n");
733 fprintf(ofp, "\t\tprint \"");
738 for (f = event->format.fields; f; f = f->next) {
741 if (count && count % 3 == 0) {
742 fprintf(ofp, "\" \\\n\t\t\"");
746 fprintf(ofp, "%s=", f->name);
747 if (f->flags & FIELD_IS_STRING ||
748 f->flags & FIELD_IS_FLAG ||
749 f->flags & FIELD_IS_ARRAY ||
750 f->flags & FIELD_IS_SYMBOLIC)
752 else if (f->flags & FIELD_IS_SIGNED)
758 fprintf(ofp, "\" %% \\\n\t\t(");
763 for (f = event->format.fields; f; f = f->next) {
767 if (++count % 5 == 0)
768 fprintf(ofp, "\n\t\t");
770 if (f->flags & FIELD_IS_FLAG) {
771 if ((count - 1) % 5 != 0) {
772 fprintf(ofp, "\n\t\t");
775 fprintf(ofp, "flag_str(\"");
776 fprintf(ofp, "%s__%s\", ", event->system,
778 fprintf(ofp, "\"%s\", %s)", f->name,
780 } else if (f->flags & FIELD_IS_SYMBOLIC) {
781 if ((count - 1) % 5 != 0) {
782 fprintf(ofp, "\n\t\t");
785 fprintf(ofp, "symbol_str(\"");
786 fprintf(ofp, "%s__%s\", ", event->system,
788 fprintf(ofp, "\"%s\", %s)", f->name,
791 fprintf(ofp, "%s", f->name);
794 fprintf(ofp, ")\n\n");
796 fprintf(ofp, "\t\tfor node in common_callchain:");
797 fprintf(ofp, "\n\t\t\tif 'sym' in node:");
798 fprintf(ofp, "\n\t\t\t\tprint \"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name'])");
799 fprintf(ofp, "\n\t\t\telse:");
800 fprintf(ofp, "\n\t\t\t\tprint \"\t[%%x]\" %% (node['ip'])\n\n");
801 fprintf(ofp, "\t\tprint \"\\n\"\n\n");
805 fprintf(ofp, "def trace_unhandled(event_name, context, "
806 "event_fields_dict):\n");
808 fprintf(ofp, "\t\tprint ' '.join(['%%s=%%s'%%(k,str(v))"
809 "for k,v in sorted(event_fields_dict.items())])\n\n");
811 fprintf(ofp, "def print_header("
812 "event_name, cpu, secs, nsecs, pid, comm):\n"
813 "\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
814 "(event_name, cpu, secs, nsecs, pid, comm),\n");
818 fprintf(stderr, "generated Python script: %s\n", fname);
823 struct scripting_ops python_scripting_ops = {
825 .start_script = python_start_script,
826 .stop_script = python_stop_script,
827 .process_event = python_process_event,
828 .generate_script = python_generate_script,