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 #include <traceevent/event-parse.h>
35 #include "../build-id.h"
36 #include "../counts.h"
39 #include "../callchain.h"
43 #include "../thread.h"
45 #include "../machine.h"
46 #include "../db-export.h"
47 #include "../thread-stack.h"
48 #include "../trace-event.h"
49 #include "../call-path.h"
52 #include "thread_map.h"
53 #include "print_binary.h"
55 #include "mem-events.h"
56 #include "util/perf_regs.h"
58 #if PY_MAJOR_VERSION < 3
59 #define _PyUnicode_FromString(arg) \
60 PyString_FromString(arg)
61 #define _PyUnicode_FromStringAndSize(arg1, arg2) \
62 PyString_FromStringAndSize((arg1), (arg2))
63 #define _PyBytes_FromStringAndSize(arg1, arg2) \
64 PyString_FromStringAndSize((arg1), (arg2))
65 #define _PyLong_FromLong(arg) \
67 #define _PyLong_AsLong(arg) \
69 #define _PyCapsule_New(arg1, arg2, arg3) \
70 PyCObject_FromVoidPtr((arg1), (arg2))
72 PyMODINIT_FUNC initperf_trace_context(void);
74 #define _PyUnicode_FromString(arg) \
75 PyUnicode_FromString(arg)
76 #define _PyUnicode_FromStringAndSize(arg1, arg2) \
77 PyUnicode_FromStringAndSize((arg1), (arg2))
78 #define _PyBytes_FromStringAndSize(arg1, arg2) \
79 PyBytes_FromStringAndSize((arg1), (arg2))
80 #define _PyLong_FromLong(arg) \
82 #define _PyLong_AsLong(arg) \
84 #define _PyCapsule_New(arg1, arg2, arg3) \
85 PyCapsule_New((arg1), (arg2), (arg3))
87 PyMODINIT_FUNC PyInit_perf_trace_context(void);
90 #define TRACE_EVENT_TYPE_MAX \
91 ((1 << (sizeof(unsigned short) * 8)) - 1)
93 static DECLARE_BITMAP(events_defined, TRACE_EVENT_TYPE_MAX);
96 #define N_COMMON_FIELDS 7
98 extern struct scripting_context *scripting_context;
100 static char *cur_field_name;
101 static int zero_flag_atom;
103 static PyObject *main_module, *main_dict;
106 struct db_export dbe;
107 PyObject *evsel_handler;
108 PyObject *machine_handler;
109 PyObject *thread_handler;
110 PyObject *comm_handler;
111 PyObject *comm_thread_handler;
112 PyObject *dso_handler;
113 PyObject *symbol_handler;
114 PyObject *branch_type_handler;
115 PyObject *sample_handler;
116 PyObject *call_path_handler;
117 PyObject *call_return_handler;
118 PyObject *synth_handler;
119 PyObject *context_switch_handler;
123 static struct tables tables_global;
125 static void handler_call_die(const char *handler_name) __noreturn;
126 static void handler_call_die(const char *handler_name)
129 Py_FatalError("problem in Python trace event handler");
130 // Py_FatalError does not return
131 // but we have to make the compiler happy
136 * Insert val into the dictionary and decrement the reference counter.
137 * This is necessary for dictionaries since PyDict_SetItemString() does not
138 * steal a reference, as opposed to PyTuple_SetItem().
140 static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
142 PyDict_SetItemString(dict, key, val);
146 static PyObject *get_handler(const char *handler_name)
150 handler = PyDict_GetItemString(main_dict, handler_name);
151 if (handler && !PyCallable_Check(handler))
156 static int get_argument_count(PyObject *handler)
161 * The attribute for the code object is func_code in Python 2,
162 * whereas it is __code__ in Python 3.0+.
164 PyObject *code_obj = PyObject_GetAttrString(handler,
166 if (PyErr_Occurred()) {
168 code_obj = PyObject_GetAttrString(handler,
173 PyObject *arg_count_obj = PyObject_GetAttrString(code_obj,
176 arg_count = (int) _PyLong_AsLong(arg_count_obj);
177 Py_DECREF(arg_count_obj);
184 static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
188 retval = PyObject_CallObject(handler, args);
190 handler_call_die(die_msg);
194 static void try_call_object(const char *handler_name, PyObject *args)
198 handler = get_handler(handler_name);
200 call_object(handler, args, handler_name);
203 static void define_value(enum tep_print_arg_type field_type,
205 const char *field_name,
206 const char *field_value,
207 const char *field_str)
209 const char *handler_name = "define_flag_value";
211 unsigned long long value;
214 if (field_type == TEP_PRINT_SYMBOL)
215 handler_name = "define_symbolic_value";
219 Py_FatalError("couldn't create Python tuple");
221 value = eval_flag(field_value);
223 PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
224 PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
225 PyTuple_SetItem(t, n++, _PyLong_FromLong(value));
226 PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_str));
228 try_call_object(handler_name, t);
233 static void define_values(enum tep_print_arg_type field_type,
234 struct tep_print_flag_sym *field,
236 const char *field_name)
238 define_value(field_type, ev_name, field_name, field->value,
242 define_values(field_type, field->next, ev_name, field_name);
245 static void define_field(enum tep_print_arg_type field_type,
247 const char *field_name,
250 const char *handler_name = "define_flag_field";
254 if (field_type == TEP_PRINT_SYMBOL)
255 handler_name = "define_symbolic_field";
257 if (field_type == TEP_PRINT_FLAGS)
262 Py_FatalError("couldn't create Python tuple");
264 PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
265 PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
266 if (field_type == TEP_PRINT_FLAGS)
267 PyTuple_SetItem(t, n++, _PyUnicode_FromString(delim));
269 try_call_object(handler_name, t);
274 static void define_event_symbols(struct tep_event *event,
276 struct tep_print_arg *args)
281 switch (args->type) {
285 define_value(TEP_PRINT_FLAGS, ev_name, cur_field_name, "0",
289 case TEP_PRINT_FIELD:
290 free(cur_field_name);
291 cur_field_name = strdup(args->field.name);
293 case TEP_PRINT_FLAGS:
294 define_event_symbols(event, ev_name, args->flags.field);
295 define_field(TEP_PRINT_FLAGS, ev_name, cur_field_name,
297 define_values(TEP_PRINT_FLAGS, args->flags.flags, ev_name,
300 case TEP_PRINT_SYMBOL:
301 define_event_symbols(event, ev_name, args->symbol.field);
302 define_field(TEP_PRINT_SYMBOL, ev_name, cur_field_name, NULL);
303 define_values(TEP_PRINT_SYMBOL, args->symbol.symbols, ev_name,
307 case TEP_PRINT_HEX_STR:
308 define_event_symbols(event, ev_name, args->hex.field);
309 define_event_symbols(event, ev_name, args->hex.size);
311 case TEP_PRINT_INT_ARRAY:
312 define_event_symbols(event, ev_name, args->int_array.field);
313 define_event_symbols(event, ev_name, args->int_array.count);
314 define_event_symbols(event, ev_name, args->int_array.el_size);
316 case TEP_PRINT_STRING:
319 define_event_symbols(event, ev_name, args->typecast.item);
322 if (strcmp(args->op.op, ":") == 0)
324 define_event_symbols(event, ev_name, args->op.left);
325 define_event_symbols(event, ev_name, args->op.right);
328 /* gcc warns for these? */
329 case TEP_PRINT_BSTRING:
330 case TEP_PRINT_DYNAMIC_ARRAY:
331 case TEP_PRINT_DYNAMIC_ARRAY_LEN:
333 case TEP_PRINT_BITMASK:
334 /* we should warn... */
339 define_event_symbols(event, ev_name, args->next);
342 static PyObject *get_field_numeric_entry(struct tep_event *event,
343 struct tep_format_field *field, void *data)
345 bool is_array = field->flags & TEP_FIELD_IS_ARRAY;
346 PyObject *obj = NULL, *list = NULL;
347 unsigned long long val;
348 unsigned int item_size, n_items, i;
351 list = PyList_New(field->arraylen);
352 item_size = field->size / field->arraylen;
353 n_items = field->arraylen;
355 item_size = field->size;
359 for (i = 0; i < n_items; i++) {
361 val = read_size(event, data + field->offset + i * item_size,
363 if (field->flags & TEP_FIELD_IS_SIGNED) {
364 if ((long long)val >= LONG_MIN &&
365 (long long)val <= LONG_MAX)
366 obj = _PyLong_FromLong(val);
368 obj = PyLong_FromLongLong(val);
371 obj = _PyLong_FromLong(val);
373 obj = PyLong_FromUnsignedLongLong(val);
376 PyList_SET_ITEM(list, i, obj);
383 static const char *get_dsoname(struct map *map)
385 const char *dsoname = "[unknown]";
387 if (map && map->dso) {
388 if (symbol_conf.show_kernel_path && map->dso->long_name)
389 dsoname = map->dso->long_name;
391 dsoname = map->dso->name;
397 static unsigned long get_offset(struct symbol *sym, struct addr_location *al)
399 unsigned long offset;
401 if (al->addr < sym->end)
402 offset = al->addr - sym->start;
404 offset = al->addr - al->map->start - sym->start;
409 static PyObject *python_process_callchain(struct perf_sample *sample,
411 struct addr_location *al)
415 pylist = PyList_New(0);
417 Py_FatalError("couldn't create Python list");
419 if (!symbol_conf.use_callchain || !sample->callchain)
422 if (thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
424 scripting_max_stack) != 0) {
425 pr_err("Failed to resolve callchain. Skipping\n");
428 callchain_cursor_commit(&callchain_cursor);
433 struct callchain_cursor_node *node;
434 node = callchain_cursor_current(&callchain_cursor);
438 pyelem = PyDict_New();
440 Py_FatalError("couldn't create Python dictionary");
443 pydict_set_item_string_decref(pyelem, "ip",
444 PyLong_FromUnsignedLongLong(node->ip));
447 PyObject *pysym = PyDict_New();
449 Py_FatalError("couldn't create Python dictionary");
450 pydict_set_item_string_decref(pysym, "start",
451 PyLong_FromUnsignedLongLong(node->ms.sym->start));
452 pydict_set_item_string_decref(pysym, "end",
453 PyLong_FromUnsignedLongLong(node->ms.sym->end));
454 pydict_set_item_string_decref(pysym, "binding",
455 _PyLong_FromLong(node->ms.sym->binding));
456 pydict_set_item_string_decref(pysym, "name",
457 _PyUnicode_FromStringAndSize(node->ms.sym->name,
458 node->ms.sym->namelen));
459 pydict_set_item_string_decref(pyelem, "sym", pysym);
462 struct map *map = node->ms.map;
463 struct addr_location node_al;
464 unsigned long offset;
466 node_al.addr = map->map_ip(map, node->ip);
468 offset = get_offset(node->ms.sym, &node_al);
470 pydict_set_item_string_decref(
472 PyLong_FromUnsignedLongLong(offset));
474 if (node->srcline && strcmp(":0", node->srcline)) {
475 pydict_set_item_string_decref(
476 pyelem, "sym_srcline",
477 _PyUnicode_FromString(node->srcline));
482 const char *dsoname = get_dsoname(node->ms.map);
484 pydict_set_item_string_decref(pyelem, "dso",
485 _PyUnicode_FromString(dsoname));
488 callchain_cursor_advance(&callchain_cursor);
489 PyList_Append(pylist, pyelem);
497 static PyObject *python_process_brstack(struct perf_sample *sample,
498 struct thread *thread)
500 struct branch_stack *br = sample->branch_stack;
501 struct branch_entry *entries = perf_sample__branch_entries(sample);
505 pylist = PyList_New(0);
507 Py_FatalError("couldn't create Python list");
512 for (i = 0; i < br->nr; i++) {
514 struct addr_location al;
517 pyelem = PyDict_New();
519 Py_FatalError("couldn't create Python dictionary");
521 pydict_set_item_string_decref(pyelem, "from",
522 PyLong_FromUnsignedLongLong(entries[i].from));
523 pydict_set_item_string_decref(pyelem, "to",
524 PyLong_FromUnsignedLongLong(entries[i].to));
525 pydict_set_item_string_decref(pyelem, "mispred",
526 PyBool_FromLong(entries[i].flags.mispred));
527 pydict_set_item_string_decref(pyelem, "predicted",
528 PyBool_FromLong(entries[i].flags.predicted));
529 pydict_set_item_string_decref(pyelem, "in_tx",
530 PyBool_FromLong(entries[i].flags.in_tx));
531 pydict_set_item_string_decref(pyelem, "abort",
532 PyBool_FromLong(entries[i].flags.abort));
533 pydict_set_item_string_decref(pyelem, "cycles",
534 PyLong_FromUnsignedLongLong(entries[i].flags.cycles));
536 thread__find_map_fb(thread, sample->cpumode,
537 entries[i].from, &al);
538 dsoname = get_dsoname(al.map);
539 pydict_set_item_string_decref(pyelem, "from_dsoname",
540 _PyUnicode_FromString(dsoname));
542 thread__find_map_fb(thread, sample->cpumode,
544 dsoname = get_dsoname(al.map);
545 pydict_set_item_string_decref(pyelem, "to_dsoname",
546 _PyUnicode_FromString(dsoname));
548 PyList_Append(pylist, pyelem);
556 static int get_symoff(struct symbol *sym, struct addr_location *al,
557 bool print_off, char *bf, int size)
559 unsigned long offset;
561 if (!sym || !sym->name[0])
562 return scnprintf(bf, size, "%s", "[unknown]");
565 return scnprintf(bf, size, "%s", sym->name);
567 offset = get_offset(sym, al);
569 return scnprintf(bf, size, "%s+0x%x", sym->name, offset);
572 static int get_br_mspred(struct branch_flags *flags, char *bf, int size)
574 if (!flags->mispred && !flags->predicted)
575 return scnprintf(bf, size, "%s", "-");
578 return scnprintf(bf, size, "%s", "M");
580 return scnprintf(bf, size, "%s", "P");
583 static PyObject *python_process_brstacksym(struct perf_sample *sample,
584 struct thread *thread)
586 struct branch_stack *br = sample->branch_stack;
587 struct branch_entry *entries = perf_sample__branch_entries(sample);
591 struct addr_location al;
593 pylist = PyList_New(0);
595 Py_FatalError("couldn't create Python list");
600 for (i = 0; i < br->nr; i++) {
603 pyelem = PyDict_New();
605 Py_FatalError("couldn't create Python dictionary");
607 thread__find_symbol_fb(thread, sample->cpumode,
608 entries[i].from, &al);
609 get_symoff(al.sym, &al, true, bf, sizeof(bf));
610 pydict_set_item_string_decref(pyelem, "from",
611 _PyUnicode_FromString(bf));
613 thread__find_symbol_fb(thread, sample->cpumode,
615 get_symoff(al.sym, &al, true, bf, sizeof(bf));
616 pydict_set_item_string_decref(pyelem, "to",
617 _PyUnicode_FromString(bf));
619 get_br_mspred(&entries[i].flags, bf, sizeof(bf));
620 pydict_set_item_string_decref(pyelem, "pred",
621 _PyUnicode_FromString(bf));
623 if (entries[i].flags.in_tx) {
624 pydict_set_item_string_decref(pyelem, "in_tx",
625 _PyUnicode_FromString("X"));
627 pydict_set_item_string_decref(pyelem, "in_tx",
628 _PyUnicode_FromString("-"));
631 if (entries[i].flags.abort) {
632 pydict_set_item_string_decref(pyelem, "abort",
633 _PyUnicode_FromString("A"));
635 pydict_set_item_string_decref(pyelem, "abort",
636 _PyUnicode_FromString("-"));
639 PyList_Append(pylist, pyelem);
647 static PyObject *get_sample_value_as_tuple(struct sample_read_value *value,
654 Py_FatalError("couldn't create Python tuple");
655 PyTuple_SetItem(t, 0, PyLong_FromUnsignedLongLong(value->id));
656 PyTuple_SetItem(t, 1, PyLong_FromUnsignedLongLong(value->value));
657 if (read_format & PERF_FORMAT_LOST)
658 PyTuple_SetItem(t, 2, PyLong_FromUnsignedLongLong(value->lost));
663 static void set_sample_read_in_dict(PyObject *dict_sample,
664 struct perf_sample *sample,
667 u64 read_format = evsel->core.attr.read_format;
671 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
672 pydict_set_item_string_decref(dict_sample, "time_enabled",
673 PyLong_FromUnsignedLongLong(sample->read.time_enabled));
676 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
677 pydict_set_item_string_decref(dict_sample, "time_running",
678 PyLong_FromUnsignedLongLong(sample->read.time_running));
681 if (read_format & PERF_FORMAT_GROUP)
682 values = PyList_New(sample->read.group.nr);
684 values = PyList_New(1);
687 Py_FatalError("couldn't create Python list");
689 if (read_format & PERF_FORMAT_GROUP) {
690 struct sample_read_value *v = sample->read.group.values;
693 sample_read_group__for_each(v, sample->read.group.nr, read_format) {
694 PyObject *t = get_sample_value_as_tuple(v, read_format);
695 PyList_SET_ITEM(values, i, t);
699 PyObject *t = get_sample_value_as_tuple(&sample->read.one,
701 PyList_SET_ITEM(values, 0, t);
703 pydict_set_item_string_decref(dict_sample, "values", values);
706 static void set_sample_datasrc_in_dict(PyObject *dict,
707 struct perf_sample *sample)
709 struct mem_info mi = { .data_src.val = sample->data_src };
712 pydict_set_item_string_decref(dict, "datasrc",
713 PyLong_FromUnsignedLongLong(sample->data_src));
715 perf_script__meminfo_scnprintf(decode, 100, &mi);
717 pydict_set_item_string_decref(dict, "datasrc_decode",
718 _PyUnicode_FromString(decode));
721 static void regs_map(struct regs_dump *regs, uint64_t mask, const char *arch, char *bf, int size)
723 unsigned int i = 0, r;
728 if (!regs || !regs->regs)
731 for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
732 u64 val = regs->regs[i++];
734 printed += scnprintf(bf + printed, size - printed,
735 "%5s:0x%" PRIx64 " ",
736 perf_reg_name(r, arch), val);
740 static void set_regs_in_dict(PyObject *dict,
741 struct perf_sample *sample,
744 struct perf_event_attr *attr = &evsel->core.attr;
745 const char *arch = perf_env__arch(evsel__env(evsel));
748 * Here value 28 is a constant size which can be used to print
749 * one register value and its corresponds to:
750 * 16 chars is to specify 64 bit register in hexadecimal.
751 * 2 chars is for appending "0x" to the hexadecimal value and
752 * 10 chars is for register name.
754 int size = __sw_hweight64(attr->sample_regs_intr) * 28;
757 regs_map(&sample->intr_regs, attr->sample_regs_intr, arch, bf, sizeof(bf));
759 pydict_set_item_string_decref(dict, "iregs",
760 _PyUnicode_FromString(bf));
762 regs_map(&sample->user_regs, attr->sample_regs_user, arch, bf, sizeof(bf));
764 pydict_set_item_string_decref(dict, "uregs",
765 _PyUnicode_FromString(bf));
768 static void set_sym_in_dict(PyObject *dict, struct addr_location *al,
769 const char *dso_field, const char *dso_bid_field,
770 const char *dso_map_start, const char *dso_map_end,
771 const char *sym_field, const char *symoff_field)
773 char sbuild_id[SBUILD_ID_SIZE];
776 pydict_set_item_string_decref(dict, dso_field,
777 _PyUnicode_FromString(al->map->dso->name));
778 build_id__sprintf(&al->map->dso->bid, sbuild_id);
779 pydict_set_item_string_decref(dict, dso_bid_field,
780 _PyUnicode_FromString(sbuild_id));
781 pydict_set_item_string_decref(dict, dso_map_start,
782 PyLong_FromUnsignedLong(al->map->start));
783 pydict_set_item_string_decref(dict, dso_map_end,
784 PyLong_FromUnsignedLong(al->map->end));
787 pydict_set_item_string_decref(dict, sym_field,
788 _PyUnicode_FromString(al->sym->name));
789 pydict_set_item_string_decref(dict, symoff_field,
790 PyLong_FromUnsignedLong(get_offset(al->sym, al)));
794 static void set_sample_flags(PyObject *dict, u32 flags)
796 const char *ch = PERF_IP_FLAG_CHARS;
799 for (p = str; *ch; ch++, flags >>= 1) {
804 pydict_set_item_string_decref(dict, "flags", _PyUnicode_FromString(str));
807 static void python_process_sample_flags(struct perf_sample *sample, PyObject *dict_sample)
809 char flags_disp[SAMPLE_FLAGS_BUF_SIZE];
811 set_sample_flags(dict_sample, sample->flags);
812 perf_sample__sprintf_flags(sample->flags, flags_disp, sizeof(flags_disp));
813 pydict_set_item_string_decref(dict_sample, "flags_disp",
814 _PyUnicode_FromString(flags_disp));
817 static PyObject *get_perf_sample_dict(struct perf_sample *sample,
819 struct addr_location *al,
820 struct addr_location *addr_al,
823 PyObject *dict, *dict_sample, *brstack, *brstacksym;
827 Py_FatalError("couldn't create Python dictionary");
829 dict_sample = PyDict_New();
831 Py_FatalError("couldn't create Python dictionary");
833 pydict_set_item_string_decref(dict, "ev_name", _PyUnicode_FromString(evsel__name(evsel)));
834 pydict_set_item_string_decref(dict, "attr", _PyBytes_FromStringAndSize((const char *)&evsel->core.attr, sizeof(evsel->core.attr)));
836 pydict_set_item_string_decref(dict_sample, "pid",
837 _PyLong_FromLong(sample->pid));
838 pydict_set_item_string_decref(dict_sample, "tid",
839 _PyLong_FromLong(sample->tid));
840 pydict_set_item_string_decref(dict_sample, "cpu",
841 _PyLong_FromLong(sample->cpu));
842 pydict_set_item_string_decref(dict_sample, "ip",
843 PyLong_FromUnsignedLongLong(sample->ip));
844 pydict_set_item_string_decref(dict_sample, "time",
845 PyLong_FromUnsignedLongLong(sample->time));
846 pydict_set_item_string_decref(dict_sample, "period",
847 PyLong_FromUnsignedLongLong(sample->period));
848 pydict_set_item_string_decref(dict_sample, "phys_addr",
849 PyLong_FromUnsignedLongLong(sample->phys_addr));
850 pydict_set_item_string_decref(dict_sample, "addr",
851 PyLong_FromUnsignedLongLong(sample->addr));
852 set_sample_read_in_dict(dict_sample, sample, evsel);
853 pydict_set_item_string_decref(dict_sample, "weight",
854 PyLong_FromUnsignedLongLong(sample->weight));
855 pydict_set_item_string_decref(dict_sample, "transaction",
856 PyLong_FromUnsignedLongLong(sample->transaction));
857 set_sample_datasrc_in_dict(dict_sample, sample);
858 pydict_set_item_string_decref(dict, "sample", dict_sample);
860 pydict_set_item_string_decref(dict, "raw_buf", _PyBytes_FromStringAndSize(
861 (const char *)sample->raw_data, sample->raw_size));
862 pydict_set_item_string_decref(dict, "comm",
863 _PyUnicode_FromString(thread__comm_str(al->thread)));
864 set_sym_in_dict(dict, al, "dso", "dso_bid", "dso_map_start", "dso_map_end",
867 pydict_set_item_string_decref(dict, "callchain", callchain);
869 brstack = python_process_brstack(sample, al->thread);
870 pydict_set_item_string_decref(dict, "brstack", brstack);
872 brstacksym = python_process_brstacksym(sample, al->thread);
873 pydict_set_item_string_decref(dict, "brstacksym", brstacksym);
875 if (sample->machine_pid) {
876 pydict_set_item_string_decref(dict_sample, "machine_pid",
877 _PyLong_FromLong(sample->machine_pid));
878 pydict_set_item_string_decref(dict_sample, "vcpu",
879 _PyLong_FromLong(sample->vcpu));
882 pydict_set_item_string_decref(dict_sample, "cpumode",
883 _PyLong_FromLong((unsigned long)sample->cpumode));
886 pydict_set_item_string_decref(dict_sample, "addr_correlates_sym",
888 set_sym_in_dict(dict_sample, addr_al, "addr_dso", "addr_dso_bid",
889 "addr_dso_map_start", "addr_dso_map_end",
890 "addr_symbol", "addr_symoff");
894 python_process_sample_flags(sample, dict_sample);
896 /* Instructions per cycle (IPC) */
897 if (sample->insn_cnt && sample->cyc_cnt) {
898 pydict_set_item_string_decref(dict_sample, "insn_cnt",
899 PyLong_FromUnsignedLongLong(sample->insn_cnt));
900 pydict_set_item_string_decref(dict_sample, "cyc_cnt",
901 PyLong_FromUnsignedLongLong(sample->cyc_cnt));
904 set_regs_in_dict(dict, sample, evsel);
909 static void python_process_tracepoint(struct perf_sample *sample,
911 struct addr_location *al,
912 struct addr_location *addr_al)
914 struct tep_event *event = evsel->tp_format;
915 PyObject *handler, *context, *t, *obj = NULL, *callchain;
916 PyObject *dict = NULL, *all_entries_dict = NULL;
917 static char handler_name[256];
918 struct tep_format_field *field;
922 int cpu = sample->cpu;
923 void *data = sample->raw_data;
924 unsigned long long nsecs = sample->time;
925 const char *comm = thread__comm_str(al->thread);
926 const char *default_handler_name = "trace_unhandled";
929 snprintf(handler_name, sizeof(handler_name),
930 "ug! no event found for type %" PRIu64, (u64)evsel->core.attr.config);
931 Py_FatalError(handler_name);
934 pid = raw_field_value(event, "common_pid", data);
936 sprintf(handler_name, "%s__%s", event->system, event->name);
938 if (!__test_and_set_bit(event->id, events_defined))
939 define_event_symbols(event, handler_name, event->print_fmt.args);
941 handler = get_handler(handler_name);
943 handler = get_handler(default_handler_name);
948 Py_FatalError("couldn't create Python dict");
951 t = PyTuple_New(MAX_FIELDS);
953 Py_FatalError("couldn't create Python tuple");
956 s = nsecs / NSEC_PER_SEC;
957 ns = nsecs - s * NSEC_PER_SEC;
959 context = _PyCapsule_New(scripting_context, NULL, NULL);
961 PyTuple_SetItem(t, n++, _PyUnicode_FromString(handler_name));
962 PyTuple_SetItem(t, n++, context);
965 callchain = python_process_callchain(sample, evsel, al);
966 /* Need an additional reference for the perf_sample dict */
967 Py_INCREF(callchain);
970 PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
971 PyTuple_SetItem(t, n++, _PyLong_FromLong(s));
972 PyTuple_SetItem(t, n++, _PyLong_FromLong(ns));
973 PyTuple_SetItem(t, n++, _PyLong_FromLong(pid));
974 PyTuple_SetItem(t, n++, _PyUnicode_FromString(comm));
975 PyTuple_SetItem(t, n++, callchain);
977 pydict_set_item_string_decref(dict, "common_cpu", _PyLong_FromLong(cpu));
978 pydict_set_item_string_decref(dict, "common_s", _PyLong_FromLong(s));
979 pydict_set_item_string_decref(dict, "common_ns", _PyLong_FromLong(ns));
980 pydict_set_item_string_decref(dict, "common_pid", _PyLong_FromLong(pid));
981 pydict_set_item_string_decref(dict, "common_comm", _PyUnicode_FromString(comm));
982 pydict_set_item_string_decref(dict, "common_callchain", callchain);
984 for (field = event->format.fields; field; field = field->next) {
985 unsigned int offset, len;
986 unsigned long long val;
988 if (field->flags & TEP_FIELD_IS_ARRAY) {
989 offset = field->offset;
991 if (field->flags & TEP_FIELD_IS_DYNAMIC) {
992 val = tep_read_number(scripting_context->pevent,
997 #ifdef HAVE_LIBTRACEEVENT_TEP_FIELD_IS_RELATIVE
998 if (field->flags & TEP_FIELD_IS_RELATIVE)
999 offset += field->offset + field->size;
1002 if (field->flags & TEP_FIELD_IS_STRING &&
1003 is_printable_array(data + offset, len)) {
1004 obj = _PyUnicode_FromString((char *) data + offset);
1006 obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
1007 field->flags &= ~TEP_FIELD_IS_STRING;
1009 } else { /* FIELD_IS_NUMERIC */
1010 obj = get_field_numeric_entry(event, field, data);
1013 PyTuple_SetItem(t, n++, obj);
1015 pydict_set_item_string_decref(dict, field->name, obj);
1020 PyTuple_SetItem(t, n++, dict);
1022 if (get_argument_count(handler) == (int) n + 1) {
1023 all_entries_dict = get_perf_sample_dict(sample, evsel, al, addr_al,
1025 PyTuple_SetItem(t, n++, all_entries_dict);
1027 Py_DECREF(callchain);
1030 if (_PyTuple_Resize(&t, n) == -1)
1031 Py_FatalError("error resizing Python tuple");
1034 call_object(handler, t, handler_name);
1036 call_object(handler, t, default_handler_name);
1041 static PyObject *tuple_new(unsigned int sz)
1045 t = PyTuple_New(sz);
1047 Py_FatalError("couldn't create Python tuple");
1051 static int tuple_set_s64(PyObject *t, unsigned int pos, s64 val)
1053 #if BITS_PER_LONG == 64
1054 return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
1056 #if BITS_PER_LONG == 32
1057 return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
1062 * Databases support only signed 64-bit numbers, so even though we are
1063 * exporting a u64, it must be as s64.
1065 #define tuple_set_d64 tuple_set_s64
1067 static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
1069 #if BITS_PER_LONG == 64
1070 return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
1072 #if BITS_PER_LONG == 32
1073 return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLongLong(val));
1077 static int tuple_set_u32(PyObject *t, unsigned int pos, u32 val)
1079 return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
1082 static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
1084 return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
1087 static int tuple_set_bool(PyObject *t, unsigned int pos, bool val)
1089 return PyTuple_SetItem(t, pos, PyBool_FromLong(val));
1092 static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
1094 return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
1097 static int tuple_set_bytes(PyObject *t, unsigned int pos, void *bytes,
1100 return PyTuple_SetItem(t, pos, _PyBytes_FromStringAndSize(bytes, sz));
1103 static int python_export_evsel(struct db_export *dbe, struct evsel *evsel)
1105 struct tables *tables = container_of(dbe, struct tables, dbe);
1110 tuple_set_d64(t, 0, evsel->db_id);
1111 tuple_set_string(t, 1, evsel__name(evsel));
1113 call_object(tables->evsel_handler, t, "evsel_table");
1120 static int python_export_machine(struct db_export *dbe,
1121 struct machine *machine)
1123 struct tables *tables = container_of(dbe, struct tables, dbe);
1128 tuple_set_d64(t, 0, machine->db_id);
1129 tuple_set_s32(t, 1, machine->pid);
1130 tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
1132 call_object(tables->machine_handler, t, "machine_table");
1139 static int python_export_thread(struct db_export *dbe, struct thread *thread,
1140 u64 main_thread_db_id, struct machine *machine)
1142 struct tables *tables = container_of(dbe, struct tables, dbe);
1147 tuple_set_d64(t, 0, thread->db_id);
1148 tuple_set_d64(t, 1, machine->db_id);
1149 tuple_set_d64(t, 2, main_thread_db_id);
1150 tuple_set_s32(t, 3, thread->pid_);
1151 tuple_set_s32(t, 4, thread->tid);
1153 call_object(tables->thread_handler, t, "thread_table");
1160 static int python_export_comm(struct db_export *dbe, struct comm *comm,
1161 struct thread *thread)
1163 struct tables *tables = container_of(dbe, struct tables, dbe);
1168 tuple_set_d64(t, 0, comm->db_id);
1169 tuple_set_string(t, 1, comm__str(comm));
1170 tuple_set_d64(t, 2, thread->db_id);
1171 tuple_set_d64(t, 3, comm->start);
1172 tuple_set_s32(t, 4, comm->exec);
1174 call_object(tables->comm_handler, t, "comm_table");
1181 static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
1182 struct comm *comm, struct thread *thread)
1184 struct tables *tables = container_of(dbe, struct tables, dbe);
1189 tuple_set_d64(t, 0, db_id);
1190 tuple_set_d64(t, 1, comm->db_id);
1191 tuple_set_d64(t, 2, thread->db_id);
1193 call_object(tables->comm_thread_handler, t, "comm_thread_table");
1200 static int python_export_dso(struct db_export *dbe, struct dso *dso,
1201 struct machine *machine)
1203 struct tables *tables = container_of(dbe, struct tables, dbe);
1204 char sbuild_id[SBUILD_ID_SIZE];
1207 build_id__sprintf(&dso->bid, sbuild_id);
1211 tuple_set_d64(t, 0, dso->db_id);
1212 tuple_set_d64(t, 1, machine->db_id);
1213 tuple_set_string(t, 2, dso->short_name);
1214 tuple_set_string(t, 3, dso->long_name);
1215 tuple_set_string(t, 4, sbuild_id);
1217 call_object(tables->dso_handler, t, "dso_table");
1224 static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
1227 struct tables *tables = container_of(dbe, struct tables, dbe);
1228 u64 *sym_db_id = symbol__priv(sym);
1233 tuple_set_d64(t, 0, *sym_db_id);
1234 tuple_set_d64(t, 1, dso->db_id);
1235 tuple_set_d64(t, 2, sym->start);
1236 tuple_set_d64(t, 3, sym->end);
1237 tuple_set_s32(t, 4, sym->binding);
1238 tuple_set_string(t, 5, sym->name);
1240 call_object(tables->symbol_handler, t, "symbol_table");
1247 static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
1250 struct tables *tables = container_of(dbe, struct tables, dbe);
1255 tuple_set_s32(t, 0, branch_type);
1256 tuple_set_string(t, 1, name);
1258 call_object(tables->branch_type_handler, t, "branch_type_table");
1265 static void python_export_sample_table(struct db_export *dbe,
1266 struct export_sample *es)
1268 struct tables *tables = container_of(dbe, struct tables, dbe);
1273 tuple_set_d64(t, 0, es->db_id);
1274 tuple_set_d64(t, 1, es->evsel->db_id);
1275 tuple_set_d64(t, 2, es->al->maps->machine->db_id);
1276 tuple_set_d64(t, 3, es->al->thread->db_id);
1277 tuple_set_d64(t, 4, es->comm_db_id);
1278 tuple_set_d64(t, 5, es->dso_db_id);
1279 tuple_set_d64(t, 6, es->sym_db_id);
1280 tuple_set_d64(t, 7, es->offset);
1281 tuple_set_d64(t, 8, es->sample->ip);
1282 tuple_set_d64(t, 9, es->sample->time);
1283 tuple_set_s32(t, 10, es->sample->cpu);
1284 tuple_set_d64(t, 11, es->addr_dso_db_id);
1285 tuple_set_d64(t, 12, es->addr_sym_db_id);
1286 tuple_set_d64(t, 13, es->addr_offset);
1287 tuple_set_d64(t, 14, es->sample->addr);
1288 tuple_set_d64(t, 15, es->sample->period);
1289 tuple_set_d64(t, 16, es->sample->weight);
1290 tuple_set_d64(t, 17, es->sample->transaction);
1291 tuple_set_d64(t, 18, es->sample->data_src);
1292 tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
1293 tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
1294 tuple_set_d64(t, 21, es->call_path_id);
1295 tuple_set_d64(t, 22, es->sample->insn_cnt);
1296 tuple_set_d64(t, 23, es->sample->cyc_cnt);
1297 tuple_set_s32(t, 24, es->sample->flags);
1299 call_object(tables->sample_handler, t, "sample_table");
1304 static void python_export_synth(struct db_export *dbe, struct export_sample *es)
1306 struct tables *tables = container_of(dbe, struct tables, dbe);
1311 tuple_set_d64(t, 0, es->db_id);
1312 tuple_set_d64(t, 1, es->evsel->core.attr.config);
1313 tuple_set_bytes(t, 2, es->sample->raw_data, es->sample->raw_size);
1315 call_object(tables->synth_handler, t, "synth_data");
1320 static int python_export_sample(struct db_export *dbe,
1321 struct export_sample *es)
1323 struct tables *tables = container_of(dbe, struct tables, dbe);
1325 python_export_sample_table(dbe, es);
1327 if (es->evsel->core.attr.type == PERF_TYPE_SYNTH && tables->synth_handler)
1328 python_export_synth(dbe, es);
1333 static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
1335 struct tables *tables = container_of(dbe, struct tables, dbe);
1337 u64 parent_db_id, sym_db_id;
1339 parent_db_id = cp->parent ? cp->parent->db_id : 0;
1340 sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
1344 tuple_set_d64(t, 0, cp->db_id);
1345 tuple_set_d64(t, 1, parent_db_id);
1346 tuple_set_d64(t, 2, sym_db_id);
1347 tuple_set_d64(t, 3, cp->ip);
1349 call_object(tables->call_path_handler, t, "call_path_table");
1356 static int python_export_call_return(struct db_export *dbe,
1357 struct call_return *cr)
1359 struct tables *tables = container_of(dbe, struct tables, dbe);
1360 u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
1365 tuple_set_d64(t, 0, cr->db_id);
1366 tuple_set_d64(t, 1, cr->thread->db_id);
1367 tuple_set_d64(t, 2, comm_db_id);
1368 tuple_set_d64(t, 3, cr->cp->db_id);
1369 tuple_set_d64(t, 4, cr->call_time);
1370 tuple_set_d64(t, 5, cr->return_time);
1371 tuple_set_d64(t, 6, cr->branch_count);
1372 tuple_set_d64(t, 7, cr->call_ref);
1373 tuple_set_d64(t, 8, cr->return_ref);
1374 tuple_set_d64(t, 9, cr->cp->parent->db_id);
1375 tuple_set_s32(t, 10, cr->flags);
1376 tuple_set_d64(t, 11, cr->parent_db_id);
1377 tuple_set_d64(t, 12, cr->insn_count);
1378 tuple_set_d64(t, 13, cr->cyc_count);
1380 call_object(tables->call_return_handler, t, "call_return_table");
1387 static int python_export_context_switch(struct db_export *dbe, u64 db_id,
1388 struct machine *machine,
1389 struct perf_sample *sample,
1390 u64 th_out_id, u64 comm_out_id,
1391 u64 th_in_id, u64 comm_in_id, int flags)
1393 struct tables *tables = container_of(dbe, struct tables, dbe);
1398 tuple_set_d64(t, 0, db_id);
1399 tuple_set_d64(t, 1, machine->db_id);
1400 tuple_set_d64(t, 2, sample->time);
1401 tuple_set_s32(t, 3, sample->cpu);
1402 tuple_set_d64(t, 4, th_out_id);
1403 tuple_set_d64(t, 5, comm_out_id);
1404 tuple_set_d64(t, 6, th_in_id);
1405 tuple_set_d64(t, 7, comm_in_id);
1406 tuple_set_s32(t, 8, flags);
1408 call_object(tables->context_switch_handler, t, "context_switch");
1415 static int python_process_call_return(struct call_return *cr, u64 *parent_db_id,
1418 struct db_export *dbe = data;
1420 return db_export__call_return(dbe, cr, parent_db_id);
1423 static void python_process_general_event(struct perf_sample *sample,
1424 struct evsel *evsel,
1425 struct addr_location *al,
1426 struct addr_location *addr_al)
1428 PyObject *handler, *t, *dict, *callchain;
1429 static char handler_name[64];
1432 snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
1434 handler = get_handler(handler_name);
1439 * Use the MAX_FIELDS to make the function expandable, though
1440 * currently there is only one item for the tuple.
1442 t = PyTuple_New(MAX_FIELDS);
1444 Py_FatalError("couldn't create Python tuple");
1447 callchain = python_process_callchain(sample, evsel, al);
1448 dict = get_perf_sample_dict(sample, evsel, al, addr_al, callchain);
1450 PyTuple_SetItem(t, n++, dict);
1451 if (_PyTuple_Resize(&t, n) == -1)
1452 Py_FatalError("error resizing Python tuple");
1454 call_object(handler, t, handler_name);
1459 static void python_process_event(union perf_event *event,
1460 struct perf_sample *sample,
1461 struct evsel *evsel,
1462 struct addr_location *al,
1463 struct addr_location *addr_al)
1465 struct tables *tables = &tables_global;
1467 scripting_context__update(scripting_context, event, sample, evsel, al, addr_al);
1469 switch (evsel->core.attr.type) {
1470 case PERF_TYPE_TRACEPOINT:
1471 python_process_tracepoint(sample, evsel, al, addr_al);
1473 /* Reserve for future process_hw/sw/raw APIs */
1475 if (tables->db_export_mode)
1476 db_export__sample(&tables->dbe, event, sample, evsel, al, addr_al);
1478 python_process_general_event(sample, evsel, al, addr_al);
1482 static void python_process_throttle(union perf_event *event,
1483 struct perf_sample *sample,
1484 struct machine *machine)
1486 const char *handler_name;
1487 PyObject *handler, *t;
1489 if (event->header.type == PERF_RECORD_THROTTLE)
1490 handler_name = "throttle";
1492 handler_name = "unthrottle";
1493 handler = get_handler(handler_name);
1501 tuple_set_u64(t, 0, event->throttle.time);
1502 tuple_set_u64(t, 1, event->throttle.id);
1503 tuple_set_u64(t, 2, event->throttle.stream_id);
1504 tuple_set_s32(t, 3, sample->cpu);
1505 tuple_set_s32(t, 4, sample->pid);
1506 tuple_set_s32(t, 5, sample->tid);
1508 call_object(handler, t, handler_name);
1513 static void python_do_process_switch(union perf_event *event,
1514 struct perf_sample *sample,
1515 struct machine *machine)
1517 const char *handler_name = "context_switch";
1518 bool out = event->header.misc & PERF_RECORD_MISC_SWITCH_OUT;
1519 bool out_preempt = out && (event->header.misc & PERF_RECORD_MISC_SWITCH_OUT_PREEMPT);
1520 pid_t np_pid = -1, np_tid = -1;
1521 PyObject *handler, *t;
1523 handler = get_handler(handler_name);
1527 if (event->header.type == PERF_RECORD_SWITCH_CPU_WIDE) {
1528 np_pid = event->context_switch.next_prev_pid;
1529 np_tid = event->context_switch.next_prev_tid;
1536 tuple_set_u64(t, 0, sample->time);
1537 tuple_set_s32(t, 1, sample->cpu);
1538 tuple_set_s32(t, 2, sample->pid);
1539 tuple_set_s32(t, 3, sample->tid);
1540 tuple_set_s32(t, 4, np_pid);
1541 tuple_set_s32(t, 5, np_tid);
1542 tuple_set_s32(t, 6, machine->pid);
1543 tuple_set_bool(t, 7, out);
1544 tuple_set_bool(t, 8, out_preempt);
1545 tuple_set_s32(t, 9, sample->machine_pid);
1546 tuple_set_s32(t, 10, sample->vcpu);
1548 call_object(handler, t, handler_name);
1553 static void python_process_switch(union perf_event *event,
1554 struct perf_sample *sample,
1555 struct machine *machine)
1557 struct tables *tables = &tables_global;
1559 if (tables->db_export_mode)
1560 db_export__switch(&tables->dbe, event, sample, machine);
1562 python_do_process_switch(event, sample, machine);
1565 static void python_process_auxtrace_error(struct perf_session *session __maybe_unused,
1566 union perf_event *event)
1568 struct perf_record_auxtrace_error *e = &event->auxtrace_error;
1569 u8 cpumode = e->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
1570 const char *handler_name = "auxtrace_error";
1571 unsigned long long tm = e->time;
1572 const char *msg = e->msg;
1573 PyObject *handler, *t;
1575 handler = get_handler(handler_name);
1581 msg = (const char *)&e->time;
1586 tuple_set_u32(t, 0, e->type);
1587 tuple_set_u32(t, 1, e->code);
1588 tuple_set_s32(t, 2, e->cpu);
1589 tuple_set_s32(t, 3, e->pid);
1590 tuple_set_s32(t, 4, e->tid);
1591 tuple_set_u64(t, 5, e->ip);
1592 tuple_set_u64(t, 6, tm);
1593 tuple_set_string(t, 7, msg);
1594 tuple_set_u32(t, 8, cpumode);
1595 tuple_set_s32(t, 9, e->machine_pid);
1596 tuple_set_s32(t, 10, e->vcpu);
1598 call_object(handler, t, handler_name);
1603 static void get_handler_name(char *str, size_t size,
1604 struct evsel *evsel)
1608 scnprintf(str, size, "stat__%s", evsel__name(evsel));
1610 while ((p = strchr(p, ':'))) {
1617 process_stat(struct evsel *counter, struct perf_cpu cpu, int thread, u64 tstamp,
1618 struct perf_counts_values *count)
1620 PyObject *handler, *t;
1621 static char handler_name[256];
1624 t = PyTuple_New(MAX_FIELDS);
1626 Py_FatalError("couldn't create Python tuple");
1628 get_handler_name(handler_name, sizeof(handler_name),
1631 handler = get_handler(handler_name);
1633 pr_debug("can't find python handler %s\n", handler_name);
1637 PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu.cpu));
1638 PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
1640 tuple_set_u64(t, n++, tstamp);
1641 tuple_set_u64(t, n++, count->val);
1642 tuple_set_u64(t, n++, count->ena);
1643 tuple_set_u64(t, n++, count->run);
1645 if (_PyTuple_Resize(&t, n) == -1)
1646 Py_FatalError("error resizing Python tuple");
1648 call_object(handler, t, handler_name);
1653 static void python_process_stat(struct perf_stat_config *config,
1654 struct evsel *counter, u64 tstamp)
1656 struct perf_thread_map *threads = counter->core.threads;
1657 struct perf_cpu_map *cpus = counter->core.cpus;
1660 for (thread = 0; thread < perf_thread_map__nr(threads); thread++) {
1661 for (cpu = 0; cpu < perf_cpu_map__nr(cpus); cpu++) {
1662 process_stat(counter, perf_cpu_map__cpu(cpus, cpu),
1663 perf_thread_map__pid(threads, thread), tstamp,
1664 perf_counts(counter->counts, cpu, thread));
1669 static void python_process_stat_interval(u64 tstamp)
1671 PyObject *handler, *t;
1672 static const char handler_name[] = "stat__interval";
1675 t = PyTuple_New(MAX_FIELDS);
1677 Py_FatalError("couldn't create Python tuple");
1679 handler = get_handler(handler_name);
1681 pr_debug("can't find python handler %s\n", handler_name);
1685 tuple_set_u64(t, n++, tstamp);
1687 if (_PyTuple_Resize(&t, n) == -1)
1688 Py_FatalError("error resizing Python tuple");
1690 call_object(handler, t, handler_name);
1695 static int perf_script_context_init(void)
1697 PyObject *perf_script_context;
1698 PyObject *perf_trace_context;
1702 perf_trace_context = PyImport_AddModule("perf_trace_context");
1703 if (!perf_trace_context)
1705 dict = PyModule_GetDict(perf_trace_context);
1709 perf_script_context = _PyCapsule_New(scripting_context, NULL, NULL);
1710 if (!perf_script_context)
1713 ret = PyDict_SetItemString(dict, "perf_script_context", perf_script_context);
1715 ret = PyDict_SetItemString(main_dict, "perf_script_context", perf_script_context);
1716 Py_DECREF(perf_script_context);
1720 static int run_start_sub(void)
1722 main_module = PyImport_AddModule("__main__");
1723 if (main_module == NULL)
1725 Py_INCREF(main_module);
1727 main_dict = PyModule_GetDict(main_module);
1728 if (main_dict == NULL)
1730 Py_INCREF(main_dict);
1732 if (perf_script_context_init())
1735 try_call_object("trace_begin", NULL);
1740 Py_XDECREF(main_dict);
1741 Py_XDECREF(main_module);
1745 #define SET_TABLE_HANDLER_(name, handler_name, table_name) do { \
1746 tables->handler_name = get_handler(#table_name); \
1747 if (tables->handler_name) \
1748 tables->dbe.export_ ## name = python_export_ ## name; \
1751 #define SET_TABLE_HANDLER(name) \
1752 SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
1754 static void set_table_handlers(struct tables *tables)
1756 const char *perf_db_export_mode = "perf_db_export_mode";
1757 const char *perf_db_export_calls = "perf_db_export_calls";
1758 const char *perf_db_export_callchains = "perf_db_export_callchains";
1759 PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
1760 bool export_calls = false;
1761 bool export_callchains = false;
1764 memset(tables, 0, sizeof(struct tables));
1765 if (db_export__init(&tables->dbe))
1766 Py_FatalError("failed to initialize export");
1768 db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
1769 if (!db_export_mode)
1772 ret = PyObject_IsTrue(db_export_mode);
1774 handler_call_die(perf_db_export_mode);
1778 /* handle export calls */
1779 tables->dbe.crp = NULL;
1780 db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
1781 if (db_export_calls) {
1782 ret = PyObject_IsTrue(db_export_calls);
1784 handler_call_die(perf_db_export_calls);
1785 export_calls = !!ret;
1790 call_return_processor__new(python_process_call_return,
1792 if (!tables->dbe.crp)
1793 Py_FatalError("failed to create calls processor");
1796 /* handle export callchains */
1797 tables->dbe.cpr = NULL;
1798 db_export_callchains = PyDict_GetItemString(main_dict,
1799 perf_db_export_callchains);
1800 if (db_export_callchains) {
1801 ret = PyObject_IsTrue(db_export_callchains);
1803 handler_call_die(perf_db_export_callchains);
1804 export_callchains = !!ret;
1807 if (export_callchains) {
1809 * Attempt to use the call path root from the call return
1810 * processor, if the call return processor is in use. Otherwise,
1811 * we allocate a new call path root. This prevents exporting
1812 * duplicate call path ids when both are in use simultaneously.
1814 if (tables->dbe.crp)
1815 tables->dbe.cpr = tables->dbe.crp->cpr;
1817 tables->dbe.cpr = call_path_root__new();
1819 if (!tables->dbe.cpr)
1820 Py_FatalError("failed to create call path root");
1823 tables->db_export_mode = true;
1825 * Reserve per symbol space for symbol->db_id via symbol__priv()
1827 symbol_conf.priv_size = sizeof(u64);
1829 SET_TABLE_HANDLER(evsel);
1830 SET_TABLE_HANDLER(machine);
1831 SET_TABLE_HANDLER(thread);
1832 SET_TABLE_HANDLER(comm);
1833 SET_TABLE_HANDLER(comm_thread);
1834 SET_TABLE_HANDLER(dso);
1835 SET_TABLE_HANDLER(symbol);
1836 SET_TABLE_HANDLER(branch_type);
1837 SET_TABLE_HANDLER(sample);
1838 SET_TABLE_HANDLER(call_path);
1839 SET_TABLE_HANDLER(call_return);
1840 SET_TABLE_HANDLER(context_switch);
1843 * Synthesized events are samples but with architecture-specific data
1844 * stored in sample->raw_data. They are exported via
1845 * python_export_sample() and consequently do not need a separate export
1848 tables->synth_handler = get_handler("synth_data");
1851 #if PY_MAJOR_VERSION < 3
1852 static void _free_command_line(const char **command_line, int num)
1857 static void _free_command_line(wchar_t **command_line, int num)
1860 for (i = 0; i < num; i++)
1861 PyMem_RawFree(command_line[i]);
1868 * Start trace script
1870 static int python_start_script(const char *script, int argc, const char **argv,
1871 struct perf_session *session)
1873 struct tables *tables = &tables_global;
1874 #if PY_MAJOR_VERSION < 3
1875 const char **command_line;
1877 wchar_t **command_line;
1880 * Use a non-const name variable to cope with python 2.6's
1881 * PyImport_AppendInittab prototype
1883 char buf[PATH_MAX], name[19] = "perf_trace_context";
1887 scripting_context->session = session;
1888 #if PY_MAJOR_VERSION < 3
1889 command_line = malloc((argc + 1) * sizeof(const char *));
1890 command_line[0] = script;
1891 for (i = 1; i < argc + 1; i++)
1892 command_line[i] = argv[i - 1];
1893 PyImport_AppendInittab(name, initperf_trace_context);
1895 command_line = malloc((argc + 1) * sizeof(wchar_t *));
1896 command_line[0] = Py_DecodeLocale(script, NULL);
1897 for (i = 1; i < argc + 1; i++)
1898 command_line[i] = Py_DecodeLocale(argv[i - 1], NULL);
1899 PyImport_AppendInittab(name, PyInit_perf_trace_context);
1903 #if PY_MAJOR_VERSION < 3
1904 PySys_SetArgv(argc + 1, (char **)command_line);
1906 PySys_SetArgv(argc + 1, command_line);
1909 fp = fopen(script, "r");
1911 sprintf(buf, "Can't open python script \"%s\"", script);
1917 err = PyRun_SimpleFile(fp, script);
1919 fprintf(stderr, "Error running python script %s\n", script);
1923 err = run_start_sub();
1925 fprintf(stderr, "Error starting python script %s\n", script);
1929 set_table_handlers(tables);
1931 if (tables->db_export_mode) {
1932 err = db_export__branch_types(&tables->dbe);
1937 _free_command_line(command_line, argc + 1);
1942 _free_command_line(command_line, argc + 1);
1947 static int python_flush_script(void)
1955 static int python_stop_script(void)
1957 struct tables *tables = &tables_global;
1959 try_call_object("trace_end", NULL);
1961 db_export__exit(&tables->dbe);
1963 Py_XDECREF(main_dict);
1964 Py_XDECREF(main_module);
1970 static int python_generate_script(struct tep_handle *pevent, const char *outfile)
1972 int i, not_first, count, nr_events;
1973 struct tep_event **all_events;
1974 struct tep_event *event = NULL;
1975 struct tep_format_field *f;
1976 char fname[PATH_MAX];
1979 sprintf(fname, "%s.py", outfile);
1980 ofp = fopen(fname, "w");
1982 fprintf(stderr, "couldn't open %s\n", fname);
1985 fprintf(ofp, "# perf script event handlers, "
1986 "generated by perf script -g python\n");
1988 fprintf(ofp, "# Licensed under the terms of the GNU GPL"
1989 " License version 2\n\n");
1991 fprintf(ofp, "# The common_* event handler fields are the most useful "
1992 "fields common to\n");
1994 fprintf(ofp, "# all events. They don't necessarily correspond to "
1995 "the 'common_*' fields\n");
1997 fprintf(ofp, "# in the format files. Those fields not available as "
1998 "handler params can\n");
2000 fprintf(ofp, "# be retrieved using Python functions of the form "
2001 "common_*(context).\n");
2003 fprintf(ofp, "# See the perf-script-python Documentation for the list "
2004 "of available functions.\n\n");
2006 fprintf(ofp, "from __future__ import print_function\n\n");
2007 fprintf(ofp, "import os\n");
2008 fprintf(ofp, "import sys\n\n");
2010 fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
2011 fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
2012 fprintf(ofp, "\nfrom perf_trace_context import *\n");
2013 fprintf(ofp, "from Core import *\n\n\n");
2015 fprintf(ofp, "def trace_begin():\n");
2016 fprintf(ofp, "\tprint(\"in trace_begin\")\n\n");
2018 fprintf(ofp, "def trace_end():\n");
2019 fprintf(ofp, "\tprint(\"in trace_end\")\n\n");
2021 nr_events = tep_get_events_count(pevent);
2022 all_events = tep_list_events(pevent, TEP_EVENT_SORT_ID);
2024 for (i = 0; all_events && i < nr_events; i++) {
2025 event = all_events[i];
2026 fprintf(ofp, "def %s__%s(", event->system, event->name);
2027 fprintf(ofp, "event_name, ");
2028 fprintf(ofp, "context, ");
2029 fprintf(ofp, "common_cpu,\n");
2030 fprintf(ofp, "\tcommon_secs, ");
2031 fprintf(ofp, "common_nsecs, ");
2032 fprintf(ofp, "common_pid, ");
2033 fprintf(ofp, "common_comm,\n\t");
2034 fprintf(ofp, "common_callchain, ");
2039 for (f = event->format.fields; f; f = f->next) {
2042 if (++count % 5 == 0)
2043 fprintf(ofp, "\n\t");
2045 fprintf(ofp, "%s", f->name);
2049 if (++count % 5 == 0)
2050 fprintf(ofp, "\n\t\t");
2051 fprintf(ofp, "perf_sample_dict");
2053 fprintf(ofp, "):\n");
2055 fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
2056 "common_secs, common_nsecs,\n\t\t\t"
2057 "common_pid, common_comm)\n\n");
2059 fprintf(ofp, "\t\tprint(\"");
2064 for (f = event->format.fields; f; f = f->next) {
2067 if (count && count % 3 == 0) {
2068 fprintf(ofp, "\" \\\n\t\t\"");
2072 fprintf(ofp, "%s=", f->name);
2073 if (f->flags & TEP_FIELD_IS_STRING ||
2074 f->flags & TEP_FIELD_IS_FLAG ||
2075 f->flags & TEP_FIELD_IS_ARRAY ||
2076 f->flags & TEP_FIELD_IS_SYMBOLIC)
2077 fprintf(ofp, "%%s");
2078 else if (f->flags & TEP_FIELD_IS_SIGNED)
2079 fprintf(ofp, "%%d");
2081 fprintf(ofp, "%%u");
2084 fprintf(ofp, "\" %% \\\n\t\t(");
2089 for (f = event->format.fields; f; f = f->next) {
2093 if (++count % 5 == 0)
2094 fprintf(ofp, "\n\t\t");
2096 if (f->flags & TEP_FIELD_IS_FLAG) {
2097 if ((count - 1) % 5 != 0) {
2098 fprintf(ofp, "\n\t\t");
2101 fprintf(ofp, "flag_str(\"");
2102 fprintf(ofp, "%s__%s\", ", event->system,
2104 fprintf(ofp, "\"%s\", %s)", f->name,
2106 } else if (f->flags & TEP_FIELD_IS_SYMBOLIC) {
2107 if ((count - 1) % 5 != 0) {
2108 fprintf(ofp, "\n\t\t");
2111 fprintf(ofp, "symbol_str(\"");
2112 fprintf(ofp, "%s__%s\", ", event->system,
2114 fprintf(ofp, "\"%s\", %s)", f->name,
2117 fprintf(ofp, "%s", f->name);
2120 fprintf(ofp, "))\n\n");
2122 fprintf(ofp, "\t\tprint('Sample: {'+"
2123 "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
2125 fprintf(ofp, "\t\tfor node in common_callchain:");
2126 fprintf(ofp, "\n\t\t\tif 'sym' in node:");
2127 fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x] %%s%%s%%s%%s\" %% (");
2128 fprintf(ofp, "\n\t\t\t\t\tnode['ip'], node['sym']['name'],");
2129 fprintf(ofp, "\n\t\t\t\t\t\"+0x{:x}\".format(node['sym_off']) if 'sym_off' in node else \"\",");
2130 fprintf(ofp, "\n\t\t\t\t\t\" ({})\".format(node['dso']) if 'dso' in node else \"\",");
2131 fprintf(ofp, "\n\t\t\t\t\t\" \" + node['sym_srcline'] if 'sym_srcline' in node else \"\"))");
2132 fprintf(ofp, "\n\t\t\telse:");
2133 fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x]\" %% (node['ip']))\n\n");
2134 fprintf(ofp, "\t\tprint()\n\n");
2138 fprintf(ofp, "def trace_unhandled(event_name, context, "
2139 "event_fields_dict, perf_sample_dict):\n");
2141 fprintf(ofp, "\t\tprint(get_dict_as_string(event_fields_dict))\n");
2142 fprintf(ofp, "\t\tprint('Sample: {'+"
2143 "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
2145 fprintf(ofp, "def print_header("
2146 "event_name, cpu, secs, nsecs, pid, comm):\n"
2147 "\tprint(\"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
2148 "(event_name, cpu, secs, nsecs, pid, comm), end=\"\")\n\n");
2150 fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
2151 "\treturn delimiter.join"
2152 "(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
2156 fprintf(stderr, "generated Python script: %s\n", fname);
2161 struct scripting_ops python_scripting_ops = {
2163 .dirname = "python",
2164 .start_script = python_start_script,
2165 .flush_script = python_flush_script,
2166 .stop_script = python_stop_script,
2167 .process_event = python_process_event,
2168 .process_switch = python_process_switch,
2169 .process_auxtrace_error = python_process_auxtrace_error,
2170 .process_stat = python_process_stat,
2171 .process_stat_interval = python_process_stat_interval,
2172 .process_throttle = python_process_throttle,
2173 .generate_script = python_generate_script,