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>
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]";
394 if (map && map->dso) {
395 if (symbol_conf.show_kernel_path && map->dso->long_name)
396 dsoname = map->dso->long_name;
398 dsoname = map->dso->name;
404 static unsigned long get_offset(struct symbol *sym, struct addr_location *al)
406 unsigned long offset;
408 if (al->addr < sym->end)
409 offset = al->addr - sym->start;
411 offset = al->addr - al->map->start - sym->start;
416 static PyObject *python_process_callchain(struct perf_sample *sample,
418 struct addr_location *al)
422 pylist = PyList_New(0);
424 Py_FatalError("couldn't create Python list");
426 if (!symbol_conf.use_callchain || !sample->callchain)
429 if (thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
431 scripting_max_stack) != 0) {
432 pr_err("Failed to resolve callchain. Skipping\n");
435 callchain_cursor_commit(&callchain_cursor);
440 struct callchain_cursor_node *node;
441 node = callchain_cursor_current(&callchain_cursor);
445 pyelem = PyDict_New();
447 Py_FatalError("couldn't create Python dictionary");
450 pydict_set_item_string_decref(pyelem, "ip",
451 PyLong_FromUnsignedLongLong(node->ip));
454 PyObject *pysym = PyDict_New();
456 Py_FatalError("couldn't create Python dictionary");
457 pydict_set_item_string_decref(pysym, "start",
458 PyLong_FromUnsignedLongLong(node->ms.sym->start));
459 pydict_set_item_string_decref(pysym, "end",
460 PyLong_FromUnsignedLongLong(node->ms.sym->end));
461 pydict_set_item_string_decref(pysym, "binding",
462 _PyLong_FromLong(node->ms.sym->binding));
463 pydict_set_item_string_decref(pysym, "name",
464 _PyUnicode_FromStringAndSize(node->ms.sym->name,
465 node->ms.sym->namelen));
466 pydict_set_item_string_decref(pyelem, "sym", pysym);
469 struct map *map = node->ms.map;
470 struct addr_location node_al;
471 unsigned long offset;
473 node_al.addr = map->map_ip(map, node->ip);
475 offset = get_offset(node->ms.sym, &node_al);
477 pydict_set_item_string_decref(
479 PyLong_FromUnsignedLongLong(offset));
481 if (node->srcline && strcmp(":0", node->srcline)) {
482 pydict_set_item_string_decref(
483 pyelem, "sym_srcline",
484 _PyUnicode_FromString(node->srcline));
489 const char *dsoname = get_dsoname(node->ms.map);
491 pydict_set_item_string_decref(pyelem, "dso",
492 _PyUnicode_FromString(dsoname));
495 callchain_cursor_advance(&callchain_cursor);
496 PyList_Append(pylist, pyelem);
504 static PyObject *python_process_brstack(struct perf_sample *sample,
505 struct thread *thread)
507 struct branch_stack *br = sample->branch_stack;
508 struct branch_entry *entries = perf_sample__branch_entries(sample);
512 pylist = PyList_New(0);
514 Py_FatalError("couldn't create Python list");
519 for (i = 0; i < br->nr; i++) {
521 struct addr_location al;
524 pyelem = PyDict_New();
526 Py_FatalError("couldn't create Python dictionary");
528 pydict_set_item_string_decref(pyelem, "from",
529 PyLong_FromUnsignedLongLong(entries[i].from));
530 pydict_set_item_string_decref(pyelem, "to",
531 PyLong_FromUnsignedLongLong(entries[i].to));
532 pydict_set_item_string_decref(pyelem, "mispred",
533 PyBool_FromLong(entries[i].flags.mispred));
534 pydict_set_item_string_decref(pyelem, "predicted",
535 PyBool_FromLong(entries[i].flags.predicted));
536 pydict_set_item_string_decref(pyelem, "in_tx",
537 PyBool_FromLong(entries[i].flags.in_tx));
538 pydict_set_item_string_decref(pyelem, "abort",
539 PyBool_FromLong(entries[i].flags.abort));
540 pydict_set_item_string_decref(pyelem, "cycles",
541 PyLong_FromUnsignedLongLong(entries[i].flags.cycles));
543 thread__find_map_fb(thread, sample->cpumode,
544 entries[i].from, &al);
545 dsoname = get_dsoname(al.map);
546 pydict_set_item_string_decref(pyelem, "from_dsoname",
547 _PyUnicode_FromString(dsoname));
549 thread__find_map_fb(thread, sample->cpumode,
551 dsoname = get_dsoname(al.map);
552 pydict_set_item_string_decref(pyelem, "to_dsoname",
553 _PyUnicode_FromString(dsoname));
555 PyList_Append(pylist, pyelem);
563 static int get_symoff(struct symbol *sym, struct addr_location *al,
564 bool print_off, char *bf, int size)
566 unsigned long offset;
568 if (!sym || !sym->name[0])
569 return scnprintf(bf, size, "%s", "[unknown]");
572 return scnprintf(bf, size, "%s", sym->name);
574 offset = get_offset(sym, al);
576 return scnprintf(bf, size, "%s+0x%x", sym->name, offset);
579 static int get_br_mspred(struct branch_flags *flags, char *bf, int size)
581 if (!flags->mispred && !flags->predicted)
582 return scnprintf(bf, size, "%s", "-");
585 return scnprintf(bf, size, "%s", "M");
587 return scnprintf(bf, size, "%s", "P");
590 static PyObject *python_process_brstacksym(struct perf_sample *sample,
591 struct thread *thread)
593 struct branch_stack *br = sample->branch_stack;
594 struct branch_entry *entries = perf_sample__branch_entries(sample);
598 struct addr_location al;
600 pylist = PyList_New(0);
602 Py_FatalError("couldn't create Python list");
607 for (i = 0; i < br->nr; i++) {
610 pyelem = PyDict_New();
612 Py_FatalError("couldn't create Python dictionary");
614 thread__find_symbol_fb(thread, sample->cpumode,
615 entries[i].from, &al);
616 get_symoff(al.sym, &al, true, bf, sizeof(bf));
617 pydict_set_item_string_decref(pyelem, "from",
618 _PyUnicode_FromString(bf));
620 thread__find_symbol_fb(thread, sample->cpumode,
622 get_symoff(al.sym, &al, true, bf, sizeof(bf));
623 pydict_set_item_string_decref(pyelem, "to",
624 _PyUnicode_FromString(bf));
626 get_br_mspred(&entries[i].flags, bf, sizeof(bf));
627 pydict_set_item_string_decref(pyelem, "pred",
628 _PyUnicode_FromString(bf));
630 if (entries[i].flags.in_tx) {
631 pydict_set_item_string_decref(pyelem, "in_tx",
632 _PyUnicode_FromString("X"));
634 pydict_set_item_string_decref(pyelem, "in_tx",
635 _PyUnicode_FromString("-"));
638 if (entries[i].flags.abort) {
639 pydict_set_item_string_decref(pyelem, "abort",
640 _PyUnicode_FromString("A"));
642 pydict_set_item_string_decref(pyelem, "abort",
643 _PyUnicode_FromString("-"));
646 PyList_Append(pylist, pyelem);
654 static PyObject *get_sample_value_as_tuple(struct sample_read_value *value,
661 Py_FatalError("couldn't create Python tuple");
662 PyTuple_SetItem(t, 0, PyLong_FromUnsignedLongLong(value->id));
663 PyTuple_SetItem(t, 1, PyLong_FromUnsignedLongLong(value->value));
664 if (read_format & PERF_FORMAT_LOST)
665 PyTuple_SetItem(t, 2, PyLong_FromUnsignedLongLong(value->lost));
670 static void set_sample_read_in_dict(PyObject *dict_sample,
671 struct perf_sample *sample,
674 u64 read_format = evsel->core.attr.read_format;
678 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
679 pydict_set_item_string_decref(dict_sample, "time_enabled",
680 PyLong_FromUnsignedLongLong(sample->read.time_enabled));
683 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
684 pydict_set_item_string_decref(dict_sample, "time_running",
685 PyLong_FromUnsignedLongLong(sample->read.time_running));
688 if (read_format & PERF_FORMAT_GROUP)
689 values = PyList_New(sample->read.group.nr);
691 values = PyList_New(1);
694 Py_FatalError("couldn't create Python list");
696 if (read_format & PERF_FORMAT_GROUP) {
697 struct sample_read_value *v = sample->read.group.values;
700 sample_read_group__for_each(v, sample->read.group.nr, read_format) {
701 PyObject *t = get_sample_value_as_tuple(v, read_format);
702 PyList_SET_ITEM(values, i, t);
706 PyObject *t = get_sample_value_as_tuple(&sample->read.one,
708 PyList_SET_ITEM(values, 0, t);
710 pydict_set_item_string_decref(dict_sample, "values", values);
713 static void set_sample_datasrc_in_dict(PyObject *dict,
714 struct perf_sample *sample)
716 struct mem_info mi = { .data_src.val = sample->data_src };
719 pydict_set_item_string_decref(dict, "datasrc",
720 PyLong_FromUnsignedLongLong(sample->data_src));
722 perf_script__meminfo_scnprintf(decode, 100, &mi);
724 pydict_set_item_string_decref(dict, "datasrc_decode",
725 _PyUnicode_FromString(decode));
728 static void regs_map(struct regs_dump *regs, uint64_t mask, const char *arch, char *bf, int size)
730 unsigned int i = 0, r;
735 if (!regs || !regs->regs)
738 for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
739 u64 val = regs->regs[i++];
741 printed += scnprintf(bf + printed, size - printed,
742 "%5s:0x%" PRIx64 " ",
743 perf_reg_name(r, arch), val);
747 static void set_regs_in_dict(PyObject *dict,
748 struct perf_sample *sample,
751 struct perf_event_attr *attr = &evsel->core.attr;
752 const char *arch = perf_env__arch(evsel__env(evsel));
755 * Here value 28 is a constant size which can be used to print
756 * one register value and its corresponds to:
757 * 16 chars is to specify 64 bit register in hexadecimal.
758 * 2 chars is for appending "0x" to the hexadecimal value and
759 * 10 chars is for register name.
761 int size = __sw_hweight64(attr->sample_regs_intr) * 28;
764 regs_map(&sample->intr_regs, attr->sample_regs_intr, arch, bf, sizeof(bf));
766 pydict_set_item_string_decref(dict, "iregs",
767 _PyUnicode_FromString(bf));
769 regs_map(&sample->user_regs, attr->sample_regs_user, arch, bf, sizeof(bf));
771 pydict_set_item_string_decref(dict, "uregs",
772 _PyUnicode_FromString(bf));
775 static void set_sym_in_dict(PyObject *dict, struct addr_location *al,
776 const char *dso_field, const char *dso_bid_field,
777 const char *dso_map_start, const char *dso_map_end,
778 const char *sym_field, const char *symoff_field)
780 char sbuild_id[SBUILD_ID_SIZE];
783 pydict_set_item_string_decref(dict, dso_field,
784 _PyUnicode_FromString(al->map->dso->name));
785 build_id__sprintf(&al->map->dso->bid, sbuild_id);
786 pydict_set_item_string_decref(dict, dso_bid_field,
787 _PyUnicode_FromString(sbuild_id));
788 pydict_set_item_string_decref(dict, dso_map_start,
789 PyLong_FromUnsignedLong(al->map->start));
790 pydict_set_item_string_decref(dict, dso_map_end,
791 PyLong_FromUnsignedLong(al->map->end));
794 pydict_set_item_string_decref(dict, sym_field,
795 _PyUnicode_FromString(al->sym->name));
796 pydict_set_item_string_decref(dict, symoff_field,
797 PyLong_FromUnsignedLong(get_offset(al->sym, al)));
801 static void set_sample_flags(PyObject *dict, u32 flags)
803 const char *ch = PERF_IP_FLAG_CHARS;
806 for (p = str; *ch; ch++, flags >>= 1) {
811 pydict_set_item_string_decref(dict, "flags", _PyUnicode_FromString(str));
814 static void python_process_sample_flags(struct perf_sample *sample, PyObject *dict_sample)
816 char flags_disp[SAMPLE_FLAGS_BUF_SIZE];
818 set_sample_flags(dict_sample, sample->flags);
819 perf_sample__sprintf_flags(sample->flags, flags_disp, sizeof(flags_disp));
820 pydict_set_item_string_decref(dict_sample, "flags_disp",
821 _PyUnicode_FromString(flags_disp));
824 static PyObject *get_perf_sample_dict(struct perf_sample *sample,
826 struct addr_location *al,
827 struct addr_location *addr_al,
830 PyObject *dict, *dict_sample, *brstack, *brstacksym;
834 Py_FatalError("couldn't create Python dictionary");
836 dict_sample = PyDict_New();
838 Py_FatalError("couldn't create Python dictionary");
840 pydict_set_item_string_decref(dict, "ev_name", _PyUnicode_FromString(evsel__name(evsel)));
841 pydict_set_item_string_decref(dict, "attr", _PyBytes_FromStringAndSize((const char *)&evsel->core.attr, sizeof(evsel->core.attr)));
843 pydict_set_item_string_decref(dict_sample, "pid",
844 _PyLong_FromLong(sample->pid));
845 pydict_set_item_string_decref(dict_sample, "tid",
846 _PyLong_FromLong(sample->tid));
847 pydict_set_item_string_decref(dict_sample, "cpu",
848 _PyLong_FromLong(sample->cpu));
849 pydict_set_item_string_decref(dict_sample, "ip",
850 PyLong_FromUnsignedLongLong(sample->ip));
851 pydict_set_item_string_decref(dict_sample, "time",
852 PyLong_FromUnsignedLongLong(sample->time));
853 pydict_set_item_string_decref(dict_sample, "period",
854 PyLong_FromUnsignedLongLong(sample->period));
855 pydict_set_item_string_decref(dict_sample, "phys_addr",
856 PyLong_FromUnsignedLongLong(sample->phys_addr));
857 pydict_set_item_string_decref(dict_sample, "addr",
858 PyLong_FromUnsignedLongLong(sample->addr));
859 set_sample_read_in_dict(dict_sample, sample, evsel);
860 pydict_set_item_string_decref(dict_sample, "weight",
861 PyLong_FromUnsignedLongLong(sample->weight));
862 pydict_set_item_string_decref(dict_sample, "transaction",
863 PyLong_FromUnsignedLongLong(sample->transaction));
864 set_sample_datasrc_in_dict(dict_sample, sample);
865 pydict_set_item_string_decref(dict, "sample", dict_sample);
867 pydict_set_item_string_decref(dict, "raw_buf", _PyBytes_FromStringAndSize(
868 (const char *)sample->raw_data, sample->raw_size));
869 pydict_set_item_string_decref(dict, "comm",
870 _PyUnicode_FromString(thread__comm_str(al->thread)));
871 set_sym_in_dict(dict, al, "dso", "dso_bid", "dso_map_start", "dso_map_end",
874 pydict_set_item_string_decref(dict, "callchain", callchain);
876 brstack = python_process_brstack(sample, al->thread);
877 pydict_set_item_string_decref(dict, "brstack", brstack);
879 brstacksym = python_process_brstacksym(sample, al->thread);
880 pydict_set_item_string_decref(dict, "brstacksym", brstacksym);
882 if (sample->machine_pid) {
883 pydict_set_item_string_decref(dict_sample, "machine_pid",
884 _PyLong_FromLong(sample->machine_pid));
885 pydict_set_item_string_decref(dict_sample, "vcpu",
886 _PyLong_FromLong(sample->vcpu));
889 pydict_set_item_string_decref(dict_sample, "cpumode",
890 _PyLong_FromLong((unsigned long)sample->cpumode));
893 pydict_set_item_string_decref(dict_sample, "addr_correlates_sym",
895 set_sym_in_dict(dict_sample, addr_al, "addr_dso", "addr_dso_bid",
896 "addr_dso_map_start", "addr_dso_map_end",
897 "addr_symbol", "addr_symoff");
901 python_process_sample_flags(sample, dict_sample);
903 /* Instructions per cycle (IPC) */
904 if (sample->insn_cnt && sample->cyc_cnt) {
905 pydict_set_item_string_decref(dict_sample, "insn_cnt",
906 PyLong_FromUnsignedLongLong(sample->insn_cnt));
907 pydict_set_item_string_decref(dict_sample, "cyc_cnt",
908 PyLong_FromUnsignedLongLong(sample->cyc_cnt));
911 set_regs_in_dict(dict, sample, evsel);
916 #ifdef HAVE_LIBTRACEEVENT
917 static void python_process_tracepoint(struct perf_sample *sample,
919 struct addr_location *al,
920 struct addr_location *addr_al)
922 struct tep_event *event = evsel->tp_format;
923 PyObject *handler, *context, *t, *obj = NULL, *callchain;
924 PyObject *dict = NULL, *all_entries_dict = NULL;
925 static char handler_name[256];
926 struct tep_format_field *field;
930 int cpu = sample->cpu;
931 void *data = sample->raw_data;
932 unsigned long long nsecs = sample->time;
933 const char *comm = thread__comm_str(al->thread);
934 const char *default_handler_name = "trace_unhandled";
937 snprintf(handler_name, sizeof(handler_name),
938 "ug! no event found for type %" PRIu64, (u64)evsel->core.attr.config);
939 Py_FatalError(handler_name);
942 pid = raw_field_value(event, "common_pid", data);
944 sprintf(handler_name, "%s__%s", event->system, event->name);
946 if (!__test_and_set_bit(event->id, events_defined))
947 define_event_symbols(event, handler_name, event->print_fmt.args);
949 handler = get_handler(handler_name);
951 handler = get_handler(default_handler_name);
956 Py_FatalError("couldn't create Python dict");
959 t = PyTuple_New(MAX_FIELDS);
961 Py_FatalError("couldn't create Python tuple");
964 s = nsecs / NSEC_PER_SEC;
965 ns = nsecs - s * NSEC_PER_SEC;
967 context = _PyCapsule_New(scripting_context, NULL, NULL);
969 PyTuple_SetItem(t, n++, _PyUnicode_FromString(handler_name));
970 PyTuple_SetItem(t, n++, context);
973 callchain = python_process_callchain(sample, evsel, al);
974 /* Need an additional reference for the perf_sample dict */
975 Py_INCREF(callchain);
978 PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
979 PyTuple_SetItem(t, n++, _PyLong_FromLong(s));
980 PyTuple_SetItem(t, n++, _PyLong_FromLong(ns));
981 PyTuple_SetItem(t, n++, _PyLong_FromLong(pid));
982 PyTuple_SetItem(t, n++, _PyUnicode_FromString(comm));
983 PyTuple_SetItem(t, n++, callchain);
985 pydict_set_item_string_decref(dict, "common_cpu", _PyLong_FromLong(cpu));
986 pydict_set_item_string_decref(dict, "common_s", _PyLong_FromLong(s));
987 pydict_set_item_string_decref(dict, "common_ns", _PyLong_FromLong(ns));
988 pydict_set_item_string_decref(dict, "common_pid", _PyLong_FromLong(pid));
989 pydict_set_item_string_decref(dict, "common_comm", _PyUnicode_FromString(comm));
990 pydict_set_item_string_decref(dict, "common_callchain", callchain);
992 for (field = event->format.fields; field; field = field->next) {
993 unsigned int offset, len;
994 unsigned long long val;
996 if (field->flags & TEP_FIELD_IS_ARRAY) {
997 offset = field->offset;
999 if (field->flags & TEP_FIELD_IS_DYNAMIC) {
1000 val = tep_read_number(scripting_context->pevent,
1001 data + offset, len);
1005 if (tep_field_is_relative(field->flags))
1006 offset += field->offset + field->size;
1008 if (field->flags & TEP_FIELD_IS_STRING &&
1009 is_printable_array(data + offset, len)) {
1010 obj = _PyUnicode_FromString((char *) data + offset);
1012 obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
1013 field->flags &= ~TEP_FIELD_IS_STRING;
1015 } else { /* FIELD_IS_NUMERIC */
1016 obj = get_field_numeric_entry(event, field, data);
1019 PyTuple_SetItem(t, n++, obj);
1021 pydict_set_item_string_decref(dict, field->name, obj);
1026 PyTuple_SetItem(t, n++, dict);
1028 if (get_argument_count(handler) == (int) n + 1) {
1029 all_entries_dict = get_perf_sample_dict(sample, evsel, al, addr_al,
1031 PyTuple_SetItem(t, n++, all_entries_dict);
1033 Py_DECREF(callchain);
1036 if (_PyTuple_Resize(&t, n) == -1)
1037 Py_FatalError("error resizing Python tuple");
1040 call_object(handler, t, handler_name);
1042 call_object(handler, t, default_handler_name);
1047 static void python_process_tracepoint(struct perf_sample *sample __maybe_unused,
1048 struct evsel *evsel __maybe_unused,
1049 struct addr_location *al __maybe_unused,
1050 struct addr_location *addr_al __maybe_unused)
1052 fprintf(stderr, "Tracepoint events are not supported because "
1053 "perf is not linked with libtraceevent.\n");
1057 static PyObject *tuple_new(unsigned int sz)
1061 t = PyTuple_New(sz);
1063 Py_FatalError("couldn't create Python tuple");
1067 static int tuple_set_s64(PyObject *t, unsigned int pos, s64 val)
1069 #if BITS_PER_LONG == 64
1070 return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
1072 #if BITS_PER_LONG == 32
1073 return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
1078 * Databases support only signed 64-bit numbers, so even though we are
1079 * exporting a u64, it must be as s64.
1081 #define tuple_set_d64 tuple_set_s64
1083 static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
1085 #if BITS_PER_LONG == 64
1086 return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
1088 #if BITS_PER_LONG == 32
1089 return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLongLong(val));
1093 static int tuple_set_u32(PyObject *t, unsigned int pos, u32 val)
1095 return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
1098 static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
1100 return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
1103 static int tuple_set_bool(PyObject *t, unsigned int pos, bool val)
1105 return PyTuple_SetItem(t, pos, PyBool_FromLong(val));
1108 static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
1110 return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
1113 static int tuple_set_bytes(PyObject *t, unsigned int pos, void *bytes,
1116 return PyTuple_SetItem(t, pos, _PyBytes_FromStringAndSize(bytes, sz));
1119 static int python_export_evsel(struct db_export *dbe, struct evsel *evsel)
1121 struct tables *tables = container_of(dbe, struct tables, dbe);
1126 tuple_set_d64(t, 0, evsel->db_id);
1127 tuple_set_string(t, 1, evsel__name(evsel));
1129 call_object(tables->evsel_handler, t, "evsel_table");
1136 static int python_export_machine(struct db_export *dbe,
1137 struct machine *machine)
1139 struct tables *tables = container_of(dbe, struct tables, dbe);
1144 tuple_set_d64(t, 0, machine->db_id);
1145 tuple_set_s32(t, 1, machine->pid);
1146 tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
1148 call_object(tables->machine_handler, t, "machine_table");
1155 static int python_export_thread(struct db_export *dbe, struct thread *thread,
1156 u64 main_thread_db_id, struct machine *machine)
1158 struct tables *tables = container_of(dbe, struct tables, dbe);
1163 tuple_set_d64(t, 0, thread->db_id);
1164 tuple_set_d64(t, 1, machine->db_id);
1165 tuple_set_d64(t, 2, main_thread_db_id);
1166 tuple_set_s32(t, 3, thread->pid_);
1167 tuple_set_s32(t, 4, thread->tid);
1169 call_object(tables->thread_handler, t, "thread_table");
1176 static int python_export_comm(struct db_export *dbe, struct comm *comm,
1177 struct thread *thread)
1179 struct tables *tables = container_of(dbe, struct tables, dbe);
1184 tuple_set_d64(t, 0, comm->db_id);
1185 tuple_set_string(t, 1, comm__str(comm));
1186 tuple_set_d64(t, 2, thread->db_id);
1187 tuple_set_d64(t, 3, comm->start);
1188 tuple_set_s32(t, 4, comm->exec);
1190 call_object(tables->comm_handler, t, "comm_table");
1197 static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
1198 struct comm *comm, struct thread *thread)
1200 struct tables *tables = container_of(dbe, struct tables, dbe);
1205 tuple_set_d64(t, 0, db_id);
1206 tuple_set_d64(t, 1, comm->db_id);
1207 tuple_set_d64(t, 2, thread->db_id);
1209 call_object(tables->comm_thread_handler, t, "comm_thread_table");
1216 static int python_export_dso(struct db_export *dbe, struct dso *dso,
1217 struct machine *machine)
1219 struct tables *tables = container_of(dbe, struct tables, dbe);
1220 char sbuild_id[SBUILD_ID_SIZE];
1223 build_id__sprintf(&dso->bid, sbuild_id);
1227 tuple_set_d64(t, 0, dso->db_id);
1228 tuple_set_d64(t, 1, machine->db_id);
1229 tuple_set_string(t, 2, dso->short_name);
1230 tuple_set_string(t, 3, dso->long_name);
1231 tuple_set_string(t, 4, sbuild_id);
1233 call_object(tables->dso_handler, t, "dso_table");
1240 static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
1243 struct tables *tables = container_of(dbe, struct tables, dbe);
1244 u64 *sym_db_id = symbol__priv(sym);
1249 tuple_set_d64(t, 0, *sym_db_id);
1250 tuple_set_d64(t, 1, dso->db_id);
1251 tuple_set_d64(t, 2, sym->start);
1252 tuple_set_d64(t, 3, sym->end);
1253 tuple_set_s32(t, 4, sym->binding);
1254 tuple_set_string(t, 5, sym->name);
1256 call_object(tables->symbol_handler, t, "symbol_table");
1263 static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
1266 struct tables *tables = container_of(dbe, struct tables, dbe);
1271 tuple_set_s32(t, 0, branch_type);
1272 tuple_set_string(t, 1, name);
1274 call_object(tables->branch_type_handler, t, "branch_type_table");
1281 static void python_export_sample_table(struct db_export *dbe,
1282 struct export_sample *es)
1284 struct tables *tables = container_of(dbe, struct tables, dbe);
1289 tuple_set_d64(t, 0, es->db_id);
1290 tuple_set_d64(t, 1, es->evsel->db_id);
1291 tuple_set_d64(t, 2, es->al->maps->machine->db_id);
1292 tuple_set_d64(t, 3, es->al->thread->db_id);
1293 tuple_set_d64(t, 4, es->comm_db_id);
1294 tuple_set_d64(t, 5, es->dso_db_id);
1295 tuple_set_d64(t, 6, es->sym_db_id);
1296 tuple_set_d64(t, 7, es->offset);
1297 tuple_set_d64(t, 8, es->sample->ip);
1298 tuple_set_d64(t, 9, es->sample->time);
1299 tuple_set_s32(t, 10, es->sample->cpu);
1300 tuple_set_d64(t, 11, es->addr_dso_db_id);
1301 tuple_set_d64(t, 12, es->addr_sym_db_id);
1302 tuple_set_d64(t, 13, es->addr_offset);
1303 tuple_set_d64(t, 14, es->sample->addr);
1304 tuple_set_d64(t, 15, es->sample->period);
1305 tuple_set_d64(t, 16, es->sample->weight);
1306 tuple_set_d64(t, 17, es->sample->transaction);
1307 tuple_set_d64(t, 18, es->sample->data_src);
1308 tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
1309 tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
1310 tuple_set_d64(t, 21, es->call_path_id);
1311 tuple_set_d64(t, 22, es->sample->insn_cnt);
1312 tuple_set_d64(t, 23, es->sample->cyc_cnt);
1313 tuple_set_s32(t, 24, es->sample->flags);
1315 call_object(tables->sample_handler, t, "sample_table");
1320 static void python_export_synth(struct db_export *dbe, struct export_sample *es)
1322 struct tables *tables = container_of(dbe, struct tables, dbe);
1327 tuple_set_d64(t, 0, es->db_id);
1328 tuple_set_d64(t, 1, es->evsel->core.attr.config);
1329 tuple_set_bytes(t, 2, es->sample->raw_data, es->sample->raw_size);
1331 call_object(tables->synth_handler, t, "synth_data");
1336 static int python_export_sample(struct db_export *dbe,
1337 struct export_sample *es)
1339 struct tables *tables = container_of(dbe, struct tables, dbe);
1341 python_export_sample_table(dbe, es);
1343 if (es->evsel->core.attr.type == PERF_TYPE_SYNTH && tables->synth_handler)
1344 python_export_synth(dbe, es);
1349 static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
1351 struct tables *tables = container_of(dbe, struct tables, dbe);
1353 u64 parent_db_id, sym_db_id;
1355 parent_db_id = cp->parent ? cp->parent->db_id : 0;
1356 sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
1360 tuple_set_d64(t, 0, cp->db_id);
1361 tuple_set_d64(t, 1, parent_db_id);
1362 tuple_set_d64(t, 2, sym_db_id);
1363 tuple_set_d64(t, 3, cp->ip);
1365 call_object(tables->call_path_handler, t, "call_path_table");
1372 static int python_export_call_return(struct db_export *dbe,
1373 struct call_return *cr)
1375 struct tables *tables = container_of(dbe, struct tables, dbe);
1376 u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
1381 tuple_set_d64(t, 0, cr->db_id);
1382 tuple_set_d64(t, 1, cr->thread->db_id);
1383 tuple_set_d64(t, 2, comm_db_id);
1384 tuple_set_d64(t, 3, cr->cp->db_id);
1385 tuple_set_d64(t, 4, cr->call_time);
1386 tuple_set_d64(t, 5, cr->return_time);
1387 tuple_set_d64(t, 6, cr->branch_count);
1388 tuple_set_d64(t, 7, cr->call_ref);
1389 tuple_set_d64(t, 8, cr->return_ref);
1390 tuple_set_d64(t, 9, cr->cp->parent->db_id);
1391 tuple_set_s32(t, 10, cr->flags);
1392 tuple_set_d64(t, 11, cr->parent_db_id);
1393 tuple_set_d64(t, 12, cr->insn_count);
1394 tuple_set_d64(t, 13, cr->cyc_count);
1396 call_object(tables->call_return_handler, t, "call_return_table");
1403 static int python_export_context_switch(struct db_export *dbe, u64 db_id,
1404 struct machine *machine,
1405 struct perf_sample *sample,
1406 u64 th_out_id, u64 comm_out_id,
1407 u64 th_in_id, u64 comm_in_id, int flags)
1409 struct tables *tables = container_of(dbe, struct tables, dbe);
1414 tuple_set_d64(t, 0, db_id);
1415 tuple_set_d64(t, 1, machine->db_id);
1416 tuple_set_d64(t, 2, sample->time);
1417 tuple_set_s32(t, 3, sample->cpu);
1418 tuple_set_d64(t, 4, th_out_id);
1419 tuple_set_d64(t, 5, comm_out_id);
1420 tuple_set_d64(t, 6, th_in_id);
1421 tuple_set_d64(t, 7, comm_in_id);
1422 tuple_set_s32(t, 8, flags);
1424 call_object(tables->context_switch_handler, t, "context_switch");
1431 static int python_process_call_return(struct call_return *cr, u64 *parent_db_id,
1434 struct db_export *dbe = data;
1436 return db_export__call_return(dbe, cr, parent_db_id);
1439 static void python_process_general_event(struct perf_sample *sample,
1440 struct evsel *evsel,
1441 struct addr_location *al,
1442 struct addr_location *addr_al)
1444 PyObject *handler, *t, *dict, *callchain;
1445 static char handler_name[64];
1448 snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
1450 handler = get_handler(handler_name);
1455 * Use the MAX_FIELDS to make the function expandable, though
1456 * currently there is only one item for the tuple.
1458 t = PyTuple_New(MAX_FIELDS);
1460 Py_FatalError("couldn't create Python tuple");
1463 callchain = python_process_callchain(sample, evsel, al);
1464 dict = get_perf_sample_dict(sample, evsel, al, addr_al, callchain);
1466 PyTuple_SetItem(t, n++, dict);
1467 if (_PyTuple_Resize(&t, n) == -1)
1468 Py_FatalError("error resizing Python tuple");
1470 call_object(handler, t, handler_name);
1475 static void python_process_event(union perf_event *event,
1476 struct perf_sample *sample,
1477 struct evsel *evsel,
1478 struct addr_location *al,
1479 struct addr_location *addr_al)
1481 struct tables *tables = &tables_global;
1483 scripting_context__update(scripting_context, event, sample, evsel, al, addr_al);
1485 switch (evsel->core.attr.type) {
1486 case PERF_TYPE_TRACEPOINT:
1487 python_process_tracepoint(sample, evsel, al, addr_al);
1489 /* Reserve for future process_hw/sw/raw APIs */
1491 if (tables->db_export_mode)
1492 db_export__sample(&tables->dbe, event, sample, evsel, al, addr_al);
1494 python_process_general_event(sample, evsel, al, addr_al);
1498 static void python_process_throttle(union perf_event *event,
1499 struct perf_sample *sample,
1500 struct machine *machine)
1502 const char *handler_name;
1503 PyObject *handler, *t;
1505 if (event->header.type == PERF_RECORD_THROTTLE)
1506 handler_name = "throttle";
1508 handler_name = "unthrottle";
1509 handler = get_handler(handler_name);
1517 tuple_set_u64(t, 0, event->throttle.time);
1518 tuple_set_u64(t, 1, event->throttle.id);
1519 tuple_set_u64(t, 2, event->throttle.stream_id);
1520 tuple_set_s32(t, 3, sample->cpu);
1521 tuple_set_s32(t, 4, sample->pid);
1522 tuple_set_s32(t, 5, sample->tid);
1524 call_object(handler, t, handler_name);
1529 static void python_do_process_switch(union perf_event *event,
1530 struct perf_sample *sample,
1531 struct machine *machine)
1533 const char *handler_name = "context_switch";
1534 bool out = event->header.misc & PERF_RECORD_MISC_SWITCH_OUT;
1535 bool out_preempt = out && (event->header.misc & PERF_RECORD_MISC_SWITCH_OUT_PREEMPT);
1536 pid_t np_pid = -1, np_tid = -1;
1537 PyObject *handler, *t;
1539 handler = get_handler(handler_name);
1543 if (event->header.type == PERF_RECORD_SWITCH_CPU_WIDE) {
1544 np_pid = event->context_switch.next_prev_pid;
1545 np_tid = event->context_switch.next_prev_tid;
1552 tuple_set_u64(t, 0, sample->time);
1553 tuple_set_s32(t, 1, sample->cpu);
1554 tuple_set_s32(t, 2, sample->pid);
1555 tuple_set_s32(t, 3, sample->tid);
1556 tuple_set_s32(t, 4, np_pid);
1557 tuple_set_s32(t, 5, np_tid);
1558 tuple_set_s32(t, 6, machine->pid);
1559 tuple_set_bool(t, 7, out);
1560 tuple_set_bool(t, 8, out_preempt);
1561 tuple_set_s32(t, 9, sample->machine_pid);
1562 tuple_set_s32(t, 10, sample->vcpu);
1564 call_object(handler, t, handler_name);
1569 static void python_process_switch(union perf_event *event,
1570 struct perf_sample *sample,
1571 struct machine *machine)
1573 struct tables *tables = &tables_global;
1575 if (tables->db_export_mode)
1576 db_export__switch(&tables->dbe, event, sample, machine);
1578 python_do_process_switch(event, sample, machine);
1581 static void python_process_auxtrace_error(struct perf_session *session __maybe_unused,
1582 union perf_event *event)
1584 struct perf_record_auxtrace_error *e = &event->auxtrace_error;
1585 u8 cpumode = e->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
1586 const char *handler_name = "auxtrace_error";
1587 unsigned long long tm = e->time;
1588 const char *msg = e->msg;
1589 PyObject *handler, *t;
1591 handler = get_handler(handler_name);
1597 msg = (const char *)&e->time;
1602 tuple_set_u32(t, 0, e->type);
1603 tuple_set_u32(t, 1, e->code);
1604 tuple_set_s32(t, 2, e->cpu);
1605 tuple_set_s32(t, 3, e->pid);
1606 tuple_set_s32(t, 4, e->tid);
1607 tuple_set_u64(t, 5, e->ip);
1608 tuple_set_u64(t, 6, tm);
1609 tuple_set_string(t, 7, msg);
1610 tuple_set_u32(t, 8, cpumode);
1611 tuple_set_s32(t, 9, e->machine_pid);
1612 tuple_set_s32(t, 10, e->vcpu);
1614 call_object(handler, t, handler_name);
1619 static void get_handler_name(char *str, size_t size,
1620 struct evsel *evsel)
1624 scnprintf(str, size, "stat__%s", evsel__name(evsel));
1626 while ((p = strchr(p, ':'))) {
1633 process_stat(struct evsel *counter, struct perf_cpu cpu, int thread, u64 tstamp,
1634 struct perf_counts_values *count)
1636 PyObject *handler, *t;
1637 static char handler_name[256];
1640 t = PyTuple_New(MAX_FIELDS);
1642 Py_FatalError("couldn't create Python tuple");
1644 get_handler_name(handler_name, sizeof(handler_name),
1647 handler = get_handler(handler_name);
1649 pr_debug("can't find python handler %s\n", handler_name);
1653 PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu.cpu));
1654 PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
1656 tuple_set_u64(t, n++, tstamp);
1657 tuple_set_u64(t, n++, count->val);
1658 tuple_set_u64(t, n++, count->ena);
1659 tuple_set_u64(t, n++, count->run);
1661 if (_PyTuple_Resize(&t, n) == -1)
1662 Py_FatalError("error resizing Python tuple");
1664 call_object(handler, t, handler_name);
1669 static void python_process_stat(struct perf_stat_config *config,
1670 struct evsel *counter, u64 tstamp)
1672 struct perf_thread_map *threads = counter->core.threads;
1673 struct perf_cpu_map *cpus = counter->core.cpus;
1676 for (thread = 0; thread < perf_thread_map__nr(threads); thread++) {
1677 for (cpu = 0; cpu < perf_cpu_map__nr(cpus); cpu++) {
1678 process_stat(counter, perf_cpu_map__cpu(cpus, cpu),
1679 perf_thread_map__pid(threads, thread), tstamp,
1680 perf_counts(counter->counts, cpu, thread));
1685 static void python_process_stat_interval(u64 tstamp)
1687 PyObject *handler, *t;
1688 static const char handler_name[] = "stat__interval";
1691 t = PyTuple_New(MAX_FIELDS);
1693 Py_FatalError("couldn't create Python tuple");
1695 handler = get_handler(handler_name);
1697 pr_debug("can't find python handler %s\n", handler_name);
1701 tuple_set_u64(t, n++, tstamp);
1703 if (_PyTuple_Resize(&t, n) == -1)
1704 Py_FatalError("error resizing Python tuple");
1706 call_object(handler, t, handler_name);
1711 static int perf_script_context_init(void)
1713 PyObject *perf_script_context;
1714 PyObject *perf_trace_context;
1718 perf_trace_context = PyImport_AddModule("perf_trace_context");
1719 if (!perf_trace_context)
1721 dict = PyModule_GetDict(perf_trace_context);
1725 perf_script_context = _PyCapsule_New(scripting_context, NULL, NULL);
1726 if (!perf_script_context)
1729 ret = PyDict_SetItemString(dict, "perf_script_context", perf_script_context);
1731 ret = PyDict_SetItemString(main_dict, "perf_script_context", perf_script_context);
1732 Py_DECREF(perf_script_context);
1736 static int run_start_sub(void)
1738 main_module = PyImport_AddModule("__main__");
1739 if (main_module == NULL)
1741 Py_INCREF(main_module);
1743 main_dict = PyModule_GetDict(main_module);
1744 if (main_dict == NULL)
1746 Py_INCREF(main_dict);
1748 if (perf_script_context_init())
1751 try_call_object("trace_begin", NULL);
1756 Py_XDECREF(main_dict);
1757 Py_XDECREF(main_module);
1761 #define SET_TABLE_HANDLER_(name, handler_name, table_name) do { \
1762 tables->handler_name = get_handler(#table_name); \
1763 if (tables->handler_name) \
1764 tables->dbe.export_ ## name = python_export_ ## name; \
1767 #define SET_TABLE_HANDLER(name) \
1768 SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
1770 static void set_table_handlers(struct tables *tables)
1772 const char *perf_db_export_mode = "perf_db_export_mode";
1773 const char *perf_db_export_calls = "perf_db_export_calls";
1774 const char *perf_db_export_callchains = "perf_db_export_callchains";
1775 PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
1776 bool export_calls = false;
1777 bool export_callchains = false;
1780 memset(tables, 0, sizeof(struct tables));
1781 if (db_export__init(&tables->dbe))
1782 Py_FatalError("failed to initialize export");
1784 db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
1785 if (!db_export_mode)
1788 ret = PyObject_IsTrue(db_export_mode);
1790 handler_call_die(perf_db_export_mode);
1794 /* handle export calls */
1795 tables->dbe.crp = NULL;
1796 db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
1797 if (db_export_calls) {
1798 ret = PyObject_IsTrue(db_export_calls);
1800 handler_call_die(perf_db_export_calls);
1801 export_calls = !!ret;
1806 call_return_processor__new(python_process_call_return,
1808 if (!tables->dbe.crp)
1809 Py_FatalError("failed to create calls processor");
1812 /* handle export callchains */
1813 tables->dbe.cpr = NULL;
1814 db_export_callchains = PyDict_GetItemString(main_dict,
1815 perf_db_export_callchains);
1816 if (db_export_callchains) {
1817 ret = PyObject_IsTrue(db_export_callchains);
1819 handler_call_die(perf_db_export_callchains);
1820 export_callchains = !!ret;
1823 if (export_callchains) {
1825 * Attempt to use the call path root from the call return
1826 * processor, if the call return processor is in use. Otherwise,
1827 * we allocate a new call path root. This prevents exporting
1828 * duplicate call path ids when both are in use simultaneously.
1830 if (tables->dbe.crp)
1831 tables->dbe.cpr = tables->dbe.crp->cpr;
1833 tables->dbe.cpr = call_path_root__new();
1835 if (!tables->dbe.cpr)
1836 Py_FatalError("failed to create call path root");
1839 tables->db_export_mode = true;
1841 * Reserve per symbol space for symbol->db_id via symbol__priv()
1843 symbol_conf.priv_size = sizeof(u64);
1845 SET_TABLE_HANDLER(evsel);
1846 SET_TABLE_HANDLER(machine);
1847 SET_TABLE_HANDLER(thread);
1848 SET_TABLE_HANDLER(comm);
1849 SET_TABLE_HANDLER(comm_thread);
1850 SET_TABLE_HANDLER(dso);
1851 SET_TABLE_HANDLER(symbol);
1852 SET_TABLE_HANDLER(branch_type);
1853 SET_TABLE_HANDLER(sample);
1854 SET_TABLE_HANDLER(call_path);
1855 SET_TABLE_HANDLER(call_return);
1856 SET_TABLE_HANDLER(context_switch);
1859 * Synthesized events are samples but with architecture-specific data
1860 * stored in sample->raw_data. They are exported via
1861 * python_export_sample() and consequently do not need a separate export
1864 tables->synth_handler = get_handler("synth_data");
1867 #if PY_MAJOR_VERSION < 3
1868 static void _free_command_line(const char **command_line, int num)
1873 static void _free_command_line(wchar_t **command_line, int num)
1876 for (i = 0; i < num; i++)
1877 PyMem_RawFree(command_line[i]);
1884 * Start trace script
1886 static int python_start_script(const char *script, int argc, const char **argv,
1887 struct perf_session *session)
1889 struct tables *tables = &tables_global;
1890 #if PY_MAJOR_VERSION < 3
1891 const char **command_line;
1893 wchar_t **command_line;
1896 * Use a non-const name variable to cope with python 2.6's
1897 * PyImport_AppendInittab prototype
1899 char buf[PATH_MAX], name[19] = "perf_trace_context";
1903 scripting_context->session = session;
1904 #if PY_MAJOR_VERSION < 3
1905 command_line = malloc((argc + 1) * sizeof(const char *));
1906 command_line[0] = script;
1907 for (i = 1; i < argc + 1; i++)
1908 command_line[i] = argv[i - 1];
1909 PyImport_AppendInittab(name, initperf_trace_context);
1911 command_line = malloc((argc + 1) * sizeof(wchar_t *));
1912 command_line[0] = Py_DecodeLocale(script, NULL);
1913 for (i = 1; i < argc + 1; i++)
1914 command_line[i] = Py_DecodeLocale(argv[i - 1], NULL);
1915 PyImport_AppendInittab(name, PyInit_perf_trace_context);
1919 #if PY_MAJOR_VERSION < 3
1920 PySys_SetArgv(argc + 1, (char **)command_line);
1922 PySys_SetArgv(argc + 1, command_line);
1925 fp = fopen(script, "r");
1927 sprintf(buf, "Can't open python script \"%s\"", script);
1933 err = PyRun_SimpleFile(fp, script);
1935 fprintf(stderr, "Error running python script %s\n", script);
1939 err = run_start_sub();
1941 fprintf(stderr, "Error starting python script %s\n", script);
1945 set_table_handlers(tables);
1947 if (tables->db_export_mode) {
1948 err = db_export__branch_types(&tables->dbe);
1953 _free_command_line(command_line, argc + 1);
1958 _free_command_line(command_line, argc + 1);
1963 static int python_flush_script(void)
1971 static int python_stop_script(void)
1973 struct tables *tables = &tables_global;
1975 try_call_object("trace_end", NULL);
1977 db_export__exit(&tables->dbe);
1979 Py_XDECREF(main_dict);
1980 Py_XDECREF(main_module);
1986 #ifdef HAVE_LIBTRACEEVENT
1987 static int python_generate_script(struct tep_handle *pevent, const char *outfile)
1989 int i, not_first, count, nr_events;
1990 struct tep_event **all_events;
1991 struct tep_event *event = NULL;
1992 struct tep_format_field *f;
1993 char fname[PATH_MAX];
1996 sprintf(fname, "%s.py", outfile);
1997 ofp = fopen(fname, "w");
1999 fprintf(stderr, "couldn't open %s\n", fname);
2002 fprintf(ofp, "# perf script event handlers, "
2003 "generated by perf script -g python\n");
2005 fprintf(ofp, "# Licensed under the terms of the GNU GPL"
2006 " License version 2\n\n");
2008 fprintf(ofp, "# The common_* event handler fields are the most useful "
2009 "fields common to\n");
2011 fprintf(ofp, "# all events. They don't necessarily correspond to "
2012 "the 'common_*' fields\n");
2014 fprintf(ofp, "# in the format files. Those fields not available as "
2015 "handler params can\n");
2017 fprintf(ofp, "# be retrieved using Python functions of the form "
2018 "common_*(context).\n");
2020 fprintf(ofp, "# See the perf-script-python Documentation for the list "
2021 "of available functions.\n\n");
2023 fprintf(ofp, "from __future__ import print_function\n\n");
2024 fprintf(ofp, "import os\n");
2025 fprintf(ofp, "import sys\n\n");
2027 fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
2028 fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
2029 fprintf(ofp, "\nfrom perf_trace_context import *\n");
2030 fprintf(ofp, "from Core import *\n\n\n");
2032 fprintf(ofp, "def trace_begin():\n");
2033 fprintf(ofp, "\tprint(\"in trace_begin\")\n\n");
2035 fprintf(ofp, "def trace_end():\n");
2036 fprintf(ofp, "\tprint(\"in trace_end\")\n\n");
2038 nr_events = tep_get_events_count(pevent);
2039 all_events = tep_list_events(pevent, TEP_EVENT_SORT_ID);
2041 for (i = 0; all_events && i < nr_events; i++) {
2042 event = all_events[i];
2043 fprintf(ofp, "def %s__%s(", event->system, event->name);
2044 fprintf(ofp, "event_name, ");
2045 fprintf(ofp, "context, ");
2046 fprintf(ofp, "common_cpu,\n");
2047 fprintf(ofp, "\tcommon_secs, ");
2048 fprintf(ofp, "common_nsecs, ");
2049 fprintf(ofp, "common_pid, ");
2050 fprintf(ofp, "common_comm,\n\t");
2051 fprintf(ofp, "common_callchain, ");
2056 for (f = event->format.fields; f; f = f->next) {
2059 if (++count % 5 == 0)
2060 fprintf(ofp, "\n\t");
2062 fprintf(ofp, "%s", f->name);
2066 if (++count % 5 == 0)
2067 fprintf(ofp, "\n\t\t");
2068 fprintf(ofp, "perf_sample_dict");
2070 fprintf(ofp, "):\n");
2072 fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
2073 "common_secs, common_nsecs,\n\t\t\t"
2074 "common_pid, common_comm)\n\n");
2076 fprintf(ofp, "\t\tprint(\"");
2081 for (f = event->format.fields; f; f = f->next) {
2084 if (count && count % 3 == 0) {
2085 fprintf(ofp, "\" \\\n\t\t\"");
2089 fprintf(ofp, "%s=", f->name);
2090 if (f->flags & TEP_FIELD_IS_STRING ||
2091 f->flags & TEP_FIELD_IS_FLAG ||
2092 f->flags & TEP_FIELD_IS_ARRAY ||
2093 f->flags & TEP_FIELD_IS_SYMBOLIC)
2094 fprintf(ofp, "%%s");
2095 else if (f->flags & TEP_FIELD_IS_SIGNED)
2096 fprintf(ofp, "%%d");
2098 fprintf(ofp, "%%u");
2101 fprintf(ofp, "\" %% \\\n\t\t(");
2106 for (f = event->format.fields; f; f = f->next) {
2110 if (++count % 5 == 0)
2111 fprintf(ofp, "\n\t\t");
2113 if (f->flags & TEP_FIELD_IS_FLAG) {
2114 if ((count - 1) % 5 != 0) {
2115 fprintf(ofp, "\n\t\t");
2118 fprintf(ofp, "flag_str(\"");
2119 fprintf(ofp, "%s__%s\", ", event->system,
2121 fprintf(ofp, "\"%s\", %s)", f->name,
2123 } else if (f->flags & TEP_FIELD_IS_SYMBOLIC) {
2124 if ((count - 1) % 5 != 0) {
2125 fprintf(ofp, "\n\t\t");
2128 fprintf(ofp, "symbol_str(\"");
2129 fprintf(ofp, "%s__%s\", ", event->system,
2131 fprintf(ofp, "\"%s\", %s)", f->name,
2134 fprintf(ofp, "%s", f->name);
2137 fprintf(ofp, "))\n\n");
2139 fprintf(ofp, "\t\tprint('Sample: {'+"
2140 "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
2142 fprintf(ofp, "\t\tfor node in common_callchain:");
2143 fprintf(ofp, "\n\t\t\tif 'sym' in node:");
2144 fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x] %%s%%s%%s%%s\" %% (");
2145 fprintf(ofp, "\n\t\t\t\t\tnode['ip'], node['sym']['name'],");
2146 fprintf(ofp, "\n\t\t\t\t\t\"+0x{:x}\".format(node['sym_off']) if 'sym_off' in node else \"\",");
2147 fprintf(ofp, "\n\t\t\t\t\t\" ({})\".format(node['dso']) if 'dso' in node else \"\",");
2148 fprintf(ofp, "\n\t\t\t\t\t\" \" + node['sym_srcline'] if 'sym_srcline' in node else \"\"))");
2149 fprintf(ofp, "\n\t\t\telse:");
2150 fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x]\" %% (node['ip']))\n\n");
2151 fprintf(ofp, "\t\tprint()\n\n");
2155 fprintf(ofp, "def trace_unhandled(event_name, context, "
2156 "event_fields_dict, perf_sample_dict):\n");
2158 fprintf(ofp, "\t\tprint(get_dict_as_string(event_fields_dict))\n");
2159 fprintf(ofp, "\t\tprint('Sample: {'+"
2160 "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
2162 fprintf(ofp, "def print_header("
2163 "event_name, cpu, secs, nsecs, pid, comm):\n"
2164 "\tprint(\"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
2165 "(event_name, cpu, secs, nsecs, pid, comm), end=\"\")\n\n");
2167 fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
2168 "\treturn delimiter.join"
2169 "(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
2173 fprintf(stderr, "generated Python script: %s\n", fname);
2178 static int python_generate_script(struct tep_handle *pevent __maybe_unused,
2179 const char *outfile __maybe_unused)
2181 fprintf(stderr, "Generating Python perf-script is not supported."
2182 " Install libtraceevent and rebuild perf to enable it.\n"
2183 "For example:\n # apt install libtraceevent-dev (ubuntu)"
2184 "\n # yum install libtraceevent-devel (Fedora)"
2190 struct scripting_ops python_scripting_ops = {
2192 .dirname = "python",
2193 .start_script = python_start_script,
2194 .flush_script = python_flush_script,
2195 .stop_script = python_stop_script,
2196 .process_event = python_process_event,
2197 .process_switch = python_process_switch,
2198 .process_auxtrace_error = python_process_auxtrace_error,
2199 .process_stat = python_process_stat,
2200 .process_stat_interval = python_process_stat_interval,
2201 .process_throttle = python_process_throttle,
2202 .generate_script = python_generate_script,