2 * trace-event-python. Feed trace events to an embedded Python interpreter.
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"
33 #include "../thread.h"
34 #include "../trace-event.h"
36 PyMODINIT_FUNC initperf_trace_context(void);
38 #define FTRACE_MAX_EVENT \
39 ((1 << (sizeof(unsigned short) * 8)) - 1)
41 struct event_format *events[FTRACE_MAX_EVENT];
44 #define N_COMMON_FIELDS 7
46 extern struct scripting_context *scripting_context;
48 static char *cur_field_name;
49 static int zero_flag_atom;
51 static PyObject *main_module, *main_dict;
53 static void handler_call_die(const char *handler_name)
56 Py_FatalError("problem in Python trace event handler");
60 * Insert val into into the dictionary and decrement the reference counter.
61 * This is necessary for dictionaries since PyDict_SetItemString() does not
62 * steal a reference, as opposed to PyTuple_SetItem().
64 static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
66 PyDict_SetItemString(dict, key, val);
70 static void define_value(enum print_arg_type field_type,
72 const char *field_name,
73 const char *field_value,
74 const char *field_str)
76 const char *handler_name = "define_flag_value";
77 PyObject *handler, *t, *retval;
78 unsigned long long value;
81 if (field_type == PRINT_SYMBOL)
82 handler_name = "define_symbolic_value";
86 Py_FatalError("couldn't create Python tuple");
88 value = eval_flag(field_value);
90 PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
91 PyTuple_SetItem(t, n++, PyString_FromString(field_name));
92 PyTuple_SetItem(t, n++, PyInt_FromLong(value));
93 PyTuple_SetItem(t, n++, PyString_FromString(field_str));
95 handler = PyDict_GetItemString(main_dict, handler_name);
96 if (handler && PyCallable_Check(handler)) {
97 retval = PyObject_CallObject(handler, t);
99 handler_call_die(handler_name);
105 static void define_values(enum print_arg_type field_type,
106 struct print_flag_sym *field,
108 const char *field_name)
110 define_value(field_type, ev_name, field_name, field->value,
114 define_values(field_type, field->next, ev_name, field_name);
117 static void define_field(enum print_arg_type field_type,
119 const char *field_name,
122 const char *handler_name = "define_flag_field";
123 PyObject *handler, *t, *retval;
126 if (field_type == PRINT_SYMBOL)
127 handler_name = "define_symbolic_field";
129 if (field_type == PRINT_FLAGS)
134 Py_FatalError("couldn't create Python tuple");
136 PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
137 PyTuple_SetItem(t, n++, PyString_FromString(field_name));
138 if (field_type == PRINT_FLAGS)
139 PyTuple_SetItem(t, n++, PyString_FromString(delim));
141 handler = PyDict_GetItemString(main_dict, handler_name);
142 if (handler && PyCallable_Check(handler)) {
143 retval = PyObject_CallObject(handler, t);
145 handler_call_die(handler_name);
151 static void define_event_symbols(struct event_format *event,
153 struct print_arg *args)
155 switch (args->type) {
159 define_value(PRINT_FLAGS, ev_name, cur_field_name, "0",
165 free(cur_field_name);
166 cur_field_name = strdup(args->field.name);
169 define_event_symbols(event, ev_name, args->flags.field);
170 define_field(PRINT_FLAGS, ev_name, cur_field_name,
172 define_values(PRINT_FLAGS, args->flags.flags, ev_name,
176 define_event_symbols(event, ev_name, args->symbol.field);
177 define_field(PRINT_SYMBOL, ev_name, cur_field_name, NULL);
178 define_values(PRINT_SYMBOL, args->symbol.symbols, ev_name,
182 define_event_symbols(event, ev_name, args->hex.field);
183 define_event_symbols(event, ev_name, args->hex.size);
188 define_event_symbols(event, ev_name, args->typecast.item);
191 if (strcmp(args->op.op, ":") == 0)
193 define_event_symbols(event, ev_name, args->op.left);
194 define_event_symbols(event, ev_name, args->op.right);
197 /* gcc warns for these? */
199 case PRINT_DYNAMIC_ARRAY:
201 /* we should warn... */
206 define_event_symbols(event, ev_name, args->next);
209 static inline struct event_format *find_cache_event(struct perf_evsel *evsel)
211 static char ev_name[256];
212 struct event_format *event;
213 int type = evsel->attr.config;
216 * XXX: Do we really need to cache this since now we have evsel->tp_format
217 * cached already? Need to re-read this "cache" routine that as well calls
218 * define_event_symbols() :-\
223 events[type] = event = evsel->tp_format;
227 sprintf(ev_name, "%s__%s", event->system, event->name);
229 define_event_symbols(event, ev_name, event->print_fmt.args);
234 static void python_process_tracepoint(union perf_event *perf_event
236 struct perf_sample *sample,
237 struct perf_evsel *evsel,
238 struct machine *machine __maybe_unused,
239 struct thread *thread,
240 struct addr_location *al)
242 PyObject *handler, *retval, *context, *t, *obj, *dict = NULL;
243 static char handler_name[256];
244 struct format_field *field;
245 unsigned long long val;
247 struct event_format *event;
250 int cpu = sample->cpu;
251 void *data = sample->raw_data;
252 unsigned long long nsecs = sample->time;
253 const char *comm = thread__comm_str(thread);
255 t = PyTuple_New(MAX_FIELDS);
257 Py_FatalError("couldn't create Python tuple");
259 event = find_cache_event(evsel);
261 die("ug! no event found for type %d", (int)evsel->attr.config);
263 pid = raw_field_value(event, "common_pid", data);
265 sprintf(handler_name, "%s__%s", event->system, event->name);
267 handler = PyDict_GetItemString(main_dict, handler_name);
268 if (handler && !PyCallable_Check(handler))
273 Py_FatalError("couldn't create Python dict");
275 s = nsecs / NSECS_PER_SEC;
276 ns = nsecs - s * NSECS_PER_SEC;
278 scripting_context->event_data = data;
279 scripting_context->pevent = evsel->tp_format->pevent;
281 context = PyCObject_FromVoidPtr(scripting_context, NULL);
283 PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
284 PyTuple_SetItem(t, n++, context);
287 PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
288 PyTuple_SetItem(t, n++, PyInt_FromLong(s));
289 PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
290 PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
291 PyTuple_SetItem(t, n++, PyString_FromString(comm));
293 pydict_set_item_string_decref(dict, "common_cpu", PyInt_FromLong(cpu));
294 pydict_set_item_string_decref(dict, "common_s", PyInt_FromLong(s));
295 pydict_set_item_string_decref(dict, "common_ns", PyInt_FromLong(ns));
296 pydict_set_item_string_decref(dict, "common_pid", PyInt_FromLong(pid));
297 pydict_set_item_string_decref(dict, "common_comm", PyString_FromString(comm));
299 for (field = event->format.fields; field; field = field->next) {
300 if (field->flags & FIELD_IS_STRING) {
302 if (field->flags & FIELD_IS_DYNAMIC) {
303 offset = *(int *)(data + field->offset);
306 offset = field->offset;
307 obj = PyString_FromString((char *)data + offset);
308 } else { /* FIELD_IS_NUMERIC */
309 val = read_size(event, data + field->offset,
311 if (field->flags & FIELD_IS_SIGNED) {
312 if ((long long)val >= LONG_MIN &&
313 (long long)val <= LONG_MAX)
314 obj = PyInt_FromLong(val);
316 obj = PyLong_FromLongLong(val);
319 obj = PyInt_FromLong(val);
321 obj = PyLong_FromUnsignedLongLong(val);
325 PyTuple_SetItem(t, n++, obj);
327 pydict_set_item_string_decref(dict, field->name, obj);
331 PyTuple_SetItem(t, n++, dict);
333 if (_PyTuple_Resize(&t, n) == -1)
334 Py_FatalError("error resizing Python tuple");
337 retval = PyObject_CallObject(handler, t);
339 handler_call_die(handler_name);
341 handler = PyDict_GetItemString(main_dict, "trace_unhandled");
342 if (handler && PyCallable_Check(handler)) {
344 retval = PyObject_CallObject(handler, t);
346 handler_call_die("trace_unhandled");
354 static void python_process_general_event(union perf_event *perf_event
356 struct perf_sample *sample,
357 struct perf_evsel *evsel,
358 struct machine *machine __maybe_unused,
359 struct thread *thread,
360 struct addr_location *al)
362 PyObject *handler, *retval, *t, *dict;
363 static char handler_name[64];
367 * Use the MAX_FIELDS to make the function expandable, though
368 * currently there is only one item for the tuple.
370 t = PyTuple_New(MAX_FIELDS);
372 Py_FatalError("couldn't create Python tuple");
376 Py_FatalError("couldn't create Python dictionary");
378 snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
380 handler = PyDict_GetItemString(main_dict, handler_name);
381 if (!handler || !PyCallable_Check(handler))
384 pydict_set_item_string_decref(dict, "ev_name", PyString_FromString(perf_evsel__name(evsel)));
385 pydict_set_item_string_decref(dict, "attr", PyString_FromStringAndSize(
386 (const char *)&evsel->attr, sizeof(evsel->attr)));
387 pydict_set_item_string_decref(dict, "sample", PyString_FromStringAndSize(
388 (const char *)sample, sizeof(*sample)));
389 pydict_set_item_string_decref(dict, "raw_buf", PyString_FromStringAndSize(
390 (const char *)sample->raw_data, sample->raw_size));
391 pydict_set_item_string_decref(dict, "comm",
392 PyString_FromString(thread__comm_str(thread)));
394 pydict_set_item_string_decref(dict, "dso",
395 PyString_FromString(al->map->dso->name));
398 pydict_set_item_string_decref(dict, "symbol",
399 PyString_FromString(al->sym->name));
402 PyTuple_SetItem(t, n++, dict);
403 if (_PyTuple_Resize(&t, n) == -1)
404 Py_FatalError("error resizing Python tuple");
406 retval = PyObject_CallObject(handler, t);
408 handler_call_die(handler_name);
414 static void python_process_event(union perf_event *perf_event,
415 struct perf_sample *sample,
416 struct perf_evsel *evsel,
417 struct machine *machine,
418 struct thread *thread,
419 struct addr_location *al)
421 switch (evsel->attr.type) {
422 case PERF_TYPE_TRACEPOINT:
423 python_process_tracepoint(perf_event, sample, evsel,
424 machine, thread, al);
426 /* Reserve for future process_hw/sw/raw APIs */
428 python_process_general_event(perf_event, sample, evsel,
429 machine, thread, al);
433 static int run_start_sub(void)
435 PyObject *handler, *retval;
438 main_module = PyImport_AddModule("__main__");
439 if (main_module == NULL)
441 Py_INCREF(main_module);
443 main_dict = PyModule_GetDict(main_module);
444 if (main_dict == NULL) {
448 Py_INCREF(main_dict);
450 handler = PyDict_GetItemString(main_dict, "trace_begin");
451 if (handler == NULL || !PyCallable_Check(handler))
454 retval = PyObject_CallObject(handler, NULL);
456 handler_call_die("trace_begin");
461 Py_XDECREF(main_dict);
462 Py_XDECREF(main_module);
470 static int python_start_script(const char *script, int argc, const char **argv)
472 const char **command_line;
477 command_line = malloc((argc + 1) * sizeof(const char *));
478 command_line[0] = script;
479 for (i = 1; i < argc + 1; i++)
480 command_line[i] = argv[i - 1];
484 initperf_trace_context();
486 PySys_SetArgv(argc + 1, (char **)command_line);
488 fp = fopen(script, "r");
490 sprintf(buf, "Can't open python script \"%s\"", script);
496 err = PyRun_SimpleFile(fp, script);
498 fprintf(stderr, "Error running python script %s\n", script);
502 err = run_start_sub();
504 fprintf(stderr, "Error starting python script %s\n", script);
521 static int python_stop_script(void)
523 PyObject *handler, *retval;
526 handler = PyDict_GetItemString(main_dict, "trace_end");
527 if (handler == NULL || !PyCallable_Check(handler))
530 retval = PyObject_CallObject(handler, NULL);
532 handler_call_die("trace_end");
536 Py_XDECREF(main_dict);
537 Py_XDECREF(main_module);
543 static int python_generate_script(struct pevent *pevent, const char *outfile)
545 struct event_format *event = NULL;
546 struct format_field *f;
547 char fname[PATH_MAX];
548 int not_first, count;
551 sprintf(fname, "%s.py", outfile);
552 ofp = fopen(fname, "w");
554 fprintf(stderr, "couldn't open %s\n", fname);
557 fprintf(ofp, "# perf script event handlers, "
558 "generated by perf script -g python\n");
560 fprintf(ofp, "# Licensed under the terms of the GNU GPL"
561 " License version 2\n\n");
563 fprintf(ofp, "# The common_* event handler fields are the most useful "
564 "fields common to\n");
566 fprintf(ofp, "# all events. They don't necessarily correspond to "
567 "the 'common_*' fields\n");
569 fprintf(ofp, "# in the format files. Those fields not available as "
570 "handler params can\n");
572 fprintf(ofp, "# be retrieved using Python functions of the form "
573 "common_*(context).\n");
575 fprintf(ofp, "# See the perf-trace-python Documentation for the list "
576 "of available functions.\n\n");
578 fprintf(ofp, "import os\n");
579 fprintf(ofp, "import sys\n\n");
581 fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
582 fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
583 fprintf(ofp, "\nfrom perf_trace_context import *\n");
584 fprintf(ofp, "from Core import *\n\n\n");
586 fprintf(ofp, "def trace_begin():\n");
587 fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
589 fprintf(ofp, "def trace_end():\n");
590 fprintf(ofp, "\tprint \"in trace_end\"\n\n");
592 while ((event = trace_find_next_event(pevent, event))) {
593 fprintf(ofp, "def %s__%s(", event->system, event->name);
594 fprintf(ofp, "event_name, ");
595 fprintf(ofp, "context, ");
596 fprintf(ofp, "common_cpu,\n");
597 fprintf(ofp, "\tcommon_secs, ");
598 fprintf(ofp, "common_nsecs, ");
599 fprintf(ofp, "common_pid, ");
600 fprintf(ofp, "common_comm,\n\t");
605 for (f = event->format.fields; f; f = f->next) {
608 if (++count % 5 == 0)
609 fprintf(ofp, "\n\t");
611 fprintf(ofp, "%s", f->name);
613 fprintf(ofp, "):\n");
615 fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
616 "common_secs, common_nsecs,\n\t\t\t"
617 "common_pid, common_comm)\n\n");
619 fprintf(ofp, "\t\tprint \"");
624 for (f = event->format.fields; f; f = f->next) {
627 if (count && count % 3 == 0) {
628 fprintf(ofp, "\" \\\n\t\t\"");
632 fprintf(ofp, "%s=", f->name);
633 if (f->flags & FIELD_IS_STRING ||
634 f->flags & FIELD_IS_FLAG ||
635 f->flags & FIELD_IS_SYMBOLIC)
637 else if (f->flags & FIELD_IS_SIGNED)
643 fprintf(ofp, "\\n\" %% \\\n\t\t(");
648 for (f = event->format.fields; f; f = f->next) {
652 if (++count % 5 == 0)
653 fprintf(ofp, "\n\t\t");
655 if (f->flags & FIELD_IS_FLAG) {
656 if ((count - 1) % 5 != 0) {
657 fprintf(ofp, "\n\t\t");
660 fprintf(ofp, "flag_str(\"");
661 fprintf(ofp, "%s__%s\", ", event->system,
663 fprintf(ofp, "\"%s\", %s)", f->name,
665 } else if (f->flags & FIELD_IS_SYMBOLIC) {
666 if ((count - 1) % 5 != 0) {
667 fprintf(ofp, "\n\t\t");
670 fprintf(ofp, "symbol_str(\"");
671 fprintf(ofp, "%s__%s\", ", event->system,
673 fprintf(ofp, "\"%s\", %s)", f->name,
676 fprintf(ofp, "%s", f->name);
679 fprintf(ofp, "),\n\n");
682 fprintf(ofp, "def trace_unhandled(event_name, context, "
683 "event_fields_dict):\n");
685 fprintf(ofp, "\t\tprint ' '.join(['%%s=%%s'%%(k,str(v))"
686 "for k,v in sorted(event_fields_dict.items())])\n\n");
688 fprintf(ofp, "def print_header("
689 "event_name, cpu, secs, nsecs, pid, comm):\n"
690 "\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
691 "(event_name, cpu, secs, nsecs, pid, comm),\n");
695 fprintf(stderr, "generated Python script: %s\n", fname);
700 struct scripting_ops python_scripting_ops = {
702 .start_script = python_start_script,
703 .stop_script = python_stop_script,
704 .process_event = python_process_event,
705 .generate_script = python_generate_script,