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>
33 #ifdef HAVE_LIBTRACEEVENT
34 #include <traceevent/event-parse.h>
37 #include "../build-id.h"
38 #include "../counts.h"
41 #include "../callchain.h"
45 #include "../thread.h"
47 #include "../machine.h"
48 #include "../db-export.h"
49 #include "../thread-stack.h"
50 #include "../trace-event.h"
51 #include "../call-path.h"
54 #include "thread_map.h"
55 #include "print_binary.h"
57 #include "mem-events.h"
58 #include "util/perf_regs.h"
60 #if PY_MAJOR_VERSION < 3
61 #define _PyUnicode_FromString(arg) \
62 PyString_FromString(arg)
63 #define _PyUnicode_FromStringAndSize(arg1, arg2) \
64 PyString_FromStringAndSize((arg1), (arg2))
65 #define _PyBytes_FromStringAndSize(arg1, arg2) \
66 PyString_FromStringAndSize((arg1), (arg2))
67 #define _PyLong_FromLong(arg) \
69 #define _PyLong_AsLong(arg) \
71 #define _PyCapsule_New(arg1, arg2, arg3) \
72 PyCObject_FromVoidPtr((arg1), (arg2))
74 PyMODINIT_FUNC initperf_trace_context(void);
76 #define _PyUnicode_FromString(arg) \
77 PyUnicode_FromString(arg)
78 #define _PyUnicode_FromStringAndSize(arg1, arg2) \
79 PyUnicode_FromStringAndSize((arg1), (arg2))
80 #define _PyBytes_FromStringAndSize(arg1, arg2) \
81 PyBytes_FromStringAndSize((arg1), (arg2))
82 #define _PyLong_FromLong(arg) \
84 #define _PyLong_AsLong(arg) \
86 #define _PyCapsule_New(arg1, arg2, arg3) \
87 PyCapsule_New((arg1), (arg2), (arg3))
89 PyMODINIT_FUNC PyInit_perf_trace_context(void);
92 #ifdef HAVE_LIBTRACEEVENT
93 #define TRACE_EVENT_TYPE_MAX \
94 ((1 << (sizeof(unsigned short) * 8)) - 1)
96 static DECLARE_BITMAP(events_defined, TRACE_EVENT_TYPE_MAX);
98 #define N_COMMON_FIELDS 7
100 static char *cur_field_name;
101 static int zero_flag_atom;
104 #define MAX_FIELDS 64
106 extern struct scripting_context *scripting_context;
108 static PyObject *main_module, *main_dict;
111 struct db_export dbe;
112 PyObject *evsel_handler;
113 PyObject *machine_handler;
114 PyObject *thread_handler;
115 PyObject *comm_handler;
116 PyObject *comm_thread_handler;
117 PyObject *dso_handler;
118 PyObject *symbol_handler;
119 PyObject *branch_type_handler;
120 PyObject *sample_handler;
121 PyObject *call_path_handler;
122 PyObject *call_return_handler;
123 PyObject *synth_handler;
124 PyObject *context_switch_handler;
128 static struct tables tables_global;
130 static void handler_call_die(const char *handler_name) __noreturn;
131 static void handler_call_die(const char *handler_name)
134 Py_FatalError("problem in Python trace event handler");
135 // Py_FatalError does not return
136 // but we have to make the compiler happy
141 * Insert val into the dictionary and decrement the reference counter.
142 * This is necessary for dictionaries since PyDict_SetItemString() does not
143 * steal a reference, as opposed to PyTuple_SetItem().
145 static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
147 PyDict_SetItemString(dict, key, val);
151 static PyObject *get_handler(const char *handler_name)
155 handler = PyDict_GetItemString(main_dict, handler_name);
156 if (handler && !PyCallable_Check(handler))
161 static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
165 retval = PyObject_CallObject(handler, args);
167 handler_call_die(die_msg);
171 static void try_call_object(const char *handler_name, PyObject *args)
175 handler = get_handler(handler_name);
177 call_object(handler, args, handler_name);
180 #ifdef HAVE_LIBTRACEEVENT
181 static int get_argument_count(PyObject *handler)
186 * The attribute for the code object is func_code in Python 2,
187 * whereas it is __code__ in Python 3.0+.
189 PyObject *code_obj = PyObject_GetAttrString(handler,
191 if (PyErr_Occurred()) {
193 code_obj = PyObject_GetAttrString(handler,
198 PyObject *arg_count_obj = PyObject_GetAttrString(code_obj,
201 arg_count = (int) _PyLong_AsLong(arg_count_obj);
202 Py_DECREF(arg_count_obj);
209 static void define_value(enum tep_print_arg_type field_type,
211 const char *field_name,
212 const char *field_value,
213 const char *field_str)
215 const char *handler_name = "define_flag_value";
217 unsigned long long value;
220 if (field_type == TEP_PRINT_SYMBOL)
221 handler_name = "define_symbolic_value";
225 Py_FatalError("couldn't create Python tuple");
227 value = eval_flag(field_value);
229 PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
230 PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
231 PyTuple_SetItem(t, n++, _PyLong_FromLong(value));
232 PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_str));
234 try_call_object(handler_name, t);
239 static void define_values(enum tep_print_arg_type field_type,
240 struct tep_print_flag_sym *field,
242 const char *field_name)
244 define_value(field_type, ev_name, field_name, field->value,
248 define_values(field_type, field->next, ev_name, field_name);
251 static void define_field(enum tep_print_arg_type field_type,
253 const char *field_name,
256 const char *handler_name = "define_flag_field";
260 if (field_type == TEP_PRINT_SYMBOL)
261 handler_name = "define_symbolic_field";
263 if (field_type == TEP_PRINT_FLAGS)
268 Py_FatalError("couldn't create Python tuple");
270 PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
271 PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
272 if (field_type == TEP_PRINT_FLAGS)
273 PyTuple_SetItem(t, n++, _PyUnicode_FromString(delim));
275 try_call_object(handler_name, t);
280 static void define_event_symbols(struct tep_event *event,
282 struct tep_print_arg *args)
287 switch (args->type) {
291 define_value(TEP_PRINT_FLAGS, ev_name, cur_field_name, "0",
295 case TEP_PRINT_FIELD:
296 free(cur_field_name);
297 cur_field_name = strdup(args->field.name);
299 case TEP_PRINT_FLAGS:
300 define_event_symbols(event, ev_name, args->flags.field);
301 define_field(TEP_PRINT_FLAGS, ev_name, cur_field_name,
303 define_values(TEP_PRINT_FLAGS, args->flags.flags, ev_name,
306 case TEP_PRINT_SYMBOL:
307 define_event_symbols(event, ev_name, args->symbol.field);
308 define_field(TEP_PRINT_SYMBOL, ev_name, cur_field_name, NULL);
309 define_values(TEP_PRINT_SYMBOL, args->symbol.symbols, ev_name,
313 case TEP_PRINT_HEX_STR:
314 define_event_symbols(event, ev_name, args->hex.field);
315 define_event_symbols(event, ev_name, args->hex.size);
317 case TEP_PRINT_INT_ARRAY:
318 define_event_symbols(event, ev_name, args->int_array.field);
319 define_event_symbols(event, ev_name, args->int_array.count);
320 define_event_symbols(event, ev_name, args->int_array.el_size);
322 case TEP_PRINT_STRING:
325 define_event_symbols(event, ev_name, args->typecast.item);
328 if (strcmp(args->op.op, ":") == 0)
330 define_event_symbols(event, ev_name, args->op.left);
331 define_event_symbols(event, ev_name, args->op.right);
334 /* gcc warns for these? */
335 case TEP_PRINT_BSTRING:
336 case TEP_PRINT_DYNAMIC_ARRAY:
337 case TEP_PRINT_DYNAMIC_ARRAY_LEN:
339 case TEP_PRINT_BITMASK:
340 /* we should warn... */
345 define_event_symbols(event, ev_name, args->next);
348 static PyObject *get_field_numeric_entry(struct tep_event *event,
349 struct tep_format_field *field, void *data)
351 bool is_array = field->flags & TEP_FIELD_IS_ARRAY;
352 PyObject *obj = NULL, *list = NULL;
353 unsigned long long val;
354 unsigned int item_size, n_items, i;
357 list = PyList_New(field->arraylen);
358 item_size = field->size / field->arraylen;
359 n_items = field->arraylen;
361 item_size = field->size;
365 for (i = 0; i < n_items; i++) {
367 val = read_size(event, data + field->offset + i * item_size,
369 if (field->flags & TEP_FIELD_IS_SIGNED) {
370 if ((long long)val >= LONG_MIN &&
371 (long long)val <= LONG_MAX)
372 obj = _PyLong_FromLong(val);
374 obj = PyLong_FromLongLong(val);
377 obj = _PyLong_FromLong(val);
379 obj = PyLong_FromUnsignedLongLong(val);
382 PyList_SET_ITEM(list, i, obj);
390 static const char *get_dsoname(struct map *map)
392 const char *dsoname = "[unknown]";
393 struct dso *dso = map ? map__dso(map) : NULL;
396 if (symbol_conf.show_kernel_path && dso->long_name)
397 dsoname = dso->long_name;
405 static unsigned long get_offset(struct symbol *sym, struct addr_location *al)
407 unsigned long offset;
409 if (al->addr < sym->end)
410 offset = al->addr - sym->start;
412 offset = al->addr - map__start(al->map) - sym->start;
417 static PyObject *python_process_callchain(struct perf_sample *sample,
419 struct addr_location *al)
423 pylist = PyList_New(0);
425 Py_FatalError("couldn't create Python list");
427 if (!symbol_conf.use_callchain || !sample->callchain)
430 if (thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
432 scripting_max_stack) != 0) {
433 pr_err("Failed to resolve callchain. Skipping\n");
436 callchain_cursor_commit(&callchain_cursor);
441 struct callchain_cursor_node *node;
442 node = callchain_cursor_current(&callchain_cursor);
446 pyelem = PyDict_New();
448 Py_FatalError("couldn't create Python dictionary");
451 pydict_set_item_string_decref(pyelem, "ip",
452 PyLong_FromUnsignedLongLong(node->ip));
455 PyObject *pysym = PyDict_New();
457 Py_FatalError("couldn't create Python dictionary");
458 pydict_set_item_string_decref(pysym, "start",
459 PyLong_FromUnsignedLongLong(node->ms.sym->start));
460 pydict_set_item_string_decref(pysym, "end",
461 PyLong_FromUnsignedLongLong(node->ms.sym->end));
462 pydict_set_item_string_decref(pysym, "binding",
463 _PyLong_FromLong(node->ms.sym->binding));
464 pydict_set_item_string_decref(pysym, "name",
465 _PyUnicode_FromStringAndSize(node->ms.sym->name,
466 node->ms.sym->namelen));
467 pydict_set_item_string_decref(pyelem, "sym", pysym);
470 struct map *map = node->ms.map;
471 struct addr_location node_al;
472 unsigned long offset;
474 node_al.addr = map__map_ip(map, node->ip);
476 offset = get_offset(node->ms.sym, &node_al);
478 pydict_set_item_string_decref(
480 PyLong_FromUnsignedLongLong(offset));
482 if (node->srcline && strcmp(":0", node->srcline)) {
483 pydict_set_item_string_decref(
484 pyelem, "sym_srcline",
485 _PyUnicode_FromString(node->srcline));
490 const char *dsoname = get_dsoname(node->ms.map);
492 pydict_set_item_string_decref(pyelem, "dso",
493 _PyUnicode_FromString(dsoname));
496 callchain_cursor_advance(&callchain_cursor);
497 PyList_Append(pylist, pyelem);
505 static PyObject *python_process_brstack(struct perf_sample *sample,
506 struct thread *thread)
508 struct branch_stack *br = sample->branch_stack;
509 struct branch_entry *entries = perf_sample__branch_entries(sample);
513 pylist = PyList_New(0);
515 Py_FatalError("couldn't create Python list");
520 for (i = 0; i < br->nr; i++) {
522 struct addr_location al;
525 pyelem = PyDict_New();
527 Py_FatalError("couldn't create Python dictionary");
529 pydict_set_item_string_decref(pyelem, "from",
530 PyLong_FromUnsignedLongLong(entries[i].from));
531 pydict_set_item_string_decref(pyelem, "to",
532 PyLong_FromUnsignedLongLong(entries[i].to));
533 pydict_set_item_string_decref(pyelem, "mispred",
534 PyBool_FromLong(entries[i].flags.mispred));
535 pydict_set_item_string_decref(pyelem, "predicted",
536 PyBool_FromLong(entries[i].flags.predicted));
537 pydict_set_item_string_decref(pyelem, "in_tx",
538 PyBool_FromLong(entries[i].flags.in_tx));
539 pydict_set_item_string_decref(pyelem, "abort",
540 PyBool_FromLong(entries[i].flags.abort));
541 pydict_set_item_string_decref(pyelem, "cycles",
542 PyLong_FromUnsignedLongLong(entries[i].flags.cycles));
544 thread__find_map_fb(thread, sample->cpumode,
545 entries[i].from, &al);
546 dsoname = get_dsoname(al.map);
547 pydict_set_item_string_decref(pyelem, "from_dsoname",
548 _PyUnicode_FromString(dsoname));
550 thread__find_map_fb(thread, sample->cpumode,
552 dsoname = get_dsoname(al.map);
553 pydict_set_item_string_decref(pyelem, "to_dsoname",
554 _PyUnicode_FromString(dsoname));
556 PyList_Append(pylist, pyelem);
564 static int get_symoff(struct symbol *sym, struct addr_location *al,
565 bool print_off, char *bf, int size)
567 unsigned long offset;
569 if (!sym || !sym->name[0])
570 return scnprintf(bf, size, "%s", "[unknown]");
573 return scnprintf(bf, size, "%s", sym->name);
575 offset = get_offset(sym, al);
577 return scnprintf(bf, size, "%s+0x%x", sym->name, offset);
580 static int get_br_mspred(struct branch_flags *flags, char *bf, int size)
582 if (!flags->mispred && !flags->predicted)
583 return scnprintf(bf, size, "%s", "-");
586 return scnprintf(bf, size, "%s", "M");
588 return scnprintf(bf, size, "%s", "P");
591 static PyObject *python_process_brstacksym(struct perf_sample *sample,
592 struct thread *thread)
594 struct branch_stack *br = sample->branch_stack;
595 struct branch_entry *entries = perf_sample__branch_entries(sample);
599 struct addr_location al;
601 pylist = PyList_New(0);
603 Py_FatalError("couldn't create Python list");
608 for (i = 0; i < br->nr; i++) {
611 pyelem = PyDict_New();
613 Py_FatalError("couldn't create Python dictionary");
615 thread__find_symbol_fb(thread, sample->cpumode,
616 entries[i].from, &al);
617 get_symoff(al.sym, &al, true, bf, sizeof(bf));
618 pydict_set_item_string_decref(pyelem, "from",
619 _PyUnicode_FromString(bf));
621 thread__find_symbol_fb(thread, sample->cpumode,
623 get_symoff(al.sym, &al, true, bf, sizeof(bf));
624 pydict_set_item_string_decref(pyelem, "to",
625 _PyUnicode_FromString(bf));
627 get_br_mspred(&entries[i].flags, bf, sizeof(bf));
628 pydict_set_item_string_decref(pyelem, "pred",
629 _PyUnicode_FromString(bf));
631 if (entries[i].flags.in_tx) {
632 pydict_set_item_string_decref(pyelem, "in_tx",
633 _PyUnicode_FromString("X"));
635 pydict_set_item_string_decref(pyelem, "in_tx",
636 _PyUnicode_FromString("-"));
639 if (entries[i].flags.abort) {
640 pydict_set_item_string_decref(pyelem, "abort",
641 _PyUnicode_FromString("A"));
643 pydict_set_item_string_decref(pyelem, "abort",
644 _PyUnicode_FromString("-"));
647 PyList_Append(pylist, pyelem);
655 static PyObject *get_sample_value_as_tuple(struct sample_read_value *value,
662 Py_FatalError("couldn't create Python tuple");
663 PyTuple_SetItem(t, 0, PyLong_FromUnsignedLongLong(value->id));
664 PyTuple_SetItem(t, 1, PyLong_FromUnsignedLongLong(value->value));
665 if (read_format & PERF_FORMAT_LOST)
666 PyTuple_SetItem(t, 2, PyLong_FromUnsignedLongLong(value->lost));
671 static void set_sample_read_in_dict(PyObject *dict_sample,
672 struct perf_sample *sample,
675 u64 read_format = evsel->core.attr.read_format;
679 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
680 pydict_set_item_string_decref(dict_sample, "time_enabled",
681 PyLong_FromUnsignedLongLong(sample->read.time_enabled));
684 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
685 pydict_set_item_string_decref(dict_sample, "time_running",
686 PyLong_FromUnsignedLongLong(sample->read.time_running));
689 if (read_format & PERF_FORMAT_GROUP)
690 values = PyList_New(sample->read.group.nr);
692 values = PyList_New(1);
695 Py_FatalError("couldn't create Python list");
697 if (read_format & PERF_FORMAT_GROUP) {
698 struct sample_read_value *v = sample->read.group.values;
701 sample_read_group__for_each(v, sample->read.group.nr, read_format) {
702 PyObject *t = get_sample_value_as_tuple(v, read_format);
703 PyList_SET_ITEM(values, i, t);
707 PyObject *t = get_sample_value_as_tuple(&sample->read.one,
709 PyList_SET_ITEM(values, 0, t);
711 pydict_set_item_string_decref(dict_sample, "values", values);
714 static void set_sample_datasrc_in_dict(PyObject *dict,
715 struct perf_sample *sample)
717 struct mem_info mi = { .data_src.val = sample->data_src };
720 pydict_set_item_string_decref(dict, "datasrc",
721 PyLong_FromUnsignedLongLong(sample->data_src));
723 perf_script__meminfo_scnprintf(decode, 100, &mi);
725 pydict_set_item_string_decref(dict, "datasrc_decode",
726 _PyUnicode_FromString(decode));
729 static void regs_map(struct regs_dump *regs, uint64_t mask, const char *arch, char *bf, int size)
731 unsigned int i = 0, r;
736 if (!regs || !regs->regs)
739 for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
740 u64 val = regs->regs[i++];
742 printed += scnprintf(bf + printed, size - printed,
743 "%5s:0x%" PRIx64 " ",
744 perf_reg_name(r, arch), val);
748 static void set_regs_in_dict(PyObject *dict,
749 struct perf_sample *sample,
752 struct perf_event_attr *attr = &evsel->core.attr;
753 const char *arch = perf_env__arch(evsel__env(evsel));
756 * Here value 28 is a constant size which can be used to print
757 * one register value and its corresponds to:
758 * 16 chars is to specify 64 bit register in hexadecimal.
759 * 2 chars is for appending "0x" to the hexadecimal value and
760 * 10 chars is for register name.
762 int size = __sw_hweight64(attr->sample_regs_intr) * 28;
765 regs_map(&sample->intr_regs, attr->sample_regs_intr, arch, bf, sizeof(bf));
767 pydict_set_item_string_decref(dict, "iregs",
768 _PyUnicode_FromString(bf));
770 regs_map(&sample->user_regs, attr->sample_regs_user, arch, bf, sizeof(bf));
772 pydict_set_item_string_decref(dict, "uregs",
773 _PyUnicode_FromString(bf));
776 static void set_sym_in_dict(PyObject *dict, struct addr_location *al,
777 const char *dso_field, const char *dso_bid_field,
778 const char *dso_map_start, const char *dso_map_end,
779 const char *sym_field, const char *symoff_field)
781 char sbuild_id[SBUILD_ID_SIZE];
784 struct dso *dso = map__dso(al->map);
786 pydict_set_item_string_decref(dict, dso_field, _PyUnicode_FromString(dso->name));
787 build_id__sprintf(&dso->bid, sbuild_id);
788 pydict_set_item_string_decref(dict, dso_bid_field,
789 _PyUnicode_FromString(sbuild_id));
790 pydict_set_item_string_decref(dict, dso_map_start,
791 PyLong_FromUnsignedLong(map__start(al->map)));
792 pydict_set_item_string_decref(dict, dso_map_end,
793 PyLong_FromUnsignedLong(map__end(al->map)));
796 pydict_set_item_string_decref(dict, sym_field,
797 _PyUnicode_FromString(al->sym->name));
798 pydict_set_item_string_decref(dict, symoff_field,
799 PyLong_FromUnsignedLong(get_offset(al->sym, al)));
803 static void set_sample_flags(PyObject *dict, u32 flags)
805 const char *ch = PERF_IP_FLAG_CHARS;
808 for (p = str; *ch; ch++, flags >>= 1) {
813 pydict_set_item_string_decref(dict, "flags", _PyUnicode_FromString(str));
816 static void python_process_sample_flags(struct perf_sample *sample, PyObject *dict_sample)
818 char flags_disp[SAMPLE_FLAGS_BUF_SIZE];
820 set_sample_flags(dict_sample, sample->flags);
821 perf_sample__sprintf_flags(sample->flags, flags_disp, sizeof(flags_disp));
822 pydict_set_item_string_decref(dict_sample, "flags_disp",
823 _PyUnicode_FromString(flags_disp));
826 static PyObject *get_perf_sample_dict(struct perf_sample *sample,
828 struct addr_location *al,
829 struct addr_location *addr_al,
832 PyObject *dict, *dict_sample, *brstack, *brstacksym;
836 Py_FatalError("couldn't create Python dictionary");
838 dict_sample = PyDict_New();
840 Py_FatalError("couldn't create Python dictionary");
842 pydict_set_item_string_decref(dict, "ev_name", _PyUnicode_FromString(evsel__name(evsel)));
843 pydict_set_item_string_decref(dict, "attr", _PyBytes_FromStringAndSize((const char *)&evsel->core.attr, sizeof(evsel->core.attr)));
845 pydict_set_item_string_decref(dict_sample, "pid",
846 _PyLong_FromLong(sample->pid));
847 pydict_set_item_string_decref(dict_sample, "tid",
848 _PyLong_FromLong(sample->tid));
849 pydict_set_item_string_decref(dict_sample, "cpu",
850 _PyLong_FromLong(sample->cpu));
851 pydict_set_item_string_decref(dict_sample, "ip",
852 PyLong_FromUnsignedLongLong(sample->ip));
853 pydict_set_item_string_decref(dict_sample, "time",
854 PyLong_FromUnsignedLongLong(sample->time));
855 pydict_set_item_string_decref(dict_sample, "period",
856 PyLong_FromUnsignedLongLong(sample->period));
857 pydict_set_item_string_decref(dict_sample, "phys_addr",
858 PyLong_FromUnsignedLongLong(sample->phys_addr));
859 pydict_set_item_string_decref(dict_sample, "addr",
860 PyLong_FromUnsignedLongLong(sample->addr));
861 set_sample_read_in_dict(dict_sample, sample, evsel);
862 pydict_set_item_string_decref(dict_sample, "weight",
863 PyLong_FromUnsignedLongLong(sample->weight));
864 pydict_set_item_string_decref(dict_sample, "transaction",
865 PyLong_FromUnsignedLongLong(sample->transaction));
866 set_sample_datasrc_in_dict(dict_sample, sample);
867 pydict_set_item_string_decref(dict, "sample", dict_sample);
869 pydict_set_item_string_decref(dict, "raw_buf", _PyBytes_FromStringAndSize(
870 (const char *)sample->raw_data, sample->raw_size));
871 pydict_set_item_string_decref(dict, "comm",
872 _PyUnicode_FromString(thread__comm_str(al->thread)));
873 set_sym_in_dict(dict, al, "dso", "dso_bid", "dso_map_start", "dso_map_end",
876 pydict_set_item_string_decref(dict, "callchain", callchain);
878 brstack = python_process_brstack(sample, al->thread);
879 pydict_set_item_string_decref(dict, "brstack", brstack);
881 brstacksym = python_process_brstacksym(sample, al->thread);
882 pydict_set_item_string_decref(dict, "brstacksym", brstacksym);
884 if (sample->machine_pid) {
885 pydict_set_item_string_decref(dict_sample, "machine_pid",
886 _PyLong_FromLong(sample->machine_pid));
887 pydict_set_item_string_decref(dict_sample, "vcpu",
888 _PyLong_FromLong(sample->vcpu));
891 pydict_set_item_string_decref(dict_sample, "cpumode",
892 _PyLong_FromLong((unsigned long)sample->cpumode));
895 pydict_set_item_string_decref(dict_sample, "addr_correlates_sym",
897 set_sym_in_dict(dict_sample, addr_al, "addr_dso", "addr_dso_bid",
898 "addr_dso_map_start", "addr_dso_map_end",
899 "addr_symbol", "addr_symoff");
903 python_process_sample_flags(sample, dict_sample);
905 /* Instructions per cycle (IPC) */
906 if (sample->insn_cnt && sample->cyc_cnt) {
907 pydict_set_item_string_decref(dict_sample, "insn_cnt",
908 PyLong_FromUnsignedLongLong(sample->insn_cnt));
909 pydict_set_item_string_decref(dict_sample, "cyc_cnt",
910 PyLong_FromUnsignedLongLong(sample->cyc_cnt));
913 set_regs_in_dict(dict, sample, evsel);
918 #ifdef HAVE_LIBTRACEEVENT
919 static void python_process_tracepoint(struct perf_sample *sample,
921 struct addr_location *al,
922 struct addr_location *addr_al)
924 struct tep_event *event = evsel->tp_format;
925 PyObject *handler, *context, *t, *obj = NULL, *callchain;
926 PyObject *dict = NULL, *all_entries_dict = NULL;
927 static char handler_name[256];
928 struct tep_format_field *field;
932 int cpu = sample->cpu;
933 void *data = sample->raw_data;
934 unsigned long long nsecs = sample->time;
935 const char *comm = thread__comm_str(al->thread);
936 const char *default_handler_name = "trace_unhandled";
939 snprintf(handler_name, sizeof(handler_name),
940 "ug! no event found for type %" PRIu64, (u64)evsel->core.attr.config);
941 Py_FatalError(handler_name);
944 pid = raw_field_value(event, "common_pid", data);
946 sprintf(handler_name, "%s__%s", event->system, event->name);
948 if (!__test_and_set_bit(event->id, events_defined))
949 define_event_symbols(event, handler_name, event->print_fmt.args);
951 handler = get_handler(handler_name);
953 handler = get_handler(default_handler_name);
958 Py_FatalError("couldn't create Python dict");
961 t = PyTuple_New(MAX_FIELDS);
963 Py_FatalError("couldn't create Python tuple");
966 s = nsecs / NSEC_PER_SEC;
967 ns = nsecs - s * NSEC_PER_SEC;
969 context = _PyCapsule_New(scripting_context, NULL, NULL);
971 PyTuple_SetItem(t, n++, _PyUnicode_FromString(handler_name));
972 PyTuple_SetItem(t, n++, context);
975 callchain = python_process_callchain(sample, evsel, al);
976 /* Need an additional reference for the perf_sample dict */
977 Py_INCREF(callchain);
980 PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
981 PyTuple_SetItem(t, n++, _PyLong_FromLong(s));
982 PyTuple_SetItem(t, n++, _PyLong_FromLong(ns));
983 PyTuple_SetItem(t, n++, _PyLong_FromLong(pid));
984 PyTuple_SetItem(t, n++, _PyUnicode_FromString(comm));
985 PyTuple_SetItem(t, n++, callchain);
987 pydict_set_item_string_decref(dict, "common_cpu", _PyLong_FromLong(cpu));
988 pydict_set_item_string_decref(dict, "common_s", _PyLong_FromLong(s));
989 pydict_set_item_string_decref(dict, "common_ns", _PyLong_FromLong(ns));
990 pydict_set_item_string_decref(dict, "common_pid", _PyLong_FromLong(pid));
991 pydict_set_item_string_decref(dict, "common_comm", _PyUnicode_FromString(comm));
992 pydict_set_item_string_decref(dict, "common_callchain", callchain);
994 for (field = event->format.fields; field; field = field->next) {
995 unsigned int offset, len;
996 unsigned long long val;
998 if (field->flags & TEP_FIELD_IS_ARRAY) {
999 offset = field->offset;
1001 if (field->flags & TEP_FIELD_IS_DYNAMIC) {
1002 val = tep_read_number(scripting_context->pevent,
1003 data + offset, len);
1007 if (tep_field_is_relative(field->flags))
1008 offset += field->offset + field->size;
1010 if (field->flags & TEP_FIELD_IS_STRING &&
1011 is_printable_array(data + offset, len)) {
1012 obj = _PyUnicode_FromString((char *) data + offset);
1014 obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
1015 field->flags &= ~TEP_FIELD_IS_STRING;
1017 } else { /* FIELD_IS_NUMERIC */
1018 obj = get_field_numeric_entry(event, field, data);
1021 PyTuple_SetItem(t, n++, obj);
1023 pydict_set_item_string_decref(dict, field->name, obj);
1028 PyTuple_SetItem(t, n++, dict);
1030 if (get_argument_count(handler) == (int) n + 1) {
1031 all_entries_dict = get_perf_sample_dict(sample, evsel, al, addr_al,
1033 PyTuple_SetItem(t, n++, all_entries_dict);
1035 Py_DECREF(callchain);
1038 if (_PyTuple_Resize(&t, n) == -1)
1039 Py_FatalError("error resizing Python tuple");
1042 call_object(handler, t, handler_name);
1044 call_object(handler, t, default_handler_name);
1049 static void python_process_tracepoint(struct perf_sample *sample __maybe_unused,
1050 struct evsel *evsel __maybe_unused,
1051 struct addr_location *al __maybe_unused,
1052 struct addr_location *addr_al __maybe_unused)
1054 fprintf(stderr, "Tracepoint events are not supported because "
1055 "perf is not linked with libtraceevent.\n");
1059 static PyObject *tuple_new(unsigned int sz)
1063 t = PyTuple_New(sz);
1065 Py_FatalError("couldn't create Python tuple");
1069 static int tuple_set_s64(PyObject *t, unsigned int pos, s64 val)
1071 #if BITS_PER_LONG == 64
1072 return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
1074 #if BITS_PER_LONG == 32
1075 return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
1080 * Databases support only signed 64-bit numbers, so even though we are
1081 * exporting a u64, it must be as s64.
1083 #define tuple_set_d64 tuple_set_s64
1085 static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
1087 #if BITS_PER_LONG == 64
1088 return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
1090 #if BITS_PER_LONG == 32
1091 return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLongLong(val));
1095 static int tuple_set_u32(PyObject *t, unsigned int pos, u32 val)
1097 return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
1100 static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
1102 return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
1105 static int tuple_set_bool(PyObject *t, unsigned int pos, bool val)
1107 return PyTuple_SetItem(t, pos, PyBool_FromLong(val));
1110 static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
1112 return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
1115 static int tuple_set_bytes(PyObject *t, unsigned int pos, void *bytes,
1118 return PyTuple_SetItem(t, pos, _PyBytes_FromStringAndSize(bytes, sz));
1121 static int python_export_evsel(struct db_export *dbe, struct evsel *evsel)
1123 struct tables *tables = container_of(dbe, struct tables, dbe);
1128 tuple_set_d64(t, 0, evsel->db_id);
1129 tuple_set_string(t, 1, evsel__name(evsel));
1131 call_object(tables->evsel_handler, t, "evsel_table");
1138 static int python_export_machine(struct db_export *dbe,
1139 struct machine *machine)
1141 struct tables *tables = container_of(dbe, struct tables, dbe);
1146 tuple_set_d64(t, 0, machine->db_id);
1147 tuple_set_s32(t, 1, machine->pid);
1148 tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
1150 call_object(tables->machine_handler, t, "machine_table");
1157 static int python_export_thread(struct db_export *dbe, struct thread *thread,
1158 u64 main_thread_db_id, struct machine *machine)
1160 struct tables *tables = container_of(dbe, struct tables, dbe);
1165 tuple_set_d64(t, 0, thread->db_id);
1166 tuple_set_d64(t, 1, machine->db_id);
1167 tuple_set_d64(t, 2, main_thread_db_id);
1168 tuple_set_s32(t, 3, thread->pid_);
1169 tuple_set_s32(t, 4, thread->tid);
1171 call_object(tables->thread_handler, t, "thread_table");
1178 static int python_export_comm(struct db_export *dbe, struct comm *comm,
1179 struct thread *thread)
1181 struct tables *tables = container_of(dbe, struct tables, dbe);
1186 tuple_set_d64(t, 0, comm->db_id);
1187 tuple_set_string(t, 1, comm__str(comm));
1188 tuple_set_d64(t, 2, thread->db_id);
1189 tuple_set_d64(t, 3, comm->start);
1190 tuple_set_s32(t, 4, comm->exec);
1192 call_object(tables->comm_handler, t, "comm_table");
1199 static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
1200 struct comm *comm, struct thread *thread)
1202 struct tables *tables = container_of(dbe, struct tables, dbe);
1207 tuple_set_d64(t, 0, db_id);
1208 tuple_set_d64(t, 1, comm->db_id);
1209 tuple_set_d64(t, 2, thread->db_id);
1211 call_object(tables->comm_thread_handler, t, "comm_thread_table");
1218 static int python_export_dso(struct db_export *dbe, struct dso *dso,
1219 struct machine *machine)
1221 struct tables *tables = container_of(dbe, struct tables, dbe);
1222 char sbuild_id[SBUILD_ID_SIZE];
1225 build_id__sprintf(&dso->bid, sbuild_id);
1229 tuple_set_d64(t, 0, dso->db_id);
1230 tuple_set_d64(t, 1, machine->db_id);
1231 tuple_set_string(t, 2, dso->short_name);
1232 tuple_set_string(t, 3, dso->long_name);
1233 tuple_set_string(t, 4, sbuild_id);
1235 call_object(tables->dso_handler, t, "dso_table");
1242 static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
1245 struct tables *tables = container_of(dbe, struct tables, dbe);
1246 u64 *sym_db_id = symbol__priv(sym);
1251 tuple_set_d64(t, 0, *sym_db_id);
1252 tuple_set_d64(t, 1, dso->db_id);
1253 tuple_set_d64(t, 2, sym->start);
1254 tuple_set_d64(t, 3, sym->end);
1255 tuple_set_s32(t, 4, sym->binding);
1256 tuple_set_string(t, 5, sym->name);
1258 call_object(tables->symbol_handler, t, "symbol_table");
1265 static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
1268 struct tables *tables = container_of(dbe, struct tables, dbe);
1273 tuple_set_s32(t, 0, branch_type);
1274 tuple_set_string(t, 1, name);
1276 call_object(tables->branch_type_handler, t, "branch_type_table");
1283 static void python_export_sample_table(struct db_export *dbe,
1284 struct export_sample *es)
1286 struct tables *tables = container_of(dbe, struct tables, dbe);
1291 tuple_set_d64(t, 0, es->db_id);
1292 tuple_set_d64(t, 1, es->evsel->db_id);
1293 tuple_set_d64(t, 2, maps__machine(es->al->maps)->db_id);
1294 tuple_set_d64(t, 3, es->al->thread->db_id);
1295 tuple_set_d64(t, 4, es->comm_db_id);
1296 tuple_set_d64(t, 5, es->dso_db_id);
1297 tuple_set_d64(t, 6, es->sym_db_id);
1298 tuple_set_d64(t, 7, es->offset);
1299 tuple_set_d64(t, 8, es->sample->ip);
1300 tuple_set_d64(t, 9, es->sample->time);
1301 tuple_set_s32(t, 10, es->sample->cpu);
1302 tuple_set_d64(t, 11, es->addr_dso_db_id);
1303 tuple_set_d64(t, 12, es->addr_sym_db_id);
1304 tuple_set_d64(t, 13, es->addr_offset);
1305 tuple_set_d64(t, 14, es->sample->addr);
1306 tuple_set_d64(t, 15, es->sample->period);
1307 tuple_set_d64(t, 16, es->sample->weight);
1308 tuple_set_d64(t, 17, es->sample->transaction);
1309 tuple_set_d64(t, 18, es->sample->data_src);
1310 tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
1311 tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
1312 tuple_set_d64(t, 21, es->call_path_id);
1313 tuple_set_d64(t, 22, es->sample->insn_cnt);
1314 tuple_set_d64(t, 23, es->sample->cyc_cnt);
1315 tuple_set_s32(t, 24, es->sample->flags);
1317 call_object(tables->sample_handler, t, "sample_table");
1322 static void python_export_synth(struct db_export *dbe, struct export_sample *es)
1324 struct tables *tables = container_of(dbe, struct tables, dbe);
1329 tuple_set_d64(t, 0, es->db_id);
1330 tuple_set_d64(t, 1, es->evsel->core.attr.config);
1331 tuple_set_bytes(t, 2, es->sample->raw_data, es->sample->raw_size);
1333 call_object(tables->synth_handler, t, "synth_data");
1338 static int python_export_sample(struct db_export *dbe,
1339 struct export_sample *es)
1341 struct tables *tables = container_of(dbe, struct tables, dbe);
1343 python_export_sample_table(dbe, es);
1345 if (es->evsel->core.attr.type == PERF_TYPE_SYNTH && tables->synth_handler)
1346 python_export_synth(dbe, es);
1351 static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
1353 struct tables *tables = container_of(dbe, struct tables, dbe);
1355 u64 parent_db_id, sym_db_id;
1357 parent_db_id = cp->parent ? cp->parent->db_id : 0;
1358 sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
1362 tuple_set_d64(t, 0, cp->db_id);
1363 tuple_set_d64(t, 1, parent_db_id);
1364 tuple_set_d64(t, 2, sym_db_id);
1365 tuple_set_d64(t, 3, cp->ip);
1367 call_object(tables->call_path_handler, t, "call_path_table");
1374 static int python_export_call_return(struct db_export *dbe,
1375 struct call_return *cr)
1377 struct tables *tables = container_of(dbe, struct tables, dbe);
1378 u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
1383 tuple_set_d64(t, 0, cr->db_id);
1384 tuple_set_d64(t, 1, cr->thread->db_id);
1385 tuple_set_d64(t, 2, comm_db_id);
1386 tuple_set_d64(t, 3, cr->cp->db_id);
1387 tuple_set_d64(t, 4, cr->call_time);
1388 tuple_set_d64(t, 5, cr->return_time);
1389 tuple_set_d64(t, 6, cr->branch_count);
1390 tuple_set_d64(t, 7, cr->call_ref);
1391 tuple_set_d64(t, 8, cr->return_ref);
1392 tuple_set_d64(t, 9, cr->cp->parent->db_id);
1393 tuple_set_s32(t, 10, cr->flags);
1394 tuple_set_d64(t, 11, cr->parent_db_id);
1395 tuple_set_d64(t, 12, cr->insn_count);
1396 tuple_set_d64(t, 13, cr->cyc_count);
1398 call_object(tables->call_return_handler, t, "call_return_table");
1405 static int python_export_context_switch(struct db_export *dbe, u64 db_id,
1406 struct machine *machine,
1407 struct perf_sample *sample,
1408 u64 th_out_id, u64 comm_out_id,
1409 u64 th_in_id, u64 comm_in_id, int flags)
1411 struct tables *tables = container_of(dbe, struct tables, dbe);
1416 tuple_set_d64(t, 0, db_id);
1417 tuple_set_d64(t, 1, machine->db_id);
1418 tuple_set_d64(t, 2, sample->time);
1419 tuple_set_s32(t, 3, sample->cpu);
1420 tuple_set_d64(t, 4, th_out_id);
1421 tuple_set_d64(t, 5, comm_out_id);
1422 tuple_set_d64(t, 6, th_in_id);
1423 tuple_set_d64(t, 7, comm_in_id);
1424 tuple_set_s32(t, 8, flags);
1426 call_object(tables->context_switch_handler, t, "context_switch");
1433 static int python_process_call_return(struct call_return *cr, u64 *parent_db_id,
1436 struct db_export *dbe = data;
1438 return db_export__call_return(dbe, cr, parent_db_id);
1441 static void python_process_general_event(struct perf_sample *sample,
1442 struct evsel *evsel,
1443 struct addr_location *al,
1444 struct addr_location *addr_al)
1446 PyObject *handler, *t, *dict, *callchain;
1447 static char handler_name[64];
1450 snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
1452 handler = get_handler(handler_name);
1457 * Use the MAX_FIELDS to make the function expandable, though
1458 * currently there is only one item for the tuple.
1460 t = PyTuple_New(MAX_FIELDS);
1462 Py_FatalError("couldn't create Python tuple");
1465 callchain = python_process_callchain(sample, evsel, al);
1466 dict = get_perf_sample_dict(sample, evsel, al, addr_al, callchain);
1468 PyTuple_SetItem(t, n++, dict);
1469 if (_PyTuple_Resize(&t, n) == -1)
1470 Py_FatalError("error resizing Python tuple");
1472 call_object(handler, t, handler_name);
1477 static void python_process_event(union perf_event *event,
1478 struct perf_sample *sample,
1479 struct evsel *evsel,
1480 struct addr_location *al,
1481 struct addr_location *addr_al)
1483 struct tables *tables = &tables_global;
1485 scripting_context__update(scripting_context, event, sample, evsel, al, addr_al);
1487 switch (evsel->core.attr.type) {
1488 case PERF_TYPE_TRACEPOINT:
1489 python_process_tracepoint(sample, evsel, al, addr_al);
1491 /* Reserve for future process_hw/sw/raw APIs */
1493 if (tables->db_export_mode)
1494 db_export__sample(&tables->dbe, event, sample, evsel, al, addr_al);
1496 python_process_general_event(sample, evsel, al, addr_al);
1500 static void python_process_throttle(union perf_event *event,
1501 struct perf_sample *sample,
1502 struct machine *machine)
1504 const char *handler_name;
1505 PyObject *handler, *t;
1507 if (event->header.type == PERF_RECORD_THROTTLE)
1508 handler_name = "throttle";
1510 handler_name = "unthrottle";
1511 handler = get_handler(handler_name);
1519 tuple_set_u64(t, 0, event->throttle.time);
1520 tuple_set_u64(t, 1, event->throttle.id);
1521 tuple_set_u64(t, 2, event->throttle.stream_id);
1522 tuple_set_s32(t, 3, sample->cpu);
1523 tuple_set_s32(t, 4, sample->pid);
1524 tuple_set_s32(t, 5, sample->tid);
1526 call_object(handler, t, handler_name);
1531 static void python_do_process_switch(union perf_event *event,
1532 struct perf_sample *sample,
1533 struct machine *machine)
1535 const char *handler_name = "context_switch";
1536 bool out = event->header.misc & PERF_RECORD_MISC_SWITCH_OUT;
1537 bool out_preempt = out && (event->header.misc & PERF_RECORD_MISC_SWITCH_OUT_PREEMPT);
1538 pid_t np_pid = -1, np_tid = -1;
1539 PyObject *handler, *t;
1541 handler = get_handler(handler_name);
1545 if (event->header.type == PERF_RECORD_SWITCH_CPU_WIDE) {
1546 np_pid = event->context_switch.next_prev_pid;
1547 np_tid = event->context_switch.next_prev_tid;
1554 tuple_set_u64(t, 0, sample->time);
1555 tuple_set_s32(t, 1, sample->cpu);
1556 tuple_set_s32(t, 2, sample->pid);
1557 tuple_set_s32(t, 3, sample->tid);
1558 tuple_set_s32(t, 4, np_pid);
1559 tuple_set_s32(t, 5, np_tid);
1560 tuple_set_s32(t, 6, machine->pid);
1561 tuple_set_bool(t, 7, out);
1562 tuple_set_bool(t, 8, out_preempt);
1563 tuple_set_s32(t, 9, sample->machine_pid);
1564 tuple_set_s32(t, 10, sample->vcpu);
1566 call_object(handler, t, handler_name);
1571 static void python_process_switch(union perf_event *event,
1572 struct perf_sample *sample,
1573 struct machine *machine)
1575 struct tables *tables = &tables_global;
1577 if (tables->db_export_mode)
1578 db_export__switch(&tables->dbe, event, sample, machine);
1580 python_do_process_switch(event, sample, machine);
1583 static void python_process_auxtrace_error(struct perf_session *session __maybe_unused,
1584 union perf_event *event)
1586 struct perf_record_auxtrace_error *e = &event->auxtrace_error;
1587 u8 cpumode = e->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
1588 const char *handler_name = "auxtrace_error";
1589 unsigned long long tm = e->time;
1590 const char *msg = e->msg;
1591 PyObject *handler, *t;
1593 handler = get_handler(handler_name);
1599 msg = (const char *)&e->time;
1604 tuple_set_u32(t, 0, e->type);
1605 tuple_set_u32(t, 1, e->code);
1606 tuple_set_s32(t, 2, e->cpu);
1607 tuple_set_s32(t, 3, e->pid);
1608 tuple_set_s32(t, 4, e->tid);
1609 tuple_set_u64(t, 5, e->ip);
1610 tuple_set_u64(t, 6, tm);
1611 tuple_set_string(t, 7, msg);
1612 tuple_set_u32(t, 8, cpumode);
1613 tuple_set_s32(t, 9, e->machine_pid);
1614 tuple_set_s32(t, 10, e->vcpu);
1616 call_object(handler, t, handler_name);
1621 static void get_handler_name(char *str, size_t size,
1622 struct evsel *evsel)
1626 scnprintf(str, size, "stat__%s", evsel__name(evsel));
1628 while ((p = strchr(p, ':'))) {
1635 process_stat(struct evsel *counter, struct perf_cpu cpu, int thread, u64 tstamp,
1636 struct perf_counts_values *count)
1638 PyObject *handler, *t;
1639 static char handler_name[256];
1642 t = PyTuple_New(MAX_FIELDS);
1644 Py_FatalError("couldn't create Python tuple");
1646 get_handler_name(handler_name, sizeof(handler_name),
1649 handler = get_handler(handler_name);
1651 pr_debug("can't find python handler %s\n", handler_name);
1655 PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu.cpu));
1656 PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
1658 tuple_set_u64(t, n++, tstamp);
1659 tuple_set_u64(t, n++, count->val);
1660 tuple_set_u64(t, n++, count->ena);
1661 tuple_set_u64(t, n++, count->run);
1663 if (_PyTuple_Resize(&t, n) == -1)
1664 Py_FatalError("error resizing Python tuple");
1666 call_object(handler, t, handler_name);
1671 static void python_process_stat(struct perf_stat_config *config,
1672 struct evsel *counter, u64 tstamp)
1674 struct perf_thread_map *threads = counter->core.threads;
1675 struct perf_cpu_map *cpus = counter->core.cpus;
1678 for (thread = 0; thread < perf_thread_map__nr(threads); thread++) {
1679 for (cpu = 0; cpu < perf_cpu_map__nr(cpus); cpu++) {
1680 process_stat(counter, perf_cpu_map__cpu(cpus, cpu),
1681 perf_thread_map__pid(threads, thread), tstamp,
1682 perf_counts(counter->counts, cpu, thread));
1687 static void python_process_stat_interval(u64 tstamp)
1689 PyObject *handler, *t;
1690 static const char handler_name[] = "stat__interval";
1693 t = PyTuple_New(MAX_FIELDS);
1695 Py_FatalError("couldn't create Python tuple");
1697 handler = get_handler(handler_name);
1699 pr_debug("can't find python handler %s\n", handler_name);
1703 tuple_set_u64(t, n++, tstamp);
1705 if (_PyTuple_Resize(&t, n) == -1)
1706 Py_FatalError("error resizing Python tuple");
1708 call_object(handler, t, handler_name);
1713 static int perf_script_context_init(void)
1715 PyObject *perf_script_context;
1716 PyObject *perf_trace_context;
1720 perf_trace_context = PyImport_AddModule("perf_trace_context");
1721 if (!perf_trace_context)
1723 dict = PyModule_GetDict(perf_trace_context);
1727 perf_script_context = _PyCapsule_New(scripting_context, NULL, NULL);
1728 if (!perf_script_context)
1731 ret = PyDict_SetItemString(dict, "perf_script_context", perf_script_context);
1733 ret = PyDict_SetItemString(main_dict, "perf_script_context", perf_script_context);
1734 Py_DECREF(perf_script_context);
1738 static int run_start_sub(void)
1740 main_module = PyImport_AddModule("__main__");
1741 if (main_module == NULL)
1743 Py_INCREF(main_module);
1745 main_dict = PyModule_GetDict(main_module);
1746 if (main_dict == NULL)
1748 Py_INCREF(main_dict);
1750 if (perf_script_context_init())
1753 try_call_object("trace_begin", NULL);
1758 Py_XDECREF(main_dict);
1759 Py_XDECREF(main_module);
1763 #define SET_TABLE_HANDLER_(name, handler_name, table_name) do { \
1764 tables->handler_name = get_handler(#table_name); \
1765 if (tables->handler_name) \
1766 tables->dbe.export_ ## name = python_export_ ## name; \
1769 #define SET_TABLE_HANDLER(name) \
1770 SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
1772 static void set_table_handlers(struct tables *tables)
1774 const char *perf_db_export_mode = "perf_db_export_mode";
1775 const char *perf_db_export_calls = "perf_db_export_calls";
1776 const char *perf_db_export_callchains = "perf_db_export_callchains";
1777 PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
1778 bool export_calls = false;
1779 bool export_callchains = false;
1782 memset(tables, 0, sizeof(struct tables));
1783 if (db_export__init(&tables->dbe))
1784 Py_FatalError("failed to initialize export");
1786 db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
1787 if (!db_export_mode)
1790 ret = PyObject_IsTrue(db_export_mode);
1792 handler_call_die(perf_db_export_mode);
1796 /* handle export calls */
1797 tables->dbe.crp = NULL;
1798 db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
1799 if (db_export_calls) {
1800 ret = PyObject_IsTrue(db_export_calls);
1802 handler_call_die(perf_db_export_calls);
1803 export_calls = !!ret;
1808 call_return_processor__new(python_process_call_return,
1810 if (!tables->dbe.crp)
1811 Py_FatalError("failed to create calls processor");
1814 /* handle export callchains */
1815 tables->dbe.cpr = NULL;
1816 db_export_callchains = PyDict_GetItemString(main_dict,
1817 perf_db_export_callchains);
1818 if (db_export_callchains) {
1819 ret = PyObject_IsTrue(db_export_callchains);
1821 handler_call_die(perf_db_export_callchains);
1822 export_callchains = !!ret;
1825 if (export_callchains) {
1827 * Attempt to use the call path root from the call return
1828 * processor, if the call return processor is in use. Otherwise,
1829 * we allocate a new call path root. This prevents exporting
1830 * duplicate call path ids when both are in use simultaneously.
1832 if (tables->dbe.crp)
1833 tables->dbe.cpr = tables->dbe.crp->cpr;
1835 tables->dbe.cpr = call_path_root__new();
1837 if (!tables->dbe.cpr)
1838 Py_FatalError("failed to create call path root");
1841 tables->db_export_mode = true;
1843 * Reserve per symbol space for symbol->db_id via symbol__priv()
1845 symbol_conf.priv_size = sizeof(u64);
1847 SET_TABLE_HANDLER(evsel);
1848 SET_TABLE_HANDLER(machine);
1849 SET_TABLE_HANDLER(thread);
1850 SET_TABLE_HANDLER(comm);
1851 SET_TABLE_HANDLER(comm_thread);
1852 SET_TABLE_HANDLER(dso);
1853 SET_TABLE_HANDLER(symbol);
1854 SET_TABLE_HANDLER(branch_type);
1855 SET_TABLE_HANDLER(sample);
1856 SET_TABLE_HANDLER(call_path);
1857 SET_TABLE_HANDLER(call_return);
1858 SET_TABLE_HANDLER(context_switch);
1861 * Synthesized events are samples but with architecture-specific data
1862 * stored in sample->raw_data. They are exported via
1863 * python_export_sample() and consequently do not need a separate export
1866 tables->synth_handler = get_handler("synth_data");
1869 #if PY_MAJOR_VERSION < 3
1870 static void _free_command_line(const char **command_line, int num)
1875 static void _free_command_line(wchar_t **command_line, int num)
1878 for (i = 0; i < num; i++)
1879 PyMem_RawFree(command_line[i]);
1886 * Start trace script
1888 static int python_start_script(const char *script, int argc, const char **argv,
1889 struct perf_session *session)
1891 struct tables *tables = &tables_global;
1892 #if PY_MAJOR_VERSION < 3
1893 const char **command_line;
1895 wchar_t **command_line;
1898 * Use a non-const name variable to cope with python 2.6's
1899 * PyImport_AppendInittab prototype
1901 char buf[PATH_MAX], name[19] = "perf_trace_context";
1905 scripting_context->session = session;
1906 #if PY_MAJOR_VERSION < 3
1907 command_line = malloc((argc + 1) * sizeof(const char *));
1908 command_line[0] = script;
1909 for (i = 1; i < argc + 1; i++)
1910 command_line[i] = argv[i - 1];
1911 PyImport_AppendInittab(name, initperf_trace_context);
1913 command_line = malloc((argc + 1) * sizeof(wchar_t *));
1914 command_line[0] = Py_DecodeLocale(script, NULL);
1915 for (i = 1; i < argc + 1; i++)
1916 command_line[i] = Py_DecodeLocale(argv[i - 1], NULL);
1917 PyImport_AppendInittab(name, PyInit_perf_trace_context);
1921 #if PY_MAJOR_VERSION < 3
1922 PySys_SetArgv(argc + 1, (char **)command_line);
1924 PySys_SetArgv(argc + 1, command_line);
1927 fp = fopen(script, "r");
1929 sprintf(buf, "Can't open python script \"%s\"", script);
1935 err = PyRun_SimpleFile(fp, script);
1937 fprintf(stderr, "Error running python script %s\n", script);
1941 err = run_start_sub();
1943 fprintf(stderr, "Error starting python script %s\n", script);
1947 set_table_handlers(tables);
1949 if (tables->db_export_mode) {
1950 err = db_export__branch_types(&tables->dbe);
1955 _free_command_line(command_line, argc + 1);
1960 _free_command_line(command_line, argc + 1);
1965 static int python_flush_script(void)
1973 static int python_stop_script(void)
1975 struct tables *tables = &tables_global;
1977 try_call_object("trace_end", NULL);
1979 db_export__exit(&tables->dbe);
1981 Py_XDECREF(main_dict);
1982 Py_XDECREF(main_module);
1988 #ifdef HAVE_LIBTRACEEVENT
1989 static int python_generate_script(struct tep_handle *pevent, const char *outfile)
1991 int i, not_first, count, nr_events;
1992 struct tep_event **all_events;
1993 struct tep_event *event = NULL;
1994 struct tep_format_field *f;
1995 char fname[PATH_MAX];
1998 sprintf(fname, "%s.py", outfile);
1999 ofp = fopen(fname, "w");
2001 fprintf(stderr, "couldn't open %s\n", fname);
2004 fprintf(ofp, "# perf script event handlers, "
2005 "generated by perf script -g python\n");
2007 fprintf(ofp, "# Licensed under the terms of the GNU GPL"
2008 " License version 2\n\n");
2010 fprintf(ofp, "# The common_* event handler fields are the most useful "
2011 "fields common to\n");
2013 fprintf(ofp, "# all events. They don't necessarily correspond to "
2014 "the 'common_*' fields\n");
2016 fprintf(ofp, "# in the format files. Those fields not available as "
2017 "handler params can\n");
2019 fprintf(ofp, "# be retrieved using Python functions of the form "
2020 "common_*(context).\n");
2022 fprintf(ofp, "# See the perf-script-python Documentation for the list "
2023 "of available functions.\n\n");
2025 fprintf(ofp, "from __future__ import print_function\n\n");
2026 fprintf(ofp, "import os\n");
2027 fprintf(ofp, "import sys\n\n");
2029 fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
2030 fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
2031 fprintf(ofp, "\nfrom perf_trace_context import *\n");
2032 fprintf(ofp, "from Core import *\n\n\n");
2034 fprintf(ofp, "def trace_begin():\n");
2035 fprintf(ofp, "\tprint(\"in trace_begin\")\n\n");
2037 fprintf(ofp, "def trace_end():\n");
2038 fprintf(ofp, "\tprint(\"in trace_end\")\n\n");
2040 nr_events = tep_get_events_count(pevent);
2041 all_events = tep_list_events(pevent, TEP_EVENT_SORT_ID);
2043 for (i = 0; all_events && i < nr_events; i++) {
2044 event = all_events[i];
2045 fprintf(ofp, "def %s__%s(", event->system, event->name);
2046 fprintf(ofp, "event_name, ");
2047 fprintf(ofp, "context, ");
2048 fprintf(ofp, "common_cpu,\n");
2049 fprintf(ofp, "\tcommon_secs, ");
2050 fprintf(ofp, "common_nsecs, ");
2051 fprintf(ofp, "common_pid, ");
2052 fprintf(ofp, "common_comm,\n\t");
2053 fprintf(ofp, "common_callchain, ");
2058 for (f = event->format.fields; f; f = f->next) {
2061 if (++count % 5 == 0)
2062 fprintf(ofp, "\n\t");
2064 fprintf(ofp, "%s", f->name);
2068 if (++count % 5 == 0)
2069 fprintf(ofp, "\n\t\t");
2070 fprintf(ofp, "perf_sample_dict");
2072 fprintf(ofp, "):\n");
2074 fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
2075 "common_secs, common_nsecs,\n\t\t\t"
2076 "common_pid, common_comm)\n\n");
2078 fprintf(ofp, "\t\tprint(\"");
2083 for (f = event->format.fields; f; f = f->next) {
2086 if (count && count % 3 == 0) {
2087 fprintf(ofp, "\" \\\n\t\t\"");
2091 fprintf(ofp, "%s=", f->name);
2092 if (f->flags & TEP_FIELD_IS_STRING ||
2093 f->flags & TEP_FIELD_IS_FLAG ||
2094 f->flags & TEP_FIELD_IS_ARRAY ||
2095 f->flags & TEP_FIELD_IS_SYMBOLIC)
2096 fprintf(ofp, "%%s");
2097 else if (f->flags & TEP_FIELD_IS_SIGNED)
2098 fprintf(ofp, "%%d");
2100 fprintf(ofp, "%%u");
2103 fprintf(ofp, "\" %% \\\n\t\t(");
2108 for (f = event->format.fields; f; f = f->next) {
2112 if (++count % 5 == 0)
2113 fprintf(ofp, "\n\t\t");
2115 if (f->flags & TEP_FIELD_IS_FLAG) {
2116 if ((count - 1) % 5 != 0) {
2117 fprintf(ofp, "\n\t\t");
2120 fprintf(ofp, "flag_str(\"");
2121 fprintf(ofp, "%s__%s\", ", event->system,
2123 fprintf(ofp, "\"%s\", %s)", f->name,
2125 } else if (f->flags & TEP_FIELD_IS_SYMBOLIC) {
2126 if ((count - 1) % 5 != 0) {
2127 fprintf(ofp, "\n\t\t");
2130 fprintf(ofp, "symbol_str(\"");
2131 fprintf(ofp, "%s__%s\", ", event->system,
2133 fprintf(ofp, "\"%s\", %s)", f->name,
2136 fprintf(ofp, "%s", f->name);
2139 fprintf(ofp, "))\n\n");
2141 fprintf(ofp, "\t\tprint('Sample: {'+"
2142 "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
2144 fprintf(ofp, "\t\tfor node in common_callchain:");
2145 fprintf(ofp, "\n\t\t\tif 'sym' in node:");
2146 fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x] %%s%%s%%s%%s\" %% (");
2147 fprintf(ofp, "\n\t\t\t\t\tnode['ip'], node['sym']['name'],");
2148 fprintf(ofp, "\n\t\t\t\t\t\"+0x{:x}\".format(node['sym_off']) if 'sym_off' in node else \"\",");
2149 fprintf(ofp, "\n\t\t\t\t\t\" ({})\".format(node['dso']) if 'dso' in node else \"\",");
2150 fprintf(ofp, "\n\t\t\t\t\t\" \" + node['sym_srcline'] if 'sym_srcline' in node else \"\"))");
2151 fprintf(ofp, "\n\t\t\telse:");
2152 fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x]\" %% (node['ip']))\n\n");
2153 fprintf(ofp, "\t\tprint()\n\n");
2157 fprintf(ofp, "def trace_unhandled(event_name, context, "
2158 "event_fields_dict, perf_sample_dict):\n");
2160 fprintf(ofp, "\t\tprint(get_dict_as_string(event_fields_dict))\n");
2161 fprintf(ofp, "\t\tprint('Sample: {'+"
2162 "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
2164 fprintf(ofp, "def print_header("
2165 "event_name, cpu, secs, nsecs, pid, comm):\n"
2166 "\tprint(\"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
2167 "(event_name, cpu, secs, nsecs, pid, comm), end=\"\")\n\n");
2169 fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
2170 "\treturn delimiter.join"
2171 "(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
2175 fprintf(stderr, "generated Python script: %s\n", fname);
2180 static int python_generate_script(struct tep_handle *pevent __maybe_unused,
2181 const char *outfile __maybe_unused)
2183 fprintf(stderr, "Generating Python perf-script is not supported."
2184 " Install libtraceevent and rebuild perf to enable it.\n"
2185 "For example:\n # apt install libtraceevent-dev (ubuntu)"
2186 "\n # yum install libtraceevent-devel (Fedora)"
2192 struct scripting_ops python_scripting_ops = {
2194 .dirname = "python",
2195 .start_script = python_start_script,
2196 .flush_script = python_flush_script,
2197 .stop_script = python_stop_script,
2198 .process_event = python_process_event,
2199 .process_switch = python_process_switch,
2200 .process_auxtrace_error = python_process_auxtrace_error,
2201 .process_stat = python_process_stat,
2202 .process_stat_interval = python_process_stat_interval,
2203 .process_throttle = python_process_throttle,
2204 .generate_script = python_generate_script,