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"
31 #include "../callchain.h"
35 #include "../thread.h"
36 #include "../trace-event.h"
37 #include "../machine.h"
39 PyMODINIT_FUNC initperf_trace_context(void);
41 #define FTRACE_MAX_EVENT \
42 ((1 << (sizeof(unsigned short) * 8)) - 1)
44 struct event_format *events[FTRACE_MAX_EVENT];
47 #define N_COMMON_FIELDS 7
49 extern struct scripting_context *scripting_context;
51 static char *cur_field_name;
52 static int zero_flag_atom;
54 static PyObject *main_module, *main_dict;
56 static void handler_call_die(const char *handler_name) NORETURN;
57 static void handler_call_die(const char *handler_name)
60 Py_FatalError("problem in Python trace event handler");
61 // Py_FatalError does not return
62 // but we have to make the compiler happy
67 * Insert val into into the dictionary and decrement the reference counter.
68 * This is necessary for dictionaries since PyDict_SetItemString() does not
69 * steal a reference, as opposed to PyTuple_SetItem().
71 static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
73 PyDict_SetItemString(dict, key, val);
77 static PyObject *get_handler(const char *handler_name)
81 handler = PyDict_GetItemString(main_dict, handler_name);
82 if (handler && !PyCallable_Check(handler))
87 static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
91 retval = PyObject_CallObject(handler, args);
93 handler_call_die(die_msg);
97 static void try_call_object(const char *handler_name, PyObject *args)
101 handler = get_handler(handler_name);
103 call_object(handler, args, handler_name);
106 static void define_value(enum print_arg_type field_type,
108 const char *field_name,
109 const char *field_value,
110 const char *field_str)
112 const char *handler_name = "define_flag_value";
114 unsigned long long value;
117 if (field_type == PRINT_SYMBOL)
118 handler_name = "define_symbolic_value";
122 Py_FatalError("couldn't create Python tuple");
124 value = eval_flag(field_value);
126 PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
127 PyTuple_SetItem(t, n++, PyString_FromString(field_name));
128 PyTuple_SetItem(t, n++, PyInt_FromLong(value));
129 PyTuple_SetItem(t, n++, PyString_FromString(field_str));
131 try_call_object(handler_name, t);
136 static void define_values(enum print_arg_type field_type,
137 struct print_flag_sym *field,
139 const char *field_name)
141 define_value(field_type, ev_name, field_name, field->value,
145 define_values(field_type, field->next, ev_name, field_name);
148 static void define_field(enum print_arg_type field_type,
150 const char *field_name,
153 const char *handler_name = "define_flag_field";
157 if (field_type == PRINT_SYMBOL)
158 handler_name = "define_symbolic_field";
160 if (field_type == PRINT_FLAGS)
165 Py_FatalError("couldn't create Python tuple");
167 PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
168 PyTuple_SetItem(t, n++, PyString_FromString(field_name));
169 if (field_type == PRINT_FLAGS)
170 PyTuple_SetItem(t, n++, PyString_FromString(delim));
172 try_call_object(handler_name, t);
177 static void define_event_symbols(struct event_format *event,
179 struct print_arg *args)
181 switch (args->type) {
185 define_value(PRINT_FLAGS, ev_name, cur_field_name, "0",
190 free(cur_field_name);
191 cur_field_name = strdup(args->field.name);
194 define_event_symbols(event, ev_name, args->flags.field);
195 define_field(PRINT_FLAGS, ev_name, cur_field_name,
197 define_values(PRINT_FLAGS, args->flags.flags, ev_name,
201 define_event_symbols(event, ev_name, args->symbol.field);
202 define_field(PRINT_SYMBOL, ev_name, cur_field_name, NULL);
203 define_values(PRINT_SYMBOL, args->symbol.symbols, ev_name,
207 define_event_symbols(event, ev_name, args->hex.field);
208 define_event_symbols(event, ev_name, args->hex.size);
213 define_event_symbols(event, ev_name, args->typecast.item);
216 if (strcmp(args->op.op, ":") == 0)
218 define_event_symbols(event, ev_name, args->op.left);
219 define_event_symbols(event, ev_name, args->op.right);
222 /* gcc warns for these? */
224 case PRINT_DYNAMIC_ARRAY:
227 /* we should warn... */
232 define_event_symbols(event, ev_name, args->next);
235 static inline struct event_format *find_cache_event(struct perf_evsel *evsel)
237 static char ev_name[256];
238 struct event_format *event;
239 int type = evsel->attr.config;
242 * XXX: Do we really need to cache this since now we have evsel->tp_format
243 * cached already? Need to re-read this "cache" routine that as well calls
244 * define_event_symbols() :-\
249 events[type] = event = evsel->tp_format;
253 sprintf(ev_name, "%s__%s", event->system, event->name);
255 define_event_symbols(event, ev_name, event->print_fmt.args);
260 static PyObject *get_field_numeric_entry(struct event_format *event,
261 struct format_field *field, void *data)
263 bool is_array = field->flags & FIELD_IS_ARRAY;
264 PyObject *obj, *list = NULL;
265 unsigned long long val;
266 unsigned int item_size, n_items, i;
269 list = PyList_New(field->arraylen);
270 item_size = field->size / field->arraylen;
271 n_items = field->arraylen;
273 item_size = field->size;
277 for (i = 0; i < n_items; i++) {
279 val = read_size(event, data + field->offset + i * item_size,
281 if (field->flags & FIELD_IS_SIGNED) {
282 if ((long long)val >= LONG_MIN &&
283 (long long)val <= LONG_MAX)
284 obj = PyInt_FromLong(val);
286 obj = PyLong_FromLongLong(val);
289 obj = PyInt_FromLong(val);
291 obj = PyLong_FromUnsignedLongLong(val);
294 PyList_SET_ITEM(list, i, obj);
302 static PyObject *python_process_callchain(struct perf_sample *sample,
303 struct perf_evsel *evsel,
304 struct addr_location *al)
308 pylist = PyList_New(0);
310 Py_FatalError("couldn't create Python list");
312 if (!symbol_conf.use_callchain || !sample->callchain)
315 if (machine__resolve_callchain(al->machine, evsel, al->thread,
317 PERF_MAX_STACK_DEPTH) != 0) {
318 pr_err("Failed to resolve callchain. Skipping\n");
321 callchain_cursor_commit(&callchain_cursor);
326 struct callchain_cursor_node *node;
327 node = callchain_cursor_current(&callchain_cursor);
331 pyelem = PyDict_New();
333 Py_FatalError("couldn't create Python dictionary");
336 pydict_set_item_string_decref(pyelem, "ip",
337 PyLong_FromUnsignedLongLong(node->ip));
340 PyObject *pysym = PyDict_New();
342 Py_FatalError("couldn't create Python dictionary");
343 pydict_set_item_string_decref(pysym, "start",
344 PyLong_FromUnsignedLongLong(node->sym->start));
345 pydict_set_item_string_decref(pysym, "end",
346 PyLong_FromUnsignedLongLong(node->sym->end));
347 pydict_set_item_string_decref(pysym, "binding",
348 PyInt_FromLong(node->sym->binding));
349 pydict_set_item_string_decref(pysym, "name",
350 PyString_FromStringAndSize(node->sym->name,
351 node->sym->namelen));
352 pydict_set_item_string_decref(pyelem, "sym", pysym);
356 struct map *map = node->map;
357 const char *dsoname = "[unknown]";
358 if (map && map->dso && (map->dso->name || map->dso->long_name)) {
359 if (symbol_conf.show_kernel_path && map->dso->long_name)
360 dsoname = map->dso->long_name;
361 else if (map->dso->name)
362 dsoname = map->dso->name;
364 pydict_set_item_string_decref(pyelem, "dso",
365 PyString_FromString(dsoname));
368 callchain_cursor_advance(&callchain_cursor);
369 PyList_Append(pylist, pyelem);
378 static void python_process_tracepoint(struct perf_sample *sample,
379 struct perf_evsel *evsel,
380 struct thread *thread,
381 struct addr_location *al)
383 PyObject *handler, *context, *t, *obj, *callchain;
384 PyObject *dict = NULL;
385 static char handler_name[256];
386 struct format_field *field;
388 struct event_format *event;
391 int cpu = sample->cpu;
392 void *data = sample->raw_data;
393 unsigned long long nsecs = sample->time;
394 const char *comm = thread__comm_str(thread);
396 t = PyTuple_New(MAX_FIELDS);
398 Py_FatalError("couldn't create Python tuple");
400 event = find_cache_event(evsel);
402 die("ug! no event found for type %d", (int)evsel->attr.config);
404 pid = raw_field_value(event, "common_pid", data);
406 sprintf(handler_name, "%s__%s", event->system, event->name);
408 handler = get_handler(handler_name);
412 Py_FatalError("couldn't create Python dict");
414 s = nsecs / NSECS_PER_SEC;
415 ns = nsecs - s * NSECS_PER_SEC;
417 scripting_context->event_data = data;
418 scripting_context->pevent = evsel->tp_format->pevent;
420 context = PyCObject_FromVoidPtr(scripting_context, NULL);
422 PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
423 PyTuple_SetItem(t, n++, context);
426 callchain = python_process_callchain(sample, evsel, al);
429 PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
430 PyTuple_SetItem(t, n++, PyInt_FromLong(s));
431 PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
432 PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
433 PyTuple_SetItem(t, n++, PyString_FromString(comm));
434 PyTuple_SetItem(t, n++, callchain);
436 pydict_set_item_string_decref(dict, "common_cpu", PyInt_FromLong(cpu));
437 pydict_set_item_string_decref(dict, "common_s", PyInt_FromLong(s));
438 pydict_set_item_string_decref(dict, "common_ns", PyInt_FromLong(ns));
439 pydict_set_item_string_decref(dict, "common_pid", PyInt_FromLong(pid));
440 pydict_set_item_string_decref(dict, "common_comm", PyString_FromString(comm));
441 pydict_set_item_string_decref(dict, "common_callchain", callchain);
443 for (field = event->format.fields; field; field = field->next) {
444 if (field->flags & FIELD_IS_STRING) {
446 if (field->flags & FIELD_IS_DYNAMIC) {
447 offset = *(int *)(data + field->offset);
450 offset = field->offset;
451 obj = PyString_FromString((char *)data + offset);
452 } else { /* FIELD_IS_NUMERIC */
453 obj = get_field_numeric_entry(event, field, data);
456 PyTuple_SetItem(t, n++, obj);
458 pydict_set_item_string_decref(dict, field->name, obj);
463 PyTuple_SetItem(t, n++, dict);
465 if (_PyTuple_Resize(&t, n) == -1)
466 Py_FatalError("error resizing Python tuple");
469 call_object(handler, t, handler_name);
471 try_call_object("trace_unhandled", t);
478 static void python_process_general_event(struct perf_sample *sample,
479 struct perf_evsel *evsel,
480 struct thread *thread,
481 struct addr_location *al)
483 PyObject *handler, *t, *dict, *callchain, *dict_sample;
484 static char handler_name[64];
488 * Use the MAX_FIELDS to make the function expandable, though
489 * currently there is only one item for the tuple.
491 t = PyTuple_New(MAX_FIELDS);
493 Py_FatalError("couldn't create Python tuple");
497 Py_FatalError("couldn't create Python dictionary");
499 dict_sample = PyDict_New();
501 Py_FatalError("couldn't create Python dictionary");
503 snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
505 handler = get_handler(handler_name);
509 pydict_set_item_string_decref(dict, "ev_name", PyString_FromString(perf_evsel__name(evsel)));
510 pydict_set_item_string_decref(dict, "attr", PyString_FromStringAndSize(
511 (const char *)&evsel->attr, sizeof(evsel->attr)));
513 pydict_set_item_string_decref(dict_sample, "pid",
514 PyInt_FromLong(sample->pid));
515 pydict_set_item_string_decref(dict_sample, "tid",
516 PyInt_FromLong(sample->tid));
517 pydict_set_item_string_decref(dict_sample, "cpu",
518 PyInt_FromLong(sample->cpu));
519 pydict_set_item_string_decref(dict_sample, "ip",
520 PyLong_FromUnsignedLongLong(sample->ip));
521 pydict_set_item_string_decref(dict_sample, "time",
522 PyLong_FromUnsignedLongLong(sample->time));
523 pydict_set_item_string_decref(dict_sample, "period",
524 PyLong_FromUnsignedLongLong(sample->period));
525 pydict_set_item_string_decref(dict, "sample", dict_sample);
527 pydict_set_item_string_decref(dict, "raw_buf", PyString_FromStringAndSize(
528 (const char *)sample->raw_data, sample->raw_size));
529 pydict_set_item_string_decref(dict, "comm",
530 PyString_FromString(thread__comm_str(thread)));
532 pydict_set_item_string_decref(dict, "dso",
533 PyString_FromString(al->map->dso->name));
536 pydict_set_item_string_decref(dict, "symbol",
537 PyString_FromString(al->sym->name));
541 callchain = python_process_callchain(sample, evsel, al);
542 pydict_set_item_string_decref(dict, "callchain", callchain);
544 PyTuple_SetItem(t, n++, dict);
545 if (_PyTuple_Resize(&t, n) == -1)
546 Py_FatalError("error resizing Python tuple");
548 call_object(handler, t, handler_name);
554 static void python_process_event(union perf_event *event __maybe_unused,
555 struct perf_sample *sample,
556 struct perf_evsel *evsel,
557 struct thread *thread,
558 struct addr_location *al)
560 switch (evsel->attr.type) {
561 case PERF_TYPE_TRACEPOINT:
562 python_process_tracepoint(sample, evsel, thread, al);
564 /* Reserve for future process_hw/sw/raw APIs */
566 python_process_general_event(sample, evsel, thread, al);
570 static int run_start_sub(void)
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)
580 Py_INCREF(main_dict);
582 try_call_object("trace_begin", NULL);
587 Py_XDECREF(main_dict);
588 Py_XDECREF(main_module);
595 static int python_start_script(const char *script, int argc, const char **argv)
597 const char **command_line;
602 command_line = malloc((argc + 1) * sizeof(const char *));
603 command_line[0] = script;
604 for (i = 1; i < argc + 1; i++)
605 command_line[i] = argv[i - 1];
609 initperf_trace_context();
611 PySys_SetArgv(argc + 1, (char **)command_line);
613 fp = fopen(script, "r");
615 sprintf(buf, "Can't open python script \"%s\"", script);
621 err = PyRun_SimpleFile(fp, script);
623 fprintf(stderr, "Error running python script %s\n", script);
627 err = run_start_sub();
629 fprintf(stderr, "Error starting python script %s\n", script);
643 static int python_flush_script(void)
651 static int python_stop_script(void)
653 try_call_object("trace_end", NULL);
655 Py_XDECREF(main_dict);
656 Py_XDECREF(main_module);
662 static int python_generate_script(struct pevent *pevent, const char *outfile)
664 struct event_format *event = NULL;
665 struct format_field *f;
666 char fname[PATH_MAX];
667 int not_first, count;
670 sprintf(fname, "%s.py", outfile);
671 ofp = fopen(fname, "w");
673 fprintf(stderr, "couldn't open %s\n", fname);
676 fprintf(ofp, "# perf script event handlers, "
677 "generated by perf script -g python\n");
679 fprintf(ofp, "# Licensed under the terms of the GNU GPL"
680 " License version 2\n\n");
682 fprintf(ofp, "# The common_* event handler fields are the most useful "
683 "fields common to\n");
685 fprintf(ofp, "# all events. They don't necessarily correspond to "
686 "the 'common_*' fields\n");
688 fprintf(ofp, "# in the format files. Those fields not available as "
689 "handler params can\n");
691 fprintf(ofp, "# be retrieved using Python functions of the form "
692 "common_*(context).\n");
694 fprintf(ofp, "# See the perf-trace-python Documentation for the list "
695 "of available functions.\n\n");
697 fprintf(ofp, "import os\n");
698 fprintf(ofp, "import sys\n\n");
700 fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
701 fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
702 fprintf(ofp, "\nfrom perf_trace_context import *\n");
703 fprintf(ofp, "from Core import *\n\n\n");
705 fprintf(ofp, "def trace_begin():\n");
706 fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
708 fprintf(ofp, "def trace_end():\n");
709 fprintf(ofp, "\tprint \"in trace_end\"\n\n");
711 while ((event = trace_find_next_event(pevent, event))) {
712 fprintf(ofp, "def %s__%s(", event->system, event->name);
713 fprintf(ofp, "event_name, ");
714 fprintf(ofp, "context, ");
715 fprintf(ofp, "common_cpu,\n");
716 fprintf(ofp, "\tcommon_secs, ");
717 fprintf(ofp, "common_nsecs, ");
718 fprintf(ofp, "common_pid, ");
719 fprintf(ofp, "common_comm,\n\t");
720 fprintf(ofp, "common_callchain, ");
725 for (f = event->format.fields; f; f = f->next) {
728 if (++count % 5 == 0)
729 fprintf(ofp, "\n\t");
731 fprintf(ofp, "%s", f->name);
733 fprintf(ofp, "):\n");
735 fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
736 "common_secs, common_nsecs,\n\t\t\t"
737 "common_pid, common_comm)\n\n");
739 fprintf(ofp, "\t\tprint \"");
744 for (f = event->format.fields; f; f = f->next) {
747 if (count && count % 3 == 0) {
748 fprintf(ofp, "\" \\\n\t\t\"");
752 fprintf(ofp, "%s=", f->name);
753 if (f->flags & FIELD_IS_STRING ||
754 f->flags & FIELD_IS_FLAG ||
755 f->flags & FIELD_IS_ARRAY ||
756 f->flags & FIELD_IS_SYMBOLIC)
758 else if (f->flags & FIELD_IS_SIGNED)
764 fprintf(ofp, "\" %% \\\n\t\t(");
769 for (f = event->format.fields; f; f = f->next) {
773 if (++count % 5 == 0)
774 fprintf(ofp, "\n\t\t");
776 if (f->flags & FIELD_IS_FLAG) {
777 if ((count - 1) % 5 != 0) {
778 fprintf(ofp, "\n\t\t");
781 fprintf(ofp, "flag_str(\"");
782 fprintf(ofp, "%s__%s\", ", event->system,
784 fprintf(ofp, "\"%s\", %s)", f->name,
786 } else if (f->flags & FIELD_IS_SYMBOLIC) {
787 if ((count - 1) % 5 != 0) {
788 fprintf(ofp, "\n\t\t");
791 fprintf(ofp, "symbol_str(\"");
792 fprintf(ofp, "%s__%s\", ", event->system,
794 fprintf(ofp, "\"%s\", %s)", f->name,
797 fprintf(ofp, "%s", f->name);
800 fprintf(ofp, ")\n\n");
802 fprintf(ofp, "\t\tfor node in common_callchain:");
803 fprintf(ofp, "\n\t\t\tif 'sym' in node:");
804 fprintf(ofp, "\n\t\t\t\tprint \"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name'])");
805 fprintf(ofp, "\n\t\t\telse:");
806 fprintf(ofp, "\n\t\t\t\tprint \"\t[%%x]\" %% (node['ip'])\n\n");
807 fprintf(ofp, "\t\tprint \"\\n\"\n\n");
811 fprintf(ofp, "def trace_unhandled(event_name, context, "
812 "event_fields_dict):\n");
814 fprintf(ofp, "\t\tprint ' '.join(['%%s=%%s'%%(k,str(v))"
815 "for k,v in sorted(event_fields_dict.items())])\n\n");
817 fprintf(ofp, "def print_header("
818 "event_name, cpu, secs, nsecs, pid, comm):\n"
819 "\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
820 "(event_name, cpu, secs, nsecs, pid, comm),\n");
824 fprintf(stderr, "generated Python script: %s\n", fname);
829 struct scripting_ops python_scripting_ops = {
831 .start_script = python_start_script,
832 .flush_script = python_flush_script,
833 .stop_script = python_stop_script,
834 .process_event = python_process_event,
835 .generate_script = python_generate_script,