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
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);
653 Py_XDECREF(all_entries_dict);
657 static PyObject *tuple_new(unsigned int sz)
663 Py_FatalError("couldn't create Python tuple");
667 static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
669 #if BITS_PER_LONG == 64
670 return PyTuple_SetItem(t, pos, PyInt_FromLong(val));
672 #if BITS_PER_LONG == 32
673 return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
677 static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
679 return PyTuple_SetItem(t, pos, PyInt_FromLong(val));
682 static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
684 return PyTuple_SetItem(t, pos, PyString_FromString(s));
687 static int python_export_evsel(struct db_export *dbe, struct perf_evsel *evsel)
689 struct tables *tables = container_of(dbe, struct tables, dbe);
694 tuple_set_u64(t, 0, evsel->db_id);
695 tuple_set_string(t, 1, perf_evsel__name(evsel));
697 call_object(tables->evsel_handler, t, "evsel_table");
704 static int python_export_machine(struct db_export *dbe,
705 struct machine *machine)
707 struct tables *tables = container_of(dbe, struct tables, dbe);
712 tuple_set_u64(t, 0, machine->db_id);
713 tuple_set_s32(t, 1, machine->pid);
714 tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
716 call_object(tables->machine_handler, t, "machine_table");
723 static int python_export_thread(struct db_export *dbe, struct thread *thread,
724 u64 main_thread_db_id, struct machine *machine)
726 struct tables *tables = container_of(dbe, struct tables, dbe);
731 tuple_set_u64(t, 0, thread->db_id);
732 tuple_set_u64(t, 1, machine->db_id);
733 tuple_set_u64(t, 2, main_thread_db_id);
734 tuple_set_s32(t, 3, thread->pid_);
735 tuple_set_s32(t, 4, thread->tid);
737 call_object(tables->thread_handler, t, "thread_table");
744 static int python_export_comm(struct db_export *dbe, struct comm *comm)
746 struct tables *tables = container_of(dbe, struct tables, dbe);
751 tuple_set_u64(t, 0, comm->db_id);
752 tuple_set_string(t, 1, comm__str(comm));
754 call_object(tables->comm_handler, t, "comm_table");
761 static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
762 struct comm *comm, struct thread *thread)
764 struct tables *tables = container_of(dbe, struct tables, dbe);
769 tuple_set_u64(t, 0, db_id);
770 tuple_set_u64(t, 1, comm->db_id);
771 tuple_set_u64(t, 2, thread->db_id);
773 call_object(tables->comm_thread_handler, t, "comm_thread_table");
780 static int python_export_dso(struct db_export *dbe, struct dso *dso,
781 struct machine *machine)
783 struct tables *tables = container_of(dbe, struct tables, dbe);
784 char sbuild_id[SBUILD_ID_SIZE];
787 build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);
791 tuple_set_u64(t, 0, dso->db_id);
792 tuple_set_u64(t, 1, machine->db_id);
793 tuple_set_string(t, 2, dso->short_name);
794 tuple_set_string(t, 3, dso->long_name);
795 tuple_set_string(t, 4, sbuild_id);
797 call_object(tables->dso_handler, t, "dso_table");
804 static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
807 struct tables *tables = container_of(dbe, struct tables, dbe);
808 u64 *sym_db_id = symbol__priv(sym);
813 tuple_set_u64(t, 0, *sym_db_id);
814 tuple_set_u64(t, 1, dso->db_id);
815 tuple_set_u64(t, 2, sym->start);
816 tuple_set_u64(t, 3, sym->end);
817 tuple_set_s32(t, 4, sym->binding);
818 tuple_set_string(t, 5, sym->name);
820 call_object(tables->symbol_handler, t, "symbol_table");
827 static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
830 struct tables *tables = container_of(dbe, struct tables, dbe);
835 tuple_set_s32(t, 0, branch_type);
836 tuple_set_string(t, 1, name);
838 call_object(tables->branch_type_handler, t, "branch_type_table");
845 static int python_export_sample(struct db_export *dbe,
846 struct export_sample *es)
848 struct tables *tables = container_of(dbe, struct tables, dbe);
853 tuple_set_u64(t, 0, es->db_id);
854 tuple_set_u64(t, 1, es->evsel->db_id);
855 tuple_set_u64(t, 2, es->al->machine->db_id);
856 tuple_set_u64(t, 3, es->al->thread->db_id);
857 tuple_set_u64(t, 4, es->comm_db_id);
858 tuple_set_u64(t, 5, es->dso_db_id);
859 tuple_set_u64(t, 6, es->sym_db_id);
860 tuple_set_u64(t, 7, es->offset);
861 tuple_set_u64(t, 8, es->sample->ip);
862 tuple_set_u64(t, 9, es->sample->time);
863 tuple_set_s32(t, 10, es->sample->cpu);
864 tuple_set_u64(t, 11, es->addr_dso_db_id);
865 tuple_set_u64(t, 12, es->addr_sym_db_id);
866 tuple_set_u64(t, 13, es->addr_offset);
867 tuple_set_u64(t, 14, es->sample->addr);
868 tuple_set_u64(t, 15, es->sample->period);
869 tuple_set_u64(t, 16, es->sample->weight);
870 tuple_set_u64(t, 17, es->sample->transaction);
871 tuple_set_u64(t, 18, es->sample->data_src);
872 tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
873 tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
874 tuple_set_u64(t, 21, es->call_path_id);
876 call_object(tables->sample_handler, t, "sample_table");
883 static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
885 struct tables *tables = container_of(dbe, struct tables, dbe);
887 u64 parent_db_id, sym_db_id;
889 parent_db_id = cp->parent ? cp->parent->db_id : 0;
890 sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
894 tuple_set_u64(t, 0, cp->db_id);
895 tuple_set_u64(t, 1, parent_db_id);
896 tuple_set_u64(t, 2, sym_db_id);
897 tuple_set_u64(t, 3, cp->ip);
899 call_object(tables->call_path_handler, t, "call_path_table");
906 static int python_export_call_return(struct db_export *dbe,
907 struct call_return *cr)
909 struct tables *tables = container_of(dbe, struct tables, dbe);
910 u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
915 tuple_set_u64(t, 0, cr->db_id);
916 tuple_set_u64(t, 1, cr->thread->db_id);
917 tuple_set_u64(t, 2, comm_db_id);
918 tuple_set_u64(t, 3, cr->cp->db_id);
919 tuple_set_u64(t, 4, cr->call_time);
920 tuple_set_u64(t, 5, cr->return_time);
921 tuple_set_u64(t, 6, cr->branch_count);
922 tuple_set_u64(t, 7, cr->call_ref);
923 tuple_set_u64(t, 8, cr->return_ref);
924 tuple_set_u64(t, 9, cr->cp->parent->db_id);
925 tuple_set_s32(t, 10, cr->flags);
927 call_object(tables->call_return_handler, t, "call_return_table");
934 static int python_process_call_return(struct call_return *cr, void *data)
936 struct db_export *dbe = data;
938 return db_export__call_return(dbe, cr);
941 static void python_process_general_event(struct perf_sample *sample,
942 struct perf_evsel *evsel,
943 struct addr_location *al)
945 PyObject *handler, *t, *dict, *callchain;
946 static char handler_name[64];
949 snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
951 handler = get_handler(handler_name);
956 * Use the MAX_FIELDS to make the function expandable, though
957 * currently there is only one item for the tuple.
959 t = PyTuple_New(MAX_FIELDS);
961 Py_FatalError("couldn't create Python tuple");
964 callchain = python_process_callchain(sample, evsel, al);
965 dict = get_perf_sample_dict(sample, evsel, al, callchain);
967 PyTuple_SetItem(t, n++, dict);
968 if (_PyTuple_Resize(&t, n) == -1)
969 Py_FatalError("error resizing Python tuple");
971 call_object(handler, t, handler_name);
977 static void python_process_event(union perf_event *event,
978 struct perf_sample *sample,
979 struct perf_evsel *evsel,
980 struct addr_location *al)
982 struct tables *tables = &tables_global;
984 switch (evsel->attr.type) {
985 case PERF_TYPE_TRACEPOINT:
986 python_process_tracepoint(sample, evsel, al);
988 /* Reserve for future process_hw/sw/raw APIs */
990 if (tables->db_export_mode)
991 db_export__sample(&tables->dbe, event, sample, evsel, al);
993 python_process_general_event(sample, evsel, al);
997 static void get_handler_name(char *str, size_t size,
998 struct perf_evsel *evsel)
1002 scnprintf(str, size, "stat__%s", perf_evsel__name(evsel));
1004 while ((p = strchr(p, ':'))) {
1011 process_stat(struct perf_evsel *counter, int cpu, int thread, u64 tstamp,
1012 struct perf_counts_values *count)
1014 PyObject *handler, *t;
1015 static char handler_name[256];
1018 t = PyTuple_New(MAX_FIELDS);
1020 Py_FatalError("couldn't create Python tuple");
1022 get_handler_name(handler_name, sizeof(handler_name),
1025 handler = get_handler(handler_name);
1027 pr_debug("can't find python handler %s\n", handler_name);
1031 PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
1032 PyTuple_SetItem(t, n++, PyInt_FromLong(thread));
1034 tuple_set_u64(t, n++, tstamp);
1035 tuple_set_u64(t, n++, count->val);
1036 tuple_set_u64(t, n++, count->ena);
1037 tuple_set_u64(t, n++, count->run);
1039 if (_PyTuple_Resize(&t, n) == -1)
1040 Py_FatalError("error resizing Python tuple");
1042 call_object(handler, t, handler_name);
1047 static void python_process_stat(struct perf_stat_config *config,
1048 struct perf_evsel *counter, u64 tstamp)
1050 struct thread_map *threads = counter->threads;
1051 struct cpu_map *cpus = counter->cpus;
1054 if (config->aggr_mode == AGGR_GLOBAL) {
1055 process_stat(counter, -1, -1, tstamp,
1056 &counter->counts->aggr);
1060 for (thread = 0; thread < threads->nr; thread++) {
1061 for (cpu = 0; cpu < cpus->nr; cpu++) {
1062 process_stat(counter, cpus->map[cpu],
1063 thread_map__pid(threads, thread), tstamp,
1064 perf_counts(counter->counts, cpu, thread));
1069 static void python_process_stat_interval(u64 tstamp)
1071 PyObject *handler, *t;
1072 static const char handler_name[] = "stat__interval";
1075 t = PyTuple_New(MAX_FIELDS);
1077 Py_FatalError("couldn't create Python tuple");
1079 handler = get_handler(handler_name);
1081 pr_debug("can't find python handler %s\n", handler_name);
1085 tuple_set_u64(t, n++, tstamp);
1087 if (_PyTuple_Resize(&t, n) == -1)
1088 Py_FatalError("error resizing Python tuple");
1090 call_object(handler, t, handler_name);
1095 static int run_start_sub(void)
1097 main_module = PyImport_AddModule("__main__");
1098 if (main_module == NULL)
1100 Py_INCREF(main_module);
1102 main_dict = PyModule_GetDict(main_module);
1103 if (main_dict == NULL)
1105 Py_INCREF(main_dict);
1107 try_call_object("trace_begin", NULL);
1112 Py_XDECREF(main_dict);
1113 Py_XDECREF(main_module);
1117 #define SET_TABLE_HANDLER_(name, handler_name, table_name) do { \
1118 tables->handler_name = get_handler(#table_name); \
1119 if (tables->handler_name) \
1120 tables->dbe.export_ ## name = python_export_ ## name; \
1123 #define SET_TABLE_HANDLER(name) \
1124 SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
1126 static void set_table_handlers(struct tables *tables)
1128 const char *perf_db_export_mode = "perf_db_export_mode";
1129 const char *perf_db_export_calls = "perf_db_export_calls";
1130 const char *perf_db_export_callchains = "perf_db_export_callchains";
1131 PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
1132 bool export_calls = false;
1133 bool export_callchains = false;
1136 memset(tables, 0, sizeof(struct tables));
1137 if (db_export__init(&tables->dbe))
1138 Py_FatalError("failed to initialize export");
1140 db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
1141 if (!db_export_mode)
1144 ret = PyObject_IsTrue(db_export_mode);
1146 handler_call_die(perf_db_export_mode);
1150 /* handle export calls */
1151 tables->dbe.crp = NULL;
1152 db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
1153 if (db_export_calls) {
1154 ret = PyObject_IsTrue(db_export_calls);
1156 handler_call_die(perf_db_export_calls);
1157 export_calls = !!ret;
1162 call_return_processor__new(python_process_call_return,
1164 if (!tables->dbe.crp)
1165 Py_FatalError("failed to create calls processor");
1168 /* handle export callchains */
1169 tables->dbe.cpr = NULL;
1170 db_export_callchains = PyDict_GetItemString(main_dict,
1171 perf_db_export_callchains);
1172 if (db_export_callchains) {
1173 ret = PyObject_IsTrue(db_export_callchains);
1175 handler_call_die(perf_db_export_callchains);
1176 export_callchains = !!ret;
1179 if (export_callchains) {
1181 * Attempt to use the call path root from the call return
1182 * processor, if the call return processor is in use. Otherwise,
1183 * we allocate a new call path root. This prevents exporting
1184 * duplicate call path ids when both are in use simultaniously.
1186 if (tables->dbe.crp)
1187 tables->dbe.cpr = tables->dbe.crp->cpr;
1189 tables->dbe.cpr = call_path_root__new();
1191 if (!tables->dbe.cpr)
1192 Py_FatalError("failed to create call path root");
1195 tables->db_export_mode = true;
1197 * Reserve per symbol space for symbol->db_id via symbol__priv()
1199 symbol_conf.priv_size = sizeof(u64);
1201 SET_TABLE_HANDLER(evsel);
1202 SET_TABLE_HANDLER(machine);
1203 SET_TABLE_HANDLER(thread);
1204 SET_TABLE_HANDLER(comm);
1205 SET_TABLE_HANDLER(comm_thread);
1206 SET_TABLE_HANDLER(dso);
1207 SET_TABLE_HANDLER(symbol);
1208 SET_TABLE_HANDLER(branch_type);
1209 SET_TABLE_HANDLER(sample);
1210 SET_TABLE_HANDLER(call_path);
1211 SET_TABLE_HANDLER(call_return);
1215 * Start trace script
1217 static int python_start_script(const char *script, int argc, const char **argv)
1219 struct tables *tables = &tables_global;
1220 const char **command_line;
1225 command_line = malloc((argc + 1) * sizeof(const char *));
1226 command_line[0] = script;
1227 for (i = 1; i < argc + 1; i++)
1228 command_line[i] = argv[i - 1];
1232 initperf_trace_context();
1234 PySys_SetArgv(argc + 1, (char **)command_line);
1236 fp = fopen(script, "r");
1238 sprintf(buf, "Can't open python script \"%s\"", script);
1244 err = PyRun_SimpleFile(fp, script);
1246 fprintf(stderr, "Error running python script %s\n", script);
1250 err = run_start_sub();
1252 fprintf(stderr, "Error starting python script %s\n", script);
1256 set_table_handlers(tables);
1258 if (tables->db_export_mode) {
1259 err = db_export__branch_types(&tables->dbe);
1274 static int python_flush_script(void)
1276 struct tables *tables = &tables_global;
1278 return db_export__flush(&tables->dbe);
1284 static int python_stop_script(void)
1286 struct tables *tables = &tables_global;
1288 try_call_object("trace_end", NULL);
1290 db_export__exit(&tables->dbe);
1292 Py_XDECREF(main_dict);
1293 Py_XDECREF(main_module);
1299 static int python_generate_script(struct pevent *pevent, const char *outfile)
1301 struct event_format *event = NULL;
1302 struct format_field *f;
1303 char fname[PATH_MAX];
1304 int not_first, count;
1307 sprintf(fname, "%s.py", outfile);
1308 ofp = fopen(fname, "w");
1310 fprintf(stderr, "couldn't open %s\n", fname);
1313 fprintf(ofp, "# perf script event handlers, "
1314 "generated by perf script -g python\n");
1316 fprintf(ofp, "# Licensed under the terms of the GNU GPL"
1317 " License version 2\n\n");
1319 fprintf(ofp, "# The common_* event handler fields are the most useful "
1320 "fields common to\n");
1322 fprintf(ofp, "# all events. They don't necessarily correspond to "
1323 "the 'common_*' fields\n");
1325 fprintf(ofp, "# in the format files. Those fields not available as "
1326 "handler params can\n");
1328 fprintf(ofp, "# be retrieved using Python functions of the form "
1329 "common_*(context).\n");
1331 fprintf(ofp, "# See the perf-script-python Documentation for the list "
1332 "of available functions.\n\n");
1334 fprintf(ofp, "import os\n");
1335 fprintf(ofp, "import sys\n\n");
1337 fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
1338 fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
1339 fprintf(ofp, "\nfrom perf_trace_context import *\n");
1340 fprintf(ofp, "from Core import *\n\n\n");
1342 fprintf(ofp, "def trace_begin():\n");
1343 fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
1345 fprintf(ofp, "def trace_end():\n");
1346 fprintf(ofp, "\tprint \"in trace_end\"\n\n");
1348 while ((event = trace_find_next_event(pevent, event))) {
1349 fprintf(ofp, "def %s__%s(", event->system, event->name);
1350 fprintf(ofp, "event_name, ");
1351 fprintf(ofp, "context, ");
1352 fprintf(ofp, "common_cpu,\n");
1353 fprintf(ofp, "\tcommon_secs, ");
1354 fprintf(ofp, "common_nsecs, ");
1355 fprintf(ofp, "common_pid, ");
1356 fprintf(ofp, "common_comm,\n\t");
1357 fprintf(ofp, "common_callchain, ");
1362 for (f = event->format.fields; f; f = f->next) {
1365 if (++count % 5 == 0)
1366 fprintf(ofp, "\n\t");
1368 fprintf(ofp, "%s", f->name);
1372 if (++count % 5 == 0)
1373 fprintf(ofp, "\n\t\t");
1374 fprintf(ofp, "perf_sample_dict");
1376 fprintf(ofp, "):\n");
1378 fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
1379 "common_secs, common_nsecs,\n\t\t\t"
1380 "common_pid, common_comm)\n\n");
1382 fprintf(ofp, "\t\tprint \"");
1387 for (f = event->format.fields; f; f = f->next) {
1390 if (count && count % 3 == 0) {
1391 fprintf(ofp, "\" \\\n\t\t\"");
1395 fprintf(ofp, "%s=", f->name);
1396 if (f->flags & FIELD_IS_STRING ||
1397 f->flags & FIELD_IS_FLAG ||
1398 f->flags & FIELD_IS_ARRAY ||
1399 f->flags & FIELD_IS_SYMBOLIC)
1400 fprintf(ofp, "%%s");
1401 else if (f->flags & FIELD_IS_SIGNED)
1402 fprintf(ofp, "%%d");
1404 fprintf(ofp, "%%u");
1407 fprintf(ofp, "\" %% \\\n\t\t(");
1412 for (f = event->format.fields; f; f = f->next) {
1416 if (++count % 5 == 0)
1417 fprintf(ofp, "\n\t\t");
1419 if (f->flags & FIELD_IS_FLAG) {
1420 if ((count - 1) % 5 != 0) {
1421 fprintf(ofp, "\n\t\t");
1424 fprintf(ofp, "flag_str(\"");
1425 fprintf(ofp, "%s__%s\", ", event->system,
1427 fprintf(ofp, "\"%s\", %s)", f->name,
1429 } else if (f->flags & FIELD_IS_SYMBOLIC) {
1430 if ((count - 1) % 5 != 0) {
1431 fprintf(ofp, "\n\t\t");
1434 fprintf(ofp, "symbol_str(\"");
1435 fprintf(ofp, "%s__%s\", ", event->system,
1437 fprintf(ofp, "\"%s\", %s)", f->name,
1440 fprintf(ofp, "%s", f->name);
1443 fprintf(ofp, ")\n\n");
1445 fprintf(ofp, "\t\tprint 'Sample: {'+"
1446 "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}'\n\n");
1448 fprintf(ofp, "\t\tfor node in common_callchain:");
1449 fprintf(ofp, "\n\t\t\tif 'sym' in node:");
1450 fprintf(ofp, "\n\t\t\t\tprint \"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name'])");
1451 fprintf(ofp, "\n\t\t\telse:");
1452 fprintf(ofp, "\n\t\t\t\tprint \"\t[%%x]\" %% (node['ip'])\n\n");
1453 fprintf(ofp, "\t\tprint \"\\n\"\n\n");
1457 fprintf(ofp, "def trace_unhandled(event_name, context, "
1458 "event_fields_dict, perf_sample_dict):\n");
1460 fprintf(ofp, "\t\tprint get_dict_as_string(event_fields_dict)\n");
1461 fprintf(ofp, "\t\tprint 'Sample: {'+"
1462 "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}'\n\n");
1464 fprintf(ofp, "def print_header("
1465 "event_name, cpu, secs, nsecs, pid, comm):\n"
1466 "\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
1467 "(event_name, cpu, secs, nsecs, pid, comm),\n\n");
1469 fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
1470 "\treturn delimiter.join"
1471 "(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
1475 fprintf(stderr, "generated Python script: %s\n", fname);
1480 struct scripting_ops python_scripting_ops = {
1482 .start_script = python_start_script,
1483 .flush_script = python_flush_script,
1484 .stop_script = python_stop_script,
1485 .process_event = python_process_event,
1486 .process_stat = python_process_stat,
1487 .process_stat_interval = python_process_stat_interval,
1488 .generate_script = python_generate_script,