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
30 #include <linux/bitmap.h>
31 #include <linux/compiler.h>
32 #include <linux/time64.h>
34 #include "../../perf.h"
36 #include "../callchain.h"
40 #include "../thread.h"
42 #include "../machine.h"
43 #include "../db-export.h"
44 #include "../thread-stack.h"
45 #include "../trace-event.h"
46 #include "../machine.h"
47 #include "../call-path.h"
48 #include "thread_map.h"
50 #include "print_binary.h"
53 PyMODINIT_FUNC initperf_trace_context(void);
55 #define TRACE_EVENT_TYPE_MAX \
56 ((1 << (sizeof(unsigned short) * 8)) - 1)
58 static DECLARE_BITMAP(events_defined, TRACE_EVENT_TYPE_MAX);
61 #define N_COMMON_FIELDS 7
63 extern struct scripting_context *scripting_context;
65 static char *cur_field_name;
66 static int zero_flag_atom;
68 static PyObject *main_module, *main_dict;
72 PyObject *evsel_handler;
73 PyObject *machine_handler;
74 PyObject *thread_handler;
75 PyObject *comm_handler;
76 PyObject *comm_thread_handler;
77 PyObject *dso_handler;
78 PyObject *symbol_handler;
79 PyObject *branch_type_handler;
80 PyObject *sample_handler;
81 PyObject *call_path_handler;
82 PyObject *call_return_handler;
86 static struct tables tables_global;
88 static void handler_call_die(const char *handler_name) __noreturn;
89 static void handler_call_die(const char *handler_name)
92 Py_FatalError("problem in Python trace event handler");
93 // Py_FatalError does not return
94 // but we have to make the compiler happy
99 * Insert val into into the dictionary and decrement the reference counter.
100 * This is necessary for dictionaries since PyDict_SetItemString() does not
101 * steal a reference, as opposed to PyTuple_SetItem().
103 static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
105 PyDict_SetItemString(dict, key, val);
109 static PyObject *get_handler(const char *handler_name)
113 handler = PyDict_GetItemString(main_dict, handler_name);
114 if (handler && !PyCallable_Check(handler))
119 static int get_argument_count(PyObject *handler)
124 * The attribute for the code object is func_code in Python 2,
125 * whereas it is __code__ in Python 3.0+.
127 PyObject *code_obj = PyObject_GetAttrString(handler,
129 if (PyErr_Occurred()) {
131 code_obj = PyObject_GetAttrString(handler,
136 PyObject *arg_count_obj = PyObject_GetAttrString(code_obj,
139 arg_count = (int) PyInt_AsLong(arg_count_obj);
140 Py_DECREF(arg_count_obj);
147 static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
151 retval = PyObject_CallObject(handler, args);
153 handler_call_die(die_msg);
157 static void try_call_object(const char *handler_name, PyObject *args)
161 handler = get_handler(handler_name);
163 call_object(handler, args, handler_name);
166 static void define_value(enum print_arg_type field_type,
168 const char *field_name,
169 const char *field_value,
170 const char *field_str)
172 const char *handler_name = "define_flag_value";
174 unsigned long long value;
177 if (field_type == PRINT_SYMBOL)
178 handler_name = "define_symbolic_value";
182 Py_FatalError("couldn't create Python tuple");
184 value = eval_flag(field_value);
186 PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
187 PyTuple_SetItem(t, n++, PyString_FromString(field_name));
188 PyTuple_SetItem(t, n++, PyInt_FromLong(value));
189 PyTuple_SetItem(t, n++, PyString_FromString(field_str));
191 try_call_object(handler_name, t);
196 static void define_values(enum print_arg_type field_type,
197 struct print_flag_sym *field,
199 const char *field_name)
201 define_value(field_type, ev_name, field_name, field->value,
205 define_values(field_type, field->next, ev_name, field_name);
208 static void define_field(enum print_arg_type field_type,
210 const char *field_name,
213 const char *handler_name = "define_flag_field";
217 if (field_type == PRINT_SYMBOL)
218 handler_name = "define_symbolic_field";
220 if (field_type == PRINT_FLAGS)
225 Py_FatalError("couldn't create Python tuple");
227 PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
228 PyTuple_SetItem(t, n++, PyString_FromString(field_name));
229 if (field_type == PRINT_FLAGS)
230 PyTuple_SetItem(t, n++, PyString_FromString(delim));
232 try_call_object(handler_name, t);
237 static void define_event_symbols(struct event_format *event,
239 struct print_arg *args)
244 switch (args->type) {
248 define_value(PRINT_FLAGS, ev_name, cur_field_name, "0",
253 free(cur_field_name);
254 cur_field_name = strdup(args->field.name);
257 define_event_symbols(event, ev_name, args->flags.field);
258 define_field(PRINT_FLAGS, ev_name, cur_field_name,
260 define_values(PRINT_FLAGS, args->flags.flags, ev_name,
264 define_event_symbols(event, ev_name, args->symbol.field);
265 define_field(PRINT_SYMBOL, ev_name, cur_field_name, NULL);
266 define_values(PRINT_SYMBOL, args->symbol.symbols, ev_name,
271 define_event_symbols(event, ev_name, args->hex.field);
272 define_event_symbols(event, ev_name, args->hex.size);
274 case PRINT_INT_ARRAY:
275 define_event_symbols(event, ev_name, args->int_array.field);
276 define_event_symbols(event, ev_name, args->int_array.count);
277 define_event_symbols(event, ev_name, args->int_array.el_size);
282 define_event_symbols(event, ev_name, args->typecast.item);
285 if (strcmp(args->op.op, ":") == 0)
287 define_event_symbols(event, ev_name, args->op.left);
288 define_event_symbols(event, ev_name, args->op.right);
291 /* gcc warns for these? */
293 case PRINT_DYNAMIC_ARRAY:
294 case PRINT_DYNAMIC_ARRAY_LEN:
297 /* we should warn... */
302 define_event_symbols(event, ev_name, args->next);
305 static PyObject *get_field_numeric_entry(struct event_format *event,
306 struct format_field *field, void *data)
308 bool is_array = field->flags & FIELD_IS_ARRAY;
309 PyObject *obj = NULL, *list = NULL;
310 unsigned long long val;
311 unsigned int item_size, n_items, i;
314 list = PyList_New(field->arraylen);
315 item_size = field->size / field->arraylen;
316 n_items = field->arraylen;
318 item_size = field->size;
322 for (i = 0; i < n_items; i++) {
324 val = read_size(event, data + field->offset + i * item_size,
326 if (field->flags & FIELD_IS_SIGNED) {
327 if ((long long)val >= LONG_MIN &&
328 (long long)val <= LONG_MAX)
329 obj = PyInt_FromLong(val);
331 obj = PyLong_FromLongLong(val);
334 obj = PyInt_FromLong(val);
336 obj = PyLong_FromUnsignedLongLong(val);
339 PyList_SET_ITEM(list, i, obj);
347 static PyObject *python_process_callchain(struct perf_sample *sample,
348 struct perf_evsel *evsel,
349 struct addr_location *al)
353 pylist = PyList_New(0);
355 Py_FatalError("couldn't create Python list");
357 if (!symbol_conf.use_callchain || !sample->callchain)
360 if (thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
362 scripting_max_stack) != 0) {
363 pr_err("Failed to resolve callchain. Skipping\n");
366 callchain_cursor_commit(&callchain_cursor);
371 struct callchain_cursor_node *node;
372 node = callchain_cursor_current(&callchain_cursor);
376 pyelem = PyDict_New();
378 Py_FatalError("couldn't create Python dictionary");
381 pydict_set_item_string_decref(pyelem, "ip",
382 PyLong_FromUnsignedLongLong(node->ip));
385 PyObject *pysym = PyDict_New();
387 Py_FatalError("couldn't create Python dictionary");
388 pydict_set_item_string_decref(pysym, "start",
389 PyLong_FromUnsignedLongLong(node->sym->start));
390 pydict_set_item_string_decref(pysym, "end",
391 PyLong_FromUnsignedLongLong(node->sym->end));
392 pydict_set_item_string_decref(pysym, "binding",
393 PyInt_FromLong(node->sym->binding));
394 pydict_set_item_string_decref(pysym, "name",
395 PyString_FromStringAndSize(node->sym->name,
396 node->sym->namelen));
397 pydict_set_item_string_decref(pyelem, "sym", pysym);
401 struct map *map = node->map;
402 const char *dsoname = "[unknown]";
403 if (map && map->dso) {
404 if (symbol_conf.show_kernel_path && map->dso->long_name)
405 dsoname = map->dso->long_name;
407 dsoname = map->dso->name;
409 pydict_set_item_string_decref(pyelem, "dso",
410 PyString_FromString(dsoname));
413 callchain_cursor_advance(&callchain_cursor);
414 PyList_Append(pylist, pyelem);
422 static PyObject *get_sample_value_as_tuple(struct sample_read_value *value)
428 Py_FatalError("couldn't create Python tuple");
429 PyTuple_SetItem(t, 0, PyLong_FromUnsignedLongLong(value->id));
430 PyTuple_SetItem(t, 1, PyLong_FromUnsignedLongLong(value->value));
434 static void set_sample_read_in_dict(PyObject *dict_sample,
435 struct perf_sample *sample,
436 struct perf_evsel *evsel)
438 u64 read_format = evsel->attr.read_format;
442 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
443 pydict_set_item_string_decref(dict_sample, "time_enabled",
444 PyLong_FromUnsignedLongLong(sample->read.time_enabled));
447 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
448 pydict_set_item_string_decref(dict_sample, "time_running",
449 PyLong_FromUnsignedLongLong(sample->read.time_running));
452 if (read_format & PERF_FORMAT_GROUP)
453 values = PyList_New(sample->read.group.nr);
455 values = PyList_New(1);
458 Py_FatalError("couldn't create Python list");
460 if (read_format & PERF_FORMAT_GROUP) {
461 for (i = 0; i < sample->read.group.nr; i++) {
462 PyObject *t = get_sample_value_as_tuple(&sample->read.group.values[i]);
463 PyList_SET_ITEM(values, i, t);
466 PyObject *t = get_sample_value_as_tuple(&sample->read.one);
467 PyList_SET_ITEM(values, 0, t);
469 pydict_set_item_string_decref(dict_sample, "values", values);
472 static PyObject *get_perf_sample_dict(struct perf_sample *sample,
473 struct perf_evsel *evsel,
474 struct addr_location *al,
477 PyObject *dict, *dict_sample;
481 Py_FatalError("couldn't create Python dictionary");
483 dict_sample = PyDict_New();
485 Py_FatalError("couldn't create Python dictionary");
487 pydict_set_item_string_decref(dict, "ev_name", PyString_FromString(perf_evsel__name(evsel)));
488 pydict_set_item_string_decref(dict, "attr", PyString_FromStringAndSize(
489 (const char *)&evsel->attr, sizeof(evsel->attr)));
491 pydict_set_item_string_decref(dict_sample, "pid",
492 PyInt_FromLong(sample->pid));
493 pydict_set_item_string_decref(dict_sample, "tid",
494 PyInt_FromLong(sample->tid));
495 pydict_set_item_string_decref(dict_sample, "cpu",
496 PyInt_FromLong(sample->cpu));
497 pydict_set_item_string_decref(dict_sample, "ip",
498 PyLong_FromUnsignedLongLong(sample->ip));
499 pydict_set_item_string_decref(dict_sample, "time",
500 PyLong_FromUnsignedLongLong(sample->time));
501 pydict_set_item_string_decref(dict_sample, "period",
502 PyLong_FromUnsignedLongLong(sample->period));
503 set_sample_read_in_dict(dict_sample, sample, evsel);
504 pydict_set_item_string_decref(dict, "sample", dict_sample);
506 pydict_set_item_string_decref(dict, "raw_buf", PyString_FromStringAndSize(
507 (const char *)sample->raw_data, sample->raw_size));
508 pydict_set_item_string_decref(dict, "comm",
509 PyString_FromString(thread__comm_str(al->thread)));
511 pydict_set_item_string_decref(dict, "dso",
512 PyString_FromString(al->map->dso->name));
515 pydict_set_item_string_decref(dict, "symbol",
516 PyString_FromString(al->sym->name));
519 pydict_set_item_string_decref(dict, "callchain", callchain);
524 static void python_process_tracepoint(struct perf_sample *sample,
525 struct perf_evsel *evsel,
526 struct addr_location *al)
528 struct event_format *event = evsel->tp_format;
529 PyObject *handler, *context, *t, *obj = NULL, *callchain;
530 PyObject *dict = NULL, *all_entries_dict = NULL;
531 static char handler_name[256];
532 struct format_field *field;
536 int cpu = sample->cpu;
537 void *data = sample->raw_data;
538 unsigned long long nsecs = sample->time;
539 const char *comm = thread__comm_str(al->thread);
540 const char *default_handler_name = "trace_unhandled";
543 snprintf(handler_name, sizeof(handler_name),
544 "ug! no event found for type %" PRIu64, (u64)evsel->attr.config);
545 Py_FatalError(handler_name);
548 pid = raw_field_value(event, "common_pid", data);
550 sprintf(handler_name, "%s__%s", event->system, event->name);
552 if (!test_and_set_bit(event->id, events_defined))
553 define_event_symbols(event, handler_name, event->print_fmt.args);
555 handler = get_handler(handler_name);
557 handler = get_handler(default_handler_name);
562 Py_FatalError("couldn't create Python dict");
565 t = PyTuple_New(MAX_FIELDS);
567 Py_FatalError("couldn't create Python tuple");
570 s = nsecs / NSEC_PER_SEC;
571 ns = nsecs - s * NSEC_PER_SEC;
573 scripting_context->event_data = data;
574 scripting_context->pevent = evsel->tp_format->pevent;
576 context = PyCObject_FromVoidPtr(scripting_context, NULL);
578 PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
579 PyTuple_SetItem(t, n++, context);
582 callchain = python_process_callchain(sample, evsel, al);
583 /* Need an additional reference for the perf_sample dict */
584 Py_INCREF(callchain);
587 PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
588 PyTuple_SetItem(t, n++, PyInt_FromLong(s));
589 PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
590 PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
591 PyTuple_SetItem(t, n++, PyString_FromString(comm));
592 PyTuple_SetItem(t, n++, callchain);
594 pydict_set_item_string_decref(dict, "common_cpu", PyInt_FromLong(cpu));
595 pydict_set_item_string_decref(dict, "common_s", PyInt_FromLong(s));
596 pydict_set_item_string_decref(dict, "common_ns", PyInt_FromLong(ns));
597 pydict_set_item_string_decref(dict, "common_pid", PyInt_FromLong(pid));
598 pydict_set_item_string_decref(dict, "common_comm", PyString_FromString(comm));
599 pydict_set_item_string_decref(dict, "common_callchain", callchain);
601 for (field = event->format.fields; field; field = field->next) {
602 unsigned int offset, len;
603 unsigned long long val;
605 if (field->flags & FIELD_IS_ARRAY) {
606 offset = field->offset;
608 if (field->flags & FIELD_IS_DYNAMIC) {
609 val = pevent_read_number(scripting_context->pevent,
615 if (field->flags & FIELD_IS_STRING &&
616 is_printable_array(data + offset, len)) {
617 obj = PyString_FromString((char *) data + offset);
619 obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
620 field->flags &= ~FIELD_IS_STRING;
622 } else { /* FIELD_IS_NUMERIC */
623 obj = get_field_numeric_entry(event, field, data);
626 PyTuple_SetItem(t, n++, obj);
628 pydict_set_item_string_decref(dict, field->name, obj);
633 PyTuple_SetItem(t, n++, dict);
635 if (get_argument_count(handler) == (int) n + 1) {
636 all_entries_dict = get_perf_sample_dict(sample, evsel, al,
638 PyTuple_SetItem(t, n++, all_entries_dict);
640 Py_DECREF(callchain);
643 if (_PyTuple_Resize(&t, n) == -1)
644 Py_FatalError("error resizing Python tuple");
647 call_object(handler, t, handler_name);
649 call_object(handler, t, default_handler_name);
654 static PyObject *tuple_new(unsigned int sz)
660 Py_FatalError("couldn't create Python tuple");
664 static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
666 #if BITS_PER_LONG == 64
667 return PyTuple_SetItem(t, pos, PyInt_FromLong(val));
669 #if BITS_PER_LONG == 32
670 return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
674 static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
676 return PyTuple_SetItem(t, pos, PyInt_FromLong(val));
679 static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
681 return PyTuple_SetItem(t, pos, PyString_FromString(s));
684 static int python_export_evsel(struct db_export *dbe, struct perf_evsel *evsel)
686 struct tables *tables = container_of(dbe, struct tables, dbe);
691 tuple_set_u64(t, 0, evsel->db_id);
692 tuple_set_string(t, 1, perf_evsel__name(evsel));
694 call_object(tables->evsel_handler, t, "evsel_table");
701 static int python_export_machine(struct db_export *dbe,
702 struct machine *machine)
704 struct tables *tables = container_of(dbe, struct tables, dbe);
709 tuple_set_u64(t, 0, machine->db_id);
710 tuple_set_s32(t, 1, machine->pid);
711 tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
713 call_object(tables->machine_handler, t, "machine_table");
720 static int python_export_thread(struct db_export *dbe, struct thread *thread,
721 u64 main_thread_db_id, struct machine *machine)
723 struct tables *tables = container_of(dbe, struct tables, dbe);
728 tuple_set_u64(t, 0, thread->db_id);
729 tuple_set_u64(t, 1, machine->db_id);
730 tuple_set_u64(t, 2, main_thread_db_id);
731 tuple_set_s32(t, 3, thread->pid_);
732 tuple_set_s32(t, 4, thread->tid);
734 call_object(tables->thread_handler, t, "thread_table");
741 static int python_export_comm(struct db_export *dbe, struct comm *comm)
743 struct tables *tables = container_of(dbe, struct tables, dbe);
748 tuple_set_u64(t, 0, comm->db_id);
749 tuple_set_string(t, 1, comm__str(comm));
751 call_object(tables->comm_handler, t, "comm_table");
758 static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
759 struct comm *comm, struct thread *thread)
761 struct tables *tables = container_of(dbe, struct tables, dbe);
766 tuple_set_u64(t, 0, db_id);
767 tuple_set_u64(t, 1, comm->db_id);
768 tuple_set_u64(t, 2, thread->db_id);
770 call_object(tables->comm_thread_handler, t, "comm_thread_table");
777 static int python_export_dso(struct db_export *dbe, struct dso *dso,
778 struct machine *machine)
780 struct tables *tables = container_of(dbe, struct tables, dbe);
781 char sbuild_id[SBUILD_ID_SIZE];
784 build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);
788 tuple_set_u64(t, 0, dso->db_id);
789 tuple_set_u64(t, 1, machine->db_id);
790 tuple_set_string(t, 2, dso->short_name);
791 tuple_set_string(t, 3, dso->long_name);
792 tuple_set_string(t, 4, sbuild_id);
794 call_object(tables->dso_handler, t, "dso_table");
801 static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
804 struct tables *tables = container_of(dbe, struct tables, dbe);
805 u64 *sym_db_id = symbol__priv(sym);
810 tuple_set_u64(t, 0, *sym_db_id);
811 tuple_set_u64(t, 1, dso->db_id);
812 tuple_set_u64(t, 2, sym->start);
813 tuple_set_u64(t, 3, sym->end);
814 tuple_set_s32(t, 4, sym->binding);
815 tuple_set_string(t, 5, sym->name);
817 call_object(tables->symbol_handler, t, "symbol_table");
824 static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
827 struct tables *tables = container_of(dbe, struct tables, dbe);
832 tuple_set_s32(t, 0, branch_type);
833 tuple_set_string(t, 1, name);
835 call_object(tables->branch_type_handler, t, "branch_type_table");
842 static int python_export_sample(struct db_export *dbe,
843 struct export_sample *es)
845 struct tables *tables = container_of(dbe, struct tables, dbe);
850 tuple_set_u64(t, 0, es->db_id);
851 tuple_set_u64(t, 1, es->evsel->db_id);
852 tuple_set_u64(t, 2, es->al->machine->db_id);
853 tuple_set_u64(t, 3, es->al->thread->db_id);
854 tuple_set_u64(t, 4, es->comm_db_id);
855 tuple_set_u64(t, 5, es->dso_db_id);
856 tuple_set_u64(t, 6, es->sym_db_id);
857 tuple_set_u64(t, 7, es->offset);
858 tuple_set_u64(t, 8, es->sample->ip);
859 tuple_set_u64(t, 9, es->sample->time);
860 tuple_set_s32(t, 10, es->sample->cpu);
861 tuple_set_u64(t, 11, es->addr_dso_db_id);
862 tuple_set_u64(t, 12, es->addr_sym_db_id);
863 tuple_set_u64(t, 13, es->addr_offset);
864 tuple_set_u64(t, 14, es->sample->addr);
865 tuple_set_u64(t, 15, es->sample->period);
866 tuple_set_u64(t, 16, es->sample->weight);
867 tuple_set_u64(t, 17, es->sample->transaction);
868 tuple_set_u64(t, 18, es->sample->data_src);
869 tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
870 tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
871 tuple_set_u64(t, 21, es->call_path_id);
873 call_object(tables->sample_handler, t, "sample_table");
880 static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
882 struct tables *tables = container_of(dbe, struct tables, dbe);
884 u64 parent_db_id, sym_db_id;
886 parent_db_id = cp->parent ? cp->parent->db_id : 0;
887 sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
891 tuple_set_u64(t, 0, cp->db_id);
892 tuple_set_u64(t, 1, parent_db_id);
893 tuple_set_u64(t, 2, sym_db_id);
894 tuple_set_u64(t, 3, cp->ip);
896 call_object(tables->call_path_handler, t, "call_path_table");
903 static int python_export_call_return(struct db_export *dbe,
904 struct call_return *cr)
906 struct tables *tables = container_of(dbe, struct tables, dbe);
907 u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
912 tuple_set_u64(t, 0, cr->db_id);
913 tuple_set_u64(t, 1, cr->thread->db_id);
914 tuple_set_u64(t, 2, comm_db_id);
915 tuple_set_u64(t, 3, cr->cp->db_id);
916 tuple_set_u64(t, 4, cr->call_time);
917 tuple_set_u64(t, 5, cr->return_time);
918 tuple_set_u64(t, 6, cr->branch_count);
919 tuple_set_u64(t, 7, cr->call_ref);
920 tuple_set_u64(t, 8, cr->return_ref);
921 tuple_set_u64(t, 9, cr->cp->parent->db_id);
922 tuple_set_s32(t, 10, cr->flags);
924 call_object(tables->call_return_handler, t, "call_return_table");
931 static int python_process_call_return(struct call_return *cr, void *data)
933 struct db_export *dbe = data;
935 return db_export__call_return(dbe, cr);
938 static void python_process_general_event(struct perf_sample *sample,
939 struct perf_evsel *evsel,
940 struct addr_location *al)
942 PyObject *handler, *t, *dict, *callchain;
943 static char handler_name[64];
946 snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
948 handler = get_handler(handler_name);
953 * Use the MAX_FIELDS to make the function expandable, though
954 * currently there is only one item for the tuple.
956 t = PyTuple_New(MAX_FIELDS);
958 Py_FatalError("couldn't create Python tuple");
961 callchain = python_process_callchain(sample, evsel, al);
962 dict = get_perf_sample_dict(sample, evsel, al, callchain);
964 PyTuple_SetItem(t, n++, dict);
965 if (_PyTuple_Resize(&t, n) == -1)
966 Py_FatalError("error resizing Python tuple");
968 call_object(handler, t, handler_name);
973 static void python_process_event(union perf_event *event,
974 struct perf_sample *sample,
975 struct perf_evsel *evsel,
976 struct addr_location *al)
978 struct tables *tables = &tables_global;
980 switch (evsel->attr.type) {
981 case PERF_TYPE_TRACEPOINT:
982 python_process_tracepoint(sample, evsel, al);
984 /* Reserve for future process_hw/sw/raw APIs */
986 if (tables->db_export_mode)
987 db_export__sample(&tables->dbe, event, sample, evsel, al);
989 python_process_general_event(sample, evsel, al);
993 static void get_handler_name(char *str, size_t size,
994 struct perf_evsel *evsel)
998 scnprintf(str, size, "stat__%s", perf_evsel__name(evsel));
1000 while ((p = strchr(p, ':'))) {
1007 process_stat(struct perf_evsel *counter, int cpu, int thread, u64 tstamp,
1008 struct perf_counts_values *count)
1010 PyObject *handler, *t;
1011 static char handler_name[256];
1014 t = PyTuple_New(MAX_FIELDS);
1016 Py_FatalError("couldn't create Python tuple");
1018 get_handler_name(handler_name, sizeof(handler_name),
1021 handler = get_handler(handler_name);
1023 pr_debug("can't find python handler %s\n", handler_name);
1027 PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
1028 PyTuple_SetItem(t, n++, PyInt_FromLong(thread));
1030 tuple_set_u64(t, n++, tstamp);
1031 tuple_set_u64(t, n++, count->val);
1032 tuple_set_u64(t, n++, count->ena);
1033 tuple_set_u64(t, n++, count->run);
1035 if (_PyTuple_Resize(&t, n) == -1)
1036 Py_FatalError("error resizing Python tuple");
1038 call_object(handler, t, handler_name);
1043 static void python_process_stat(struct perf_stat_config *config,
1044 struct perf_evsel *counter, u64 tstamp)
1046 struct thread_map *threads = counter->threads;
1047 struct cpu_map *cpus = counter->cpus;
1050 if (config->aggr_mode == AGGR_GLOBAL) {
1051 process_stat(counter, -1, -1, tstamp,
1052 &counter->counts->aggr);
1056 for (thread = 0; thread < threads->nr; thread++) {
1057 for (cpu = 0; cpu < cpus->nr; cpu++) {
1058 process_stat(counter, cpus->map[cpu],
1059 thread_map__pid(threads, thread), tstamp,
1060 perf_counts(counter->counts, cpu, thread));
1065 static void python_process_stat_interval(u64 tstamp)
1067 PyObject *handler, *t;
1068 static const char handler_name[] = "stat__interval";
1071 t = PyTuple_New(MAX_FIELDS);
1073 Py_FatalError("couldn't create Python tuple");
1075 handler = get_handler(handler_name);
1077 pr_debug("can't find python handler %s\n", handler_name);
1081 tuple_set_u64(t, n++, tstamp);
1083 if (_PyTuple_Resize(&t, n) == -1)
1084 Py_FatalError("error resizing Python tuple");
1086 call_object(handler, t, handler_name);
1091 static int run_start_sub(void)
1093 main_module = PyImport_AddModule("__main__");
1094 if (main_module == NULL)
1096 Py_INCREF(main_module);
1098 main_dict = PyModule_GetDict(main_module);
1099 if (main_dict == NULL)
1101 Py_INCREF(main_dict);
1103 try_call_object("trace_begin", NULL);
1108 Py_XDECREF(main_dict);
1109 Py_XDECREF(main_module);
1113 #define SET_TABLE_HANDLER_(name, handler_name, table_name) do { \
1114 tables->handler_name = get_handler(#table_name); \
1115 if (tables->handler_name) \
1116 tables->dbe.export_ ## name = python_export_ ## name; \
1119 #define SET_TABLE_HANDLER(name) \
1120 SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
1122 static void set_table_handlers(struct tables *tables)
1124 const char *perf_db_export_mode = "perf_db_export_mode";
1125 const char *perf_db_export_calls = "perf_db_export_calls";
1126 const char *perf_db_export_callchains = "perf_db_export_callchains";
1127 PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
1128 bool export_calls = false;
1129 bool export_callchains = false;
1132 memset(tables, 0, sizeof(struct tables));
1133 if (db_export__init(&tables->dbe))
1134 Py_FatalError("failed to initialize export");
1136 db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
1137 if (!db_export_mode)
1140 ret = PyObject_IsTrue(db_export_mode);
1142 handler_call_die(perf_db_export_mode);
1146 /* handle export calls */
1147 tables->dbe.crp = NULL;
1148 db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
1149 if (db_export_calls) {
1150 ret = PyObject_IsTrue(db_export_calls);
1152 handler_call_die(perf_db_export_calls);
1153 export_calls = !!ret;
1158 call_return_processor__new(python_process_call_return,
1160 if (!tables->dbe.crp)
1161 Py_FatalError("failed to create calls processor");
1164 /* handle export callchains */
1165 tables->dbe.cpr = NULL;
1166 db_export_callchains = PyDict_GetItemString(main_dict,
1167 perf_db_export_callchains);
1168 if (db_export_callchains) {
1169 ret = PyObject_IsTrue(db_export_callchains);
1171 handler_call_die(perf_db_export_callchains);
1172 export_callchains = !!ret;
1175 if (export_callchains) {
1177 * Attempt to use the call path root from the call return
1178 * processor, if the call return processor is in use. Otherwise,
1179 * we allocate a new call path root. This prevents exporting
1180 * duplicate call path ids when both are in use simultaniously.
1182 if (tables->dbe.crp)
1183 tables->dbe.cpr = tables->dbe.crp->cpr;
1185 tables->dbe.cpr = call_path_root__new();
1187 if (!tables->dbe.cpr)
1188 Py_FatalError("failed to create call path root");
1191 tables->db_export_mode = true;
1193 * Reserve per symbol space for symbol->db_id via symbol__priv()
1195 symbol_conf.priv_size = sizeof(u64);
1197 SET_TABLE_HANDLER(evsel);
1198 SET_TABLE_HANDLER(machine);
1199 SET_TABLE_HANDLER(thread);
1200 SET_TABLE_HANDLER(comm);
1201 SET_TABLE_HANDLER(comm_thread);
1202 SET_TABLE_HANDLER(dso);
1203 SET_TABLE_HANDLER(symbol);
1204 SET_TABLE_HANDLER(branch_type);
1205 SET_TABLE_HANDLER(sample);
1206 SET_TABLE_HANDLER(call_path);
1207 SET_TABLE_HANDLER(call_return);
1211 * Start trace script
1213 static int python_start_script(const char *script, int argc, const char **argv)
1215 struct tables *tables = &tables_global;
1216 const char **command_line;
1221 command_line = malloc((argc + 1) * sizeof(const char *));
1222 command_line[0] = script;
1223 for (i = 1; i < argc + 1; i++)
1224 command_line[i] = argv[i - 1];
1228 initperf_trace_context();
1230 PySys_SetArgv(argc + 1, (char **)command_line);
1232 fp = fopen(script, "r");
1234 sprintf(buf, "Can't open python script \"%s\"", script);
1240 err = PyRun_SimpleFile(fp, script);
1242 fprintf(stderr, "Error running python script %s\n", script);
1246 err = run_start_sub();
1248 fprintf(stderr, "Error starting python script %s\n", script);
1252 set_table_handlers(tables);
1254 if (tables->db_export_mode) {
1255 err = db_export__branch_types(&tables->dbe);
1270 static int python_flush_script(void)
1272 struct tables *tables = &tables_global;
1274 return db_export__flush(&tables->dbe);
1280 static int python_stop_script(void)
1282 struct tables *tables = &tables_global;
1284 try_call_object("trace_end", NULL);
1286 db_export__exit(&tables->dbe);
1288 Py_XDECREF(main_dict);
1289 Py_XDECREF(main_module);
1295 static int python_generate_script(struct pevent *pevent, const char *outfile)
1297 struct event_format *event = NULL;
1298 struct format_field *f;
1299 char fname[PATH_MAX];
1300 int not_first, count;
1303 sprintf(fname, "%s.py", outfile);
1304 ofp = fopen(fname, "w");
1306 fprintf(stderr, "couldn't open %s\n", fname);
1309 fprintf(ofp, "# perf script event handlers, "
1310 "generated by perf script -g python\n");
1312 fprintf(ofp, "# Licensed under the terms of the GNU GPL"
1313 " License version 2\n\n");
1315 fprintf(ofp, "# The common_* event handler fields are the most useful "
1316 "fields common to\n");
1318 fprintf(ofp, "# all events. They don't necessarily correspond to "
1319 "the 'common_*' fields\n");
1321 fprintf(ofp, "# in the format files. Those fields not available as "
1322 "handler params can\n");
1324 fprintf(ofp, "# be retrieved using Python functions of the form "
1325 "common_*(context).\n");
1327 fprintf(ofp, "# See the perf-script-python Documentation for the list "
1328 "of available functions.\n\n");
1330 fprintf(ofp, "import os\n");
1331 fprintf(ofp, "import sys\n\n");
1333 fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
1334 fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
1335 fprintf(ofp, "\nfrom perf_trace_context import *\n");
1336 fprintf(ofp, "from Core import *\n\n\n");
1338 fprintf(ofp, "def trace_begin():\n");
1339 fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
1341 fprintf(ofp, "def trace_end():\n");
1342 fprintf(ofp, "\tprint \"in trace_end\"\n\n");
1344 while ((event = trace_find_next_event(pevent, event))) {
1345 fprintf(ofp, "def %s__%s(", event->system, event->name);
1346 fprintf(ofp, "event_name, ");
1347 fprintf(ofp, "context, ");
1348 fprintf(ofp, "common_cpu,\n");
1349 fprintf(ofp, "\tcommon_secs, ");
1350 fprintf(ofp, "common_nsecs, ");
1351 fprintf(ofp, "common_pid, ");
1352 fprintf(ofp, "common_comm,\n\t");
1353 fprintf(ofp, "common_callchain, ");
1358 for (f = event->format.fields; f; f = f->next) {
1361 if (++count % 5 == 0)
1362 fprintf(ofp, "\n\t");
1364 fprintf(ofp, "%s", f->name);
1368 if (++count % 5 == 0)
1369 fprintf(ofp, "\n\t\t");
1370 fprintf(ofp, "perf_sample_dict");
1372 fprintf(ofp, "):\n");
1374 fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
1375 "common_secs, common_nsecs,\n\t\t\t"
1376 "common_pid, common_comm)\n\n");
1378 fprintf(ofp, "\t\tprint \"");
1383 for (f = event->format.fields; f; f = f->next) {
1386 if (count && count % 3 == 0) {
1387 fprintf(ofp, "\" \\\n\t\t\"");
1391 fprintf(ofp, "%s=", f->name);
1392 if (f->flags & FIELD_IS_STRING ||
1393 f->flags & FIELD_IS_FLAG ||
1394 f->flags & FIELD_IS_ARRAY ||
1395 f->flags & FIELD_IS_SYMBOLIC)
1396 fprintf(ofp, "%%s");
1397 else if (f->flags & FIELD_IS_SIGNED)
1398 fprintf(ofp, "%%d");
1400 fprintf(ofp, "%%u");
1403 fprintf(ofp, "\" %% \\\n\t\t(");
1408 for (f = event->format.fields; f; f = f->next) {
1412 if (++count % 5 == 0)
1413 fprintf(ofp, "\n\t\t");
1415 if (f->flags & FIELD_IS_FLAG) {
1416 if ((count - 1) % 5 != 0) {
1417 fprintf(ofp, "\n\t\t");
1420 fprintf(ofp, "flag_str(\"");
1421 fprintf(ofp, "%s__%s\", ", event->system,
1423 fprintf(ofp, "\"%s\", %s)", f->name,
1425 } else if (f->flags & FIELD_IS_SYMBOLIC) {
1426 if ((count - 1) % 5 != 0) {
1427 fprintf(ofp, "\n\t\t");
1430 fprintf(ofp, "symbol_str(\"");
1431 fprintf(ofp, "%s__%s\", ", event->system,
1433 fprintf(ofp, "\"%s\", %s)", f->name,
1436 fprintf(ofp, "%s", f->name);
1439 fprintf(ofp, ")\n\n");
1441 fprintf(ofp, "\t\tprint 'Sample: {'+"
1442 "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}'\n\n");
1444 fprintf(ofp, "\t\tfor node in common_callchain:");
1445 fprintf(ofp, "\n\t\t\tif 'sym' in node:");
1446 fprintf(ofp, "\n\t\t\t\tprint \"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name'])");
1447 fprintf(ofp, "\n\t\t\telse:");
1448 fprintf(ofp, "\n\t\t\t\tprint \"\t[%%x]\" %% (node['ip'])\n\n");
1449 fprintf(ofp, "\t\tprint \"\\n\"\n\n");
1453 fprintf(ofp, "def trace_unhandled(event_name, context, "
1454 "event_fields_dict, perf_sample_dict):\n");
1456 fprintf(ofp, "\t\tprint get_dict_as_string(event_fields_dict)\n");
1457 fprintf(ofp, "\t\tprint 'Sample: {'+"
1458 "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}'\n\n");
1460 fprintf(ofp, "def print_header("
1461 "event_name, cpu, secs, nsecs, pid, comm):\n"
1462 "\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
1463 "(event_name, cpu, secs, nsecs, pid, comm),\n\n");
1465 fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
1466 "\treturn delimiter.join"
1467 "(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
1471 fprintf(stderr, "generated Python script: %s\n", fname);
1476 struct scripting_ops python_scripting_ops = {
1478 .start_script = python_start_script,
1479 .flush_script = python_flush_script,
1480 .stop_script = python_stop_script,
1481 .process_event = python_process_event,
1482 .process_stat = python_process_stat,
1483 .process_stat_interval = python_process_stat_interval,
1484 .generate_script = python_generate_script,