Loading...
1/*
2 * trace-event-python. Feed trace events to an embedded Python interpreter.
3 *
4 * Copyright (C) 2010 Tom Zanussi <tzanussi@gmail.com>
5 *
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.
10 *
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.
15 *
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
19 *
20 */
21
22#include <Python.h>
23
24#include <inttypes.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
28#include <stdbool.h>
29#include <errno.h>
30#include <linux/bitmap.h>
31#include <linux/compiler.h>
32#include <linux/time64.h>
33#include <traceevent/event-parse.h>
34
35#include "../build-id.h"
36#include "../counts.h"
37#include "../debug.h"
38#include "../dso.h"
39#include "../callchain.h"
40#include "../env.h"
41#include "../evsel.h"
42#include "../event.h"
43#include "../thread.h"
44#include "../comm.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"
50#include "map.h"
51#include "symbol.h"
52#include "thread_map.h"
53#include "print_binary.h"
54#include "stat.h"
55#include "mem-events.h"
56#include "util/perf_regs.h"
57
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) \
66 PyInt_FromLong(arg)
67#define _PyLong_AsLong(arg) \
68 PyInt_AsLong(arg)
69#define _PyCapsule_New(arg1, arg2, arg3) \
70 PyCObject_FromVoidPtr((arg1), (arg2))
71
72PyMODINIT_FUNC initperf_trace_context(void);
73#else
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) \
81 PyLong_FromLong(arg)
82#define _PyLong_AsLong(arg) \
83 PyLong_AsLong(arg)
84#define _PyCapsule_New(arg1, arg2, arg3) \
85 PyCapsule_New((arg1), (arg2), (arg3))
86
87PyMODINIT_FUNC PyInit_perf_trace_context(void);
88#endif
89
90#define TRACE_EVENT_TYPE_MAX \
91 ((1 << (sizeof(unsigned short) * 8)) - 1)
92
93static DECLARE_BITMAP(events_defined, TRACE_EVENT_TYPE_MAX);
94
95#define MAX_FIELDS 64
96#define N_COMMON_FIELDS 7
97
98extern struct scripting_context *scripting_context;
99
100static char *cur_field_name;
101static int zero_flag_atom;
102
103static PyObject *main_module, *main_dict;
104
105struct tables {
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;
120 bool db_export_mode;
121};
122
123static struct tables tables_global;
124
125static void handler_call_die(const char *handler_name) __noreturn;
126static void handler_call_die(const char *handler_name)
127{
128 PyErr_Print();
129 Py_FatalError("problem in Python trace event handler");
130 // Py_FatalError does not return
131 // but we have to make the compiler happy
132 abort();
133}
134
135/*
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().
139 */
140static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
141{
142 PyDict_SetItemString(dict, key, val);
143 Py_DECREF(val);
144}
145
146static PyObject *get_handler(const char *handler_name)
147{
148 PyObject *handler;
149
150 handler = PyDict_GetItemString(main_dict, handler_name);
151 if (handler && !PyCallable_Check(handler))
152 return NULL;
153 return handler;
154}
155
156static int get_argument_count(PyObject *handler)
157{
158 int arg_count = 0;
159
160 /*
161 * The attribute for the code object is func_code in Python 2,
162 * whereas it is __code__ in Python 3.0+.
163 */
164 PyObject *code_obj = PyObject_GetAttrString(handler,
165 "func_code");
166 if (PyErr_Occurred()) {
167 PyErr_Clear();
168 code_obj = PyObject_GetAttrString(handler,
169 "__code__");
170 }
171 PyErr_Clear();
172 if (code_obj) {
173 PyObject *arg_count_obj = PyObject_GetAttrString(code_obj,
174 "co_argcount");
175 if (arg_count_obj) {
176 arg_count = (int) _PyLong_AsLong(arg_count_obj);
177 Py_DECREF(arg_count_obj);
178 }
179 Py_DECREF(code_obj);
180 }
181 return arg_count;
182}
183
184static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
185{
186 PyObject *retval;
187
188 retval = PyObject_CallObject(handler, args);
189 if (retval == NULL)
190 handler_call_die(die_msg);
191 Py_DECREF(retval);
192}
193
194static void try_call_object(const char *handler_name, PyObject *args)
195{
196 PyObject *handler;
197
198 handler = get_handler(handler_name);
199 if (handler)
200 call_object(handler, args, handler_name);
201}
202
203static void define_value(enum tep_print_arg_type field_type,
204 const char *ev_name,
205 const char *field_name,
206 const char *field_value,
207 const char *field_str)
208{
209 const char *handler_name = "define_flag_value";
210 PyObject *t;
211 unsigned long long value;
212 unsigned n = 0;
213
214 if (field_type == TEP_PRINT_SYMBOL)
215 handler_name = "define_symbolic_value";
216
217 t = PyTuple_New(4);
218 if (!t)
219 Py_FatalError("couldn't create Python tuple");
220
221 value = eval_flag(field_value);
222
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));
227
228 try_call_object(handler_name, t);
229
230 Py_DECREF(t);
231}
232
233static void define_values(enum tep_print_arg_type field_type,
234 struct tep_print_flag_sym *field,
235 const char *ev_name,
236 const char *field_name)
237{
238 define_value(field_type, ev_name, field_name, field->value,
239 field->str);
240
241 if (field->next)
242 define_values(field_type, field->next, ev_name, field_name);
243}
244
245static void define_field(enum tep_print_arg_type field_type,
246 const char *ev_name,
247 const char *field_name,
248 const char *delim)
249{
250 const char *handler_name = "define_flag_field";
251 PyObject *t;
252 unsigned n = 0;
253
254 if (field_type == TEP_PRINT_SYMBOL)
255 handler_name = "define_symbolic_field";
256
257 if (field_type == TEP_PRINT_FLAGS)
258 t = PyTuple_New(3);
259 else
260 t = PyTuple_New(2);
261 if (!t)
262 Py_FatalError("couldn't create Python tuple");
263
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));
268
269 try_call_object(handler_name, t);
270
271 Py_DECREF(t);
272}
273
274static void define_event_symbols(struct tep_event *event,
275 const char *ev_name,
276 struct tep_print_arg *args)
277{
278 if (args == NULL)
279 return;
280
281 switch (args->type) {
282 case TEP_PRINT_NULL:
283 break;
284 case TEP_PRINT_ATOM:
285 define_value(TEP_PRINT_FLAGS, ev_name, cur_field_name, "0",
286 args->atom.atom);
287 zero_flag_atom = 0;
288 break;
289 case TEP_PRINT_FIELD:
290 free(cur_field_name);
291 cur_field_name = strdup(args->field.name);
292 break;
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,
296 args->flags.delim);
297 define_values(TEP_PRINT_FLAGS, args->flags.flags, ev_name,
298 cur_field_name);
299 break;
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,
304 cur_field_name);
305 break;
306 case TEP_PRINT_HEX:
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);
310 break;
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);
315 break;
316 case TEP_PRINT_STRING:
317 break;
318 case TEP_PRINT_TYPE:
319 define_event_symbols(event, ev_name, args->typecast.item);
320 break;
321 case TEP_PRINT_OP:
322 if (strcmp(args->op.op, ":") == 0)
323 zero_flag_atom = 1;
324 define_event_symbols(event, ev_name, args->op.left);
325 define_event_symbols(event, ev_name, args->op.right);
326 break;
327 default:
328 /* gcc warns for these? */
329 case TEP_PRINT_BSTRING:
330 case TEP_PRINT_DYNAMIC_ARRAY:
331 case TEP_PRINT_DYNAMIC_ARRAY_LEN:
332 case TEP_PRINT_FUNC:
333 case TEP_PRINT_BITMASK:
334 /* we should warn... */
335 return;
336 }
337
338 if (args->next)
339 define_event_symbols(event, ev_name, args->next);
340}
341
342static PyObject *get_field_numeric_entry(struct tep_event *event,
343 struct tep_format_field *field, void *data)
344{
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;
349
350 if (is_array) {
351 list = PyList_New(field->arraylen);
352 item_size = field->size / field->arraylen;
353 n_items = field->arraylen;
354 } else {
355 item_size = field->size;
356 n_items = 1;
357 }
358
359 for (i = 0; i < n_items; i++) {
360
361 val = read_size(event, data + field->offset + i * item_size,
362 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);
367 else
368 obj = PyLong_FromLongLong(val);
369 } else {
370 if (val <= LONG_MAX)
371 obj = _PyLong_FromLong(val);
372 else
373 obj = PyLong_FromUnsignedLongLong(val);
374 }
375 if (is_array)
376 PyList_SET_ITEM(list, i, obj);
377 }
378 if (is_array)
379 obj = list;
380 return obj;
381}
382
383static const char *get_dsoname(struct map *map)
384{
385 const char *dsoname = "[unknown]";
386
387 if (map && map->dso) {
388 if (symbol_conf.show_kernel_path && map->dso->long_name)
389 dsoname = map->dso->long_name;
390 else
391 dsoname = map->dso->name;
392 }
393
394 return dsoname;
395}
396
397static unsigned long get_offset(struct symbol *sym, struct addr_location *al)
398{
399 unsigned long offset;
400
401 if (al->addr < sym->end)
402 offset = al->addr - sym->start;
403 else
404 offset = al->addr - al->map->start - sym->start;
405
406 return offset;
407}
408
409static PyObject *python_process_callchain(struct perf_sample *sample,
410 struct evsel *evsel,
411 struct addr_location *al)
412{
413 PyObject *pylist;
414
415 pylist = PyList_New(0);
416 if (!pylist)
417 Py_FatalError("couldn't create Python list");
418
419 if (!symbol_conf.use_callchain || !sample->callchain)
420 goto exit;
421
422 if (thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
423 sample, NULL, NULL,
424 scripting_max_stack) != 0) {
425 pr_err("Failed to resolve callchain. Skipping\n");
426 goto exit;
427 }
428 callchain_cursor_commit(&callchain_cursor);
429
430
431 while (1) {
432 PyObject *pyelem;
433 struct callchain_cursor_node *node;
434 node = callchain_cursor_current(&callchain_cursor);
435 if (!node)
436 break;
437
438 pyelem = PyDict_New();
439 if (!pyelem)
440 Py_FatalError("couldn't create Python dictionary");
441
442
443 pydict_set_item_string_decref(pyelem, "ip",
444 PyLong_FromUnsignedLongLong(node->ip));
445
446 if (node->ms.sym) {
447 PyObject *pysym = PyDict_New();
448 if (!pysym)
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);
460
461 if (node->ms.map) {
462 struct map *map = node->ms.map;
463 struct addr_location node_al;
464 unsigned long offset;
465
466 node_al.addr = map->map_ip(map, node->ip);
467 node_al.map = map;
468 offset = get_offset(node->ms.sym, &node_al);
469
470 pydict_set_item_string_decref(
471 pyelem, "sym_off",
472 PyLong_FromUnsignedLongLong(offset));
473 }
474 if (node->srcline && strcmp(":0", node->srcline)) {
475 pydict_set_item_string_decref(
476 pyelem, "sym_srcline",
477 _PyUnicode_FromString(node->srcline));
478 }
479 }
480
481 if (node->ms.map) {
482 const char *dsoname = get_dsoname(node->ms.map);
483
484 pydict_set_item_string_decref(pyelem, "dso",
485 _PyUnicode_FromString(dsoname));
486 }
487
488 callchain_cursor_advance(&callchain_cursor);
489 PyList_Append(pylist, pyelem);
490 Py_DECREF(pyelem);
491 }
492
493exit:
494 return pylist;
495}
496
497static PyObject *python_process_brstack(struct perf_sample *sample,
498 struct thread *thread)
499{
500 struct branch_stack *br = sample->branch_stack;
501 struct branch_entry *entries = perf_sample__branch_entries(sample);
502 PyObject *pylist;
503 u64 i;
504
505 pylist = PyList_New(0);
506 if (!pylist)
507 Py_FatalError("couldn't create Python list");
508
509 if (!(br && br->nr))
510 goto exit;
511
512 for (i = 0; i < br->nr; i++) {
513 PyObject *pyelem;
514 struct addr_location al;
515 const char *dsoname;
516
517 pyelem = PyDict_New();
518 if (!pyelem)
519 Py_FatalError("couldn't create Python dictionary");
520
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));
535
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));
541
542 thread__find_map_fb(thread, sample->cpumode,
543 entries[i].to, &al);
544 dsoname = get_dsoname(al.map);
545 pydict_set_item_string_decref(pyelem, "to_dsoname",
546 _PyUnicode_FromString(dsoname));
547
548 PyList_Append(pylist, pyelem);
549 Py_DECREF(pyelem);
550 }
551
552exit:
553 return pylist;
554}
555
556static int get_symoff(struct symbol *sym, struct addr_location *al,
557 bool print_off, char *bf, int size)
558{
559 unsigned long offset;
560
561 if (!sym || !sym->name[0])
562 return scnprintf(bf, size, "%s", "[unknown]");
563
564 if (!print_off)
565 return scnprintf(bf, size, "%s", sym->name);
566
567 offset = get_offset(sym, al);
568
569 return scnprintf(bf, size, "%s+0x%x", sym->name, offset);
570}
571
572static int get_br_mspred(struct branch_flags *flags, char *bf, int size)
573{
574 if (!flags->mispred && !flags->predicted)
575 return scnprintf(bf, size, "%s", "-");
576
577 if (flags->mispred)
578 return scnprintf(bf, size, "%s", "M");
579
580 return scnprintf(bf, size, "%s", "P");
581}
582
583static PyObject *python_process_brstacksym(struct perf_sample *sample,
584 struct thread *thread)
585{
586 struct branch_stack *br = sample->branch_stack;
587 struct branch_entry *entries = perf_sample__branch_entries(sample);
588 PyObject *pylist;
589 u64 i;
590 char bf[512];
591 struct addr_location al;
592
593 pylist = PyList_New(0);
594 if (!pylist)
595 Py_FatalError("couldn't create Python list");
596
597 if (!(br && br->nr))
598 goto exit;
599
600 for (i = 0; i < br->nr; i++) {
601 PyObject *pyelem;
602
603 pyelem = PyDict_New();
604 if (!pyelem)
605 Py_FatalError("couldn't create Python dictionary");
606
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));
612
613 thread__find_symbol_fb(thread, sample->cpumode,
614 entries[i].to, &al);
615 get_symoff(al.sym, &al, true, bf, sizeof(bf));
616 pydict_set_item_string_decref(pyelem, "to",
617 _PyUnicode_FromString(bf));
618
619 get_br_mspred(&entries[i].flags, bf, sizeof(bf));
620 pydict_set_item_string_decref(pyelem, "pred",
621 _PyUnicode_FromString(bf));
622
623 if (entries[i].flags.in_tx) {
624 pydict_set_item_string_decref(pyelem, "in_tx",
625 _PyUnicode_FromString("X"));
626 } else {
627 pydict_set_item_string_decref(pyelem, "in_tx",
628 _PyUnicode_FromString("-"));
629 }
630
631 if (entries[i].flags.abort) {
632 pydict_set_item_string_decref(pyelem, "abort",
633 _PyUnicode_FromString("A"));
634 } else {
635 pydict_set_item_string_decref(pyelem, "abort",
636 _PyUnicode_FromString("-"));
637 }
638
639 PyList_Append(pylist, pyelem);
640 Py_DECREF(pyelem);
641 }
642
643exit:
644 return pylist;
645}
646
647static PyObject *get_sample_value_as_tuple(struct sample_read_value *value,
648 u64 read_format)
649{
650 PyObject *t;
651
652 t = PyTuple_New(3);
653 if (!t)
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));
659
660 return t;
661}
662
663static void set_sample_read_in_dict(PyObject *dict_sample,
664 struct perf_sample *sample,
665 struct evsel *evsel)
666{
667 u64 read_format = evsel->core.attr.read_format;
668 PyObject *values;
669 unsigned int i;
670
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));
674 }
675
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));
679 }
680
681 if (read_format & PERF_FORMAT_GROUP)
682 values = PyList_New(sample->read.group.nr);
683 else
684 values = PyList_New(1);
685
686 if (!values)
687 Py_FatalError("couldn't create Python list");
688
689 if (read_format & PERF_FORMAT_GROUP) {
690 struct sample_read_value *v = sample->read.group.values;
691
692 i = 0;
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);
696 i++;
697 }
698 } else {
699 PyObject *t = get_sample_value_as_tuple(&sample->read.one,
700 read_format);
701 PyList_SET_ITEM(values, 0, t);
702 }
703 pydict_set_item_string_decref(dict_sample, "values", values);
704}
705
706static void set_sample_datasrc_in_dict(PyObject *dict,
707 struct perf_sample *sample)
708{
709 struct mem_info mi = { .data_src.val = sample->data_src };
710 char decode[100];
711
712 pydict_set_item_string_decref(dict, "datasrc",
713 PyLong_FromUnsignedLongLong(sample->data_src));
714
715 perf_script__meminfo_scnprintf(decode, 100, &mi);
716
717 pydict_set_item_string_decref(dict, "datasrc_decode",
718 _PyUnicode_FromString(decode));
719}
720
721static void regs_map(struct regs_dump *regs, uint64_t mask, const char *arch, char *bf, int size)
722{
723 unsigned int i = 0, r;
724 int printed = 0;
725
726 bf[0] = 0;
727
728 if (!regs || !regs->regs)
729 return;
730
731 for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
732 u64 val = regs->regs[i++];
733
734 printed += scnprintf(bf + printed, size - printed,
735 "%5s:0x%" PRIx64 " ",
736 perf_reg_name(r, arch), val);
737 }
738}
739
740static void set_regs_in_dict(PyObject *dict,
741 struct perf_sample *sample,
742 struct evsel *evsel)
743{
744 struct perf_event_attr *attr = &evsel->core.attr;
745 const char *arch = perf_env__arch(evsel__env(evsel));
746
747 /*
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.
753 */
754 int size = __sw_hweight64(attr->sample_regs_intr) * 28;
755 char bf[size];
756
757 regs_map(&sample->intr_regs, attr->sample_regs_intr, arch, bf, sizeof(bf));
758
759 pydict_set_item_string_decref(dict, "iregs",
760 _PyUnicode_FromString(bf));
761
762 regs_map(&sample->user_regs, attr->sample_regs_user, arch, bf, sizeof(bf));
763
764 pydict_set_item_string_decref(dict, "uregs",
765 _PyUnicode_FromString(bf));
766}
767
768static 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)
772{
773 char sbuild_id[SBUILD_ID_SIZE];
774
775 if (al->map) {
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));
785 }
786 if (al->sym) {
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)));
791 }
792}
793
794static void set_sample_flags(PyObject *dict, u32 flags)
795{
796 const char *ch = PERF_IP_FLAG_CHARS;
797 char *p, str[33];
798
799 for (p = str; *ch; ch++, flags >>= 1) {
800 if (flags & 1)
801 *p++ = *ch;
802 }
803 *p = 0;
804 pydict_set_item_string_decref(dict, "flags", _PyUnicode_FromString(str));
805}
806
807static void python_process_sample_flags(struct perf_sample *sample, PyObject *dict_sample)
808{
809 char flags_disp[SAMPLE_FLAGS_BUF_SIZE];
810
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));
815}
816
817static PyObject *get_perf_sample_dict(struct perf_sample *sample,
818 struct evsel *evsel,
819 struct addr_location *al,
820 struct addr_location *addr_al,
821 PyObject *callchain)
822{
823 PyObject *dict, *dict_sample, *brstack, *brstacksym;
824
825 dict = PyDict_New();
826 if (!dict)
827 Py_FatalError("couldn't create Python dictionary");
828
829 dict_sample = PyDict_New();
830 if (!dict_sample)
831 Py_FatalError("couldn't create Python dictionary");
832
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)));
835
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);
859
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",
865 "symbol", "symoff");
866
867 pydict_set_item_string_decref(dict, "callchain", callchain);
868
869 brstack = python_process_brstack(sample, al->thread);
870 pydict_set_item_string_decref(dict, "brstack", brstack);
871
872 brstacksym = python_process_brstacksym(sample, al->thread);
873 pydict_set_item_string_decref(dict, "brstacksym", brstacksym);
874
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));
880 }
881
882 pydict_set_item_string_decref(dict_sample, "cpumode",
883 _PyLong_FromLong((unsigned long)sample->cpumode));
884
885 if (addr_al) {
886 pydict_set_item_string_decref(dict_sample, "addr_correlates_sym",
887 PyBool_FromLong(1));
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");
891 }
892
893 if (sample->flags)
894 python_process_sample_flags(sample, dict_sample);
895
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));
902 }
903
904 set_regs_in_dict(dict, sample, evsel);
905
906 return dict;
907}
908
909static void python_process_tracepoint(struct perf_sample *sample,
910 struct evsel *evsel,
911 struct addr_location *al,
912 struct addr_location *addr_al)
913{
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;
919 unsigned long s, ns;
920 unsigned n = 0;
921 int pid;
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";
927
928 if (!event) {
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);
932 }
933
934 pid = raw_field_value(event, "common_pid", data);
935
936 sprintf(handler_name, "%s__%s", event->system, event->name);
937
938 if (!__test_and_set_bit(event->id, events_defined))
939 define_event_symbols(event, handler_name, event->print_fmt.args);
940
941 handler = get_handler(handler_name);
942 if (!handler) {
943 handler = get_handler(default_handler_name);
944 if (!handler)
945 return;
946 dict = PyDict_New();
947 if (!dict)
948 Py_FatalError("couldn't create Python dict");
949 }
950
951 t = PyTuple_New(MAX_FIELDS);
952 if (!t)
953 Py_FatalError("couldn't create Python tuple");
954
955
956 s = nsecs / NSEC_PER_SEC;
957 ns = nsecs - s * NSEC_PER_SEC;
958
959 context = _PyCapsule_New(scripting_context, NULL, NULL);
960
961 PyTuple_SetItem(t, n++, _PyUnicode_FromString(handler_name));
962 PyTuple_SetItem(t, n++, context);
963
964 /* ip unwinding */
965 callchain = python_process_callchain(sample, evsel, al);
966 /* Need an additional reference for the perf_sample dict */
967 Py_INCREF(callchain);
968
969 if (!dict) {
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);
976 } else {
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);
983 }
984 for (field = event->format.fields; field; field = field->next) {
985 unsigned int offset, len;
986 unsigned long long val;
987
988 if (field->flags & TEP_FIELD_IS_ARRAY) {
989 offset = field->offset;
990 len = field->size;
991 if (field->flags & TEP_FIELD_IS_DYNAMIC) {
992 val = tep_read_number(scripting_context->pevent,
993 data + offset, len);
994 offset = val;
995 len = offset >> 16;
996 offset &= 0xffff;
997#ifdef HAVE_LIBTRACEEVENT_TEP_FIELD_IS_RELATIVE
998 if (field->flags & TEP_FIELD_IS_RELATIVE)
999 offset += field->offset + field->size;
1000#endif
1001 }
1002 if (field->flags & TEP_FIELD_IS_STRING &&
1003 is_printable_array(data + offset, len)) {
1004 obj = _PyUnicode_FromString((char *) data + offset);
1005 } else {
1006 obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
1007 field->flags &= ~TEP_FIELD_IS_STRING;
1008 }
1009 } else { /* FIELD_IS_NUMERIC */
1010 obj = get_field_numeric_entry(event, field, data);
1011 }
1012 if (!dict)
1013 PyTuple_SetItem(t, n++, obj);
1014 else
1015 pydict_set_item_string_decref(dict, field->name, obj);
1016
1017 }
1018
1019 if (dict)
1020 PyTuple_SetItem(t, n++, dict);
1021
1022 if (get_argument_count(handler) == (int) n + 1) {
1023 all_entries_dict = get_perf_sample_dict(sample, evsel, al, addr_al,
1024 callchain);
1025 PyTuple_SetItem(t, n++, all_entries_dict);
1026 } else {
1027 Py_DECREF(callchain);
1028 }
1029
1030 if (_PyTuple_Resize(&t, n) == -1)
1031 Py_FatalError("error resizing Python tuple");
1032
1033 if (!dict)
1034 call_object(handler, t, handler_name);
1035 else
1036 call_object(handler, t, default_handler_name);
1037
1038 Py_DECREF(t);
1039}
1040
1041static PyObject *tuple_new(unsigned int sz)
1042{
1043 PyObject *t;
1044
1045 t = PyTuple_New(sz);
1046 if (!t)
1047 Py_FatalError("couldn't create Python tuple");
1048 return t;
1049}
1050
1051static int tuple_set_s64(PyObject *t, unsigned int pos, s64 val)
1052{
1053#if BITS_PER_LONG == 64
1054 return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
1055#endif
1056#if BITS_PER_LONG == 32
1057 return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
1058#endif
1059}
1060
1061/*
1062 * Databases support only signed 64-bit numbers, so even though we are
1063 * exporting a u64, it must be as s64.
1064 */
1065#define tuple_set_d64 tuple_set_s64
1066
1067static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
1068{
1069#if BITS_PER_LONG == 64
1070 return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
1071#endif
1072#if BITS_PER_LONG == 32
1073 return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLongLong(val));
1074#endif
1075}
1076
1077static int tuple_set_u32(PyObject *t, unsigned int pos, u32 val)
1078{
1079 return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
1080}
1081
1082static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
1083{
1084 return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
1085}
1086
1087static int tuple_set_bool(PyObject *t, unsigned int pos, bool val)
1088{
1089 return PyTuple_SetItem(t, pos, PyBool_FromLong(val));
1090}
1091
1092static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
1093{
1094 return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
1095}
1096
1097static int tuple_set_bytes(PyObject *t, unsigned int pos, void *bytes,
1098 unsigned int sz)
1099{
1100 return PyTuple_SetItem(t, pos, _PyBytes_FromStringAndSize(bytes, sz));
1101}
1102
1103static int python_export_evsel(struct db_export *dbe, struct evsel *evsel)
1104{
1105 struct tables *tables = container_of(dbe, struct tables, dbe);
1106 PyObject *t;
1107
1108 t = tuple_new(2);
1109
1110 tuple_set_d64(t, 0, evsel->db_id);
1111 tuple_set_string(t, 1, evsel__name(evsel));
1112
1113 call_object(tables->evsel_handler, t, "evsel_table");
1114
1115 Py_DECREF(t);
1116
1117 return 0;
1118}
1119
1120static int python_export_machine(struct db_export *dbe,
1121 struct machine *machine)
1122{
1123 struct tables *tables = container_of(dbe, struct tables, dbe);
1124 PyObject *t;
1125
1126 t = tuple_new(3);
1127
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 : "");
1131
1132 call_object(tables->machine_handler, t, "machine_table");
1133
1134 Py_DECREF(t);
1135
1136 return 0;
1137}
1138
1139static int python_export_thread(struct db_export *dbe, struct thread *thread,
1140 u64 main_thread_db_id, struct machine *machine)
1141{
1142 struct tables *tables = container_of(dbe, struct tables, dbe);
1143 PyObject *t;
1144
1145 t = tuple_new(5);
1146
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);
1152
1153 call_object(tables->thread_handler, t, "thread_table");
1154
1155 Py_DECREF(t);
1156
1157 return 0;
1158}
1159
1160static int python_export_comm(struct db_export *dbe, struct comm *comm,
1161 struct thread *thread)
1162{
1163 struct tables *tables = container_of(dbe, struct tables, dbe);
1164 PyObject *t;
1165
1166 t = tuple_new(5);
1167
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);
1173
1174 call_object(tables->comm_handler, t, "comm_table");
1175
1176 Py_DECREF(t);
1177
1178 return 0;
1179}
1180
1181static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
1182 struct comm *comm, struct thread *thread)
1183{
1184 struct tables *tables = container_of(dbe, struct tables, dbe);
1185 PyObject *t;
1186
1187 t = tuple_new(3);
1188
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);
1192
1193 call_object(tables->comm_thread_handler, t, "comm_thread_table");
1194
1195 Py_DECREF(t);
1196
1197 return 0;
1198}
1199
1200static int python_export_dso(struct db_export *dbe, struct dso *dso,
1201 struct machine *machine)
1202{
1203 struct tables *tables = container_of(dbe, struct tables, dbe);
1204 char sbuild_id[SBUILD_ID_SIZE];
1205 PyObject *t;
1206
1207 build_id__sprintf(&dso->bid, sbuild_id);
1208
1209 t = tuple_new(5);
1210
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);
1216
1217 call_object(tables->dso_handler, t, "dso_table");
1218
1219 Py_DECREF(t);
1220
1221 return 0;
1222}
1223
1224static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
1225 struct dso *dso)
1226{
1227 struct tables *tables = container_of(dbe, struct tables, dbe);
1228 u64 *sym_db_id = symbol__priv(sym);
1229 PyObject *t;
1230
1231 t = tuple_new(6);
1232
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);
1239
1240 call_object(tables->symbol_handler, t, "symbol_table");
1241
1242 Py_DECREF(t);
1243
1244 return 0;
1245}
1246
1247static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
1248 const char *name)
1249{
1250 struct tables *tables = container_of(dbe, struct tables, dbe);
1251 PyObject *t;
1252
1253 t = tuple_new(2);
1254
1255 tuple_set_s32(t, 0, branch_type);
1256 tuple_set_string(t, 1, name);
1257
1258 call_object(tables->branch_type_handler, t, "branch_type_table");
1259
1260 Py_DECREF(t);
1261
1262 return 0;
1263}
1264
1265static void python_export_sample_table(struct db_export *dbe,
1266 struct export_sample *es)
1267{
1268 struct tables *tables = container_of(dbe, struct tables, dbe);
1269 PyObject *t;
1270
1271 t = tuple_new(25);
1272
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);
1298
1299 call_object(tables->sample_handler, t, "sample_table");
1300
1301 Py_DECREF(t);
1302}
1303
1304static void python_export_synth(struct db_export *dbe, struct export_sample *es)
1305{
1306 struct tables *tables = container_of(dbe, struct tables, dbe);
1307 PyObject *t;
1308
1309 t = tuple_new(3);
1310
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);
1314
1315 call_object(tables->synth_handler, t, "synth_data");
1316
1317 Py_DECREF(t);
1318}
1319
1320static int python_export_sample(struct db_export *dbe,
1321 struct export_sample *es)
1322{
1323 struct tables *tables = container_of(dbe, struct tables, dbe);
1324
1325 python_export_sample_table(dbe, es);
1326
1327 if (es->evsel->core.attr.type == PERF_TYPE_SYNTH && tables->synth_handler)
1328 python_export_synth(dbe, es);
1329
1330 return 0;
1331}
1332
1333static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
1334{
1335 struct tables *tables = container_of(dbe, struct tables, dbe);
1336 PyObject *t;
1337 u64 parent_db_id, sym_db_id;
1338
1339 parent_db_id = cp->parent ? cp->parent->db_id : 0;
1340 sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
1341
1342 t = tuple_new(4);
1343
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);
1348
1349 call_object(tables->call_path_handler, t, "call_path_table");
1350
1351 Py_DECREF(t);
1352
1353 return 0;
1354}
1355
1356static int python_export_call_return(struct db_export *dbe,
1357 struct call_return *cr)
1358{
1359 struct tables *tables = container_of(dbe, struct tables, dbe);
1360 u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
1361 PyObject *t;
1362
1363 t = tuple_new(14);
1364
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);
1379
1380 call_object(tables->call_return_handler, t, "call_return_table");
1381
1382 Py_DECREF(t);
1383
1384 return 0;
1385}
1386
1387static 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)
1392{
1393 struct tables *tables = container_of(dbe, struct tables, dbe);
1394 PyObject *t;
1395
1396 t = tuple_new(9);
1397
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);
1407
1408 call_object(tables->context_switch_handler, t, "context_switch");
1409
1410 Py_DECREF(t);
1411
1412 return 0;
1413}
1414
1415static int python_process_call_return(struct call_return *cr, u64 *parent_db_id,
1416 void *data)
1417{
1418 struct db_export *dbe = data;
1419
1420 return db_export__call_return(dbe, cr, parent_db_id);
1421}
1422
1423static void python_process_general_event(struct perf_sample *sample,
1424 struct evsel *evsel,
1425 struct addr_location *al,
1426 struct addr_location *addr_al)
1427{
1428 PyObject *handler, *t, *dict, *callchain;
1429 static char handler_name[64];
1430 unsigned n = 0;
1431
1432 snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
1433
1434 handler = get_handler(handler_name);
1435 if (!handler)
1436 return;
1437
1438 /*
1439 * Use the MAX_FIELDS to make the function expandable, though
1440 * currently there is only one item for the tuple.
1441 */
1442 t = PyTuple_New(MAX_FIELDS);
1443 if (!t)
1444 Py_FatalError("couldn't create Python tuple");
1445
1446 /* ip unwinding */
1447 callchain = python_process_callchain(sample, evsel, al);
1448 dict = get_perf_sample_dict(sample, evsel, al, addr_al, callchain);
1449
1450 PyTuple_SetItem(t, n++, dict);
1451 if (_PyTuple_Resize(&t, n) == -1)
1452 Py_FatalError("error resizing Python tuple");
1453
1454 call_object(handler, t, handler_name);
1455
1456 Py_DECREF(t);
1457}
1458
1459static 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)
1464{
1465 struct tables *tables = &tables_global;
1466
1467 scripting_context__update(scripting_context, event, sample, evsel, al, addr_al);
1468
1469 switch (evsel->core.attr.type) {
1470 case PERF_TYPE_TRACEPOINT:
1471 python_process_tracepoint(sample, evsel, al, addr_al);
1472 break;
1473 /* Reserve for future process_hw/sw/raw APIs */
1474 default:
1475 if (tables->db_export_mode)
1476 db_export__sample(&tables->dbe, event, sample, evsel, al, addr_al);
1477 else
1478 python_process_general_event(sample, evsel, al, addr_al);
1479 }
1480}
1481
1482static void python_process_throttle(union perf_event *event,
1483 struct perf_sample *sample,
1484 struct machine *machine)
1485{
1486 const char *handler_name;
1487 PyObject *handler, *t;
1488
1489 if (event->header.type == PERF_RECORD_THROTTLE)
1490 handler_name = "throttle";
1491 else
1492 handler_name = "unthrottle";
1493 handler = get_handler(handler_name);
1494 if (!handler)
1495 return;
1496
1497 t = tuple_new(6);
1498 if (!t)
1499 return;
1500
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);
1507
1508 call_object(handler, t, handler_name);
1509
1510 Py_DECREF(t);
1511}
1512
1513static void python_do_process_switch(union perf_event *event,
1514 struct perf_sample *sample,
1515 struct machine *machine)
1516{
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;
1522
1523 handler = get_handler(handler_name);
1524 if (!handler)
1525 return;
1526
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;
1530 }
1531
1532 t = tuple_new(11);
1533 if (!t)
1534 return;
1535
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);
1547
1548 call_object(handler, t, handler_name);
1549
1550 Py_DECREF(t);
1551}
1552
1553static void python_process_switch(union perf_event *event,
1554 struct perf_sample *sample,
1555 struct machine *machine)
1556{
1557 struct tables *tables = &tables_global;
1558
1559 if (tables->db_export_mode)
1560 db_export__switch(&tables->dbe, event, sample, machine);
1561 else
1562 python_do_process_switch(event, sample, machine);
1563}
1564
1565static void python_process_auxtrace_error(struct perf_session *session __maybe_unused,
1566 union perf_event *event)
1567{
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;
1574
1575 handler = get_handler(handler_name);
1576 if (!handler)
1577 return;
1578
1579 if (!e->fmt) {
1580 tm = 0;
1581 msg = (const char *)&e->time;
1582 }
1583
1584 t = tuple_new(11);
1585
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);
1597
1598 call_object(handler, t, handler_name);
1599
1600 Py_DECREF(t);
1601}
1602
1603static void get_handler_name(char *str, size_t size,
1604 struct evsel *evsel)
1605{
1606 char *p = str;
1607
1608 scnprintf(str, size, "stat__%s", evsel__name(evsel));
1609
1610 while ((p = strchr(p, ':'))) {
1611 *p = '_';
1612 p++;
1613 }
1614}
1615
1616static void
1617process_stat(struct evsel *counter, struct perf_cpu cpu, int thread, u64 tstamp,
1618 struct perf_counts_values *count)
1619{
1620 PyObject *handler, *t;
1621 static char handler_name[256];
1622 int n = 0;
1623
1624 t = PyTuple_New(MAX_FIELDS);
1625 if (!t)
1626 Py_FatalError("couldn't create Python tuple");
1627
1628 get_handler_name(handler_name, sizeof(handler_name),
1629 counter);
1630
1631 handler = get_handler(handler_name);
1632 if (!handler) {
1633 pr_debug("can't find python handler %s\n", handler_name);
1634 return;
1635 }
1636
1637 PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu.cpu));
1638 PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
1639
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);
1644
1645 if (_PyTuple_Resize(&t, n) == -1)
1646 Py_FatalError("error resizing Python tuple");
1647
1648 call_object(handler, t, handler_name);
1649
1650 Py_DECREF(t);
1651}
1652
1653static void python_process_stat(struct perf_stat_config *config,
1654 struct evsel *counter, u64 tstamp)
1655{
1656 struct perf_thread_map *threads = counter->core.threads;
1657 struct perf_cpu_map *cpus = counter->core.cpus;
1658 int cpu, thread;
1659
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));
1665 }
1666 }
1667}
1668
1669static void python_process_stat_interval(u64 tstamp)
1670{
1671 PyObject *handler, *t;
1672 static const char handler_name[] = "stat__interval";
1673 int n = 0;
1674
1675 t = PyTuple_New(MAX_FIELDS);
1676 if (!t)
1677 Py_FatalError("couldn't create Python tuple");
1678
1679 handler = get_handler(handler_name);
1680 if (!handler) {
1681 pr_debug("can't find python handler %s\n", handler_name);
1682 return;
1683 }
1684
1685 tuple_set_u64(t, n++, tstamp);
1686
1687 if (_PyTuple_Resize(&t, n) == -1)
1688 Py_FatalError("error resizing Python tuple");
1689
1690 call_object(handler, t, handler_name);
1691
1692 Py_DECREF(t);
1693}
1694
1695static int perf_script_context_init(void)
1696{
1697 PyObject *perf_script_context;
1698 PyObject *perf_trace_context;
1699 PyObject *dict;
1700 int ret;
1701
1702 perf_trace_context = PyImport_AddModule("perf_trace_context");
1703 if (!perf_trace_context)
1704 return -1;
1705 dict = PyModule_GetDict(perf_trace_context);
1706 if (!dict)
1707 return -1;
1708
1709 perf_script_context = _PyCapsule_New(scripting_context, NULL, NULL);
1710 if (!perf_script_context)
1711 return -1;
1712
1713 ret = PyDict_SetItemString(dict, "perf_script_context", perf_script_context);
1714 if (!ret)
1715 ret = PyDict_SetItemString(main_dict, "perf_script_context", perf_script_context);
1716 Py_DECREF(perf_script_context);
1717 return ret;
1718}
1719
1720static int run_start_sub(void)
1721{
1722 main_module = PyImport_AddModule("__main__");
1723 if (main_module == NULL)
1724 return -1;
1725 Py_INCREF(main_module);
1726
1727 main_dict = PyModule_GetDict(main_module);
1728 if (main_dict == NULL)
1729 goto error;
1730 Py_INCREF(main_dict);
1731
1732 if (perf_script_context_init())
1733 goto error;
1734
1735 try_call_object("trace_begin", NULL);
1736
1737 return 0;
1738
1739error:
1740 Py_XDECREF(main_dict);
1741 Py_XDECREF(main_module);
1742 return -1;
1743}
1744
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; \
1749} while (0)
1750
1751#define SET_TABLE_HANDLER(name) \
1752 SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
1753
1754static void set_table_handlers(struct tables *tables)
1755{
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;
1762 int ret;
1763
1764 memset(tables, 0, sizeof(struct tables));
1765 if (db_export__init(&tables->dbe))
1766 Py_FatalError("failed to initialize export");
1767
1768 db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
1769 if (!db_export_mode)
1770 return;
1771
1772 ret = PyObject_IsTrue(db_export_mode);
1773 if (ret == -1)
1774 handler_call_die(perf_db_export_mode);
1775 if (!ret)
1776 return;
1777
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);
1783 if (ret == -1)
1784 handler_call_die(perf_db_export_calls);
1785 export_calls = !!ret;
1786 }
1787
1788 if (export_calls) {
1789 tables->dbe.crp =
1790 call_return_processor__new(python_process_call_return,
1791 &tables->dbe);
1792 if (!tables->dbe.crp)
1793 Py_FatalError("failed to create calls processor");
1794 }
1795
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);
1802 if (ret == -1)
1803 handler_call_die(perf_db_export_callchains);
1804 export_callchains = !!ret;
1805 }
1806
1807 if (export_callchains) {
1808 /*
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.
1813 */
1814 if (tables->dbe.crp)
1815 tables->dbe.cpr = tables->dbe.crp->cpr;
1816 else
1817 tables->dbe.cpr = call_path_root__new();
1818
1819 if (!tables->dbe.cpr)
1820 Py_FatalError("failed to create call path root");
1821 }
1822
1823 tables->db_export_mode = true;
1824 /*
1825 * Reserve per symbol space for symbol->db_id via symbol__priv()
1826 */
1827 symbol_conf.priv_size = sizeof(u64);
1828
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);
1841
1842 /*
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
1846 * callback.
1847 */
1848 tables->synth_handler = get_handler("synth_data");
1849}
1850
1851#if PY_MAJOR_VERSION < 3
1852static void _free_command_line(const char **command_line, int num)
1853{
1854 free(command_line);
1855}
1856#else
1857static void _free_command_line(wchar_t **command_line, int num)
1858{
1859 int i;
1860 for (i = 0; i < num; i++)
1861 PyMem_RawFree(command_line[i]);
1862 free(command_line);
1863}
1864#endif
1865
1866
1867/*
1868 * Start trace script
1869 */
1870static int python_start_script(const char *script, int argc, const char **argv,
1871 struct perf_session *session)
1872{
1873 struct tables *tables = &tables_global;
1874#if PY_MAJOR_VERSION < 3
1875 const char **command_line;
1876#else
1877 wchar_t **command_line;
1878#endif
1879 /*
1880 * Use a non-const name variable to cope with python 2.6's
1881 * PyImport_AppendInittab prototype
1882 */
1883 char buf[PATH_MAX], name[19] = "perf_trace_context";
1884 int i, err = 0;
1885 FILE *fp;
1886
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);
1894#else
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);
1900#endif
1901 Py_Initialize();
1902
1903#if PY_MAJOR_VERSION < 3
1904 PySys_SetArgv(argc + 1, (char **)command_line);
1905#else
1906 PySys_SetArgv(argc + 1, command_line);
1907#endif
1908
1909 fp = fopen(script, "r");
1910 if (!fp) {
1911 sprintf(buf, "Can't open python script \"%s\"", script);
1912 perror(buf);
1913 err = -1;
1914 goto error;
1915 }
1916
1917 err = PyRun_SimpleFile(fp, script);
1918 if (err) {
1919 fprintf(stderr, "Error running python script %s\n", script);
1920 goto error;
1921 }
1922
1923 err = run_start_sub();
1924 if (err) {
1925 fprintf(stderr, "Error starting python script %s\n", script);
1926 goto error;
1927 }
1928
1929 set_table_handlers(tables);
1930
1931 if (tables->db_export_mode) {
1932 err = db_export__branch_types(&tables->dbe);
1933 if (err)
1934 goto error;
1935 }
1936
1937 _free_command_line(command_line, argc + 1);
1938
1939 return err;
1940error:
1941 Py_Finalize();
1942 _free_command_line(command_line, argc + 1);
1943
1944 return err;
1945}
1946
1947static int python_flush_script(void)
1948{
1949 return 0;
1950}
1951
1952/*
1953 * Stop trace script
1954 */
1955static int python_stop_script(void)
1956{
1957 struct tables *tables = &tables_global;
1958
1959 try_call_object("trace_end", NULL);
1960
1961 db_export__exit(&tables->dbe);
1962
1963 Py_XDECREF(main_dict);
1964 Py_XDECREF(main_module);
1965 Py_Finalize();
1966
1967 return 0;
1968}
1969
1970static int python_generate_script(struct tep_handle *pevent, const char *outfile)
1971{
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];
1977 FILE *ofp;
1978
1979 sprintf(fname, "%s.py", outfile);
1980 ofp = fopen(fname, "w");
1981 if (ofp == NULL) {
1982 fprintf(stderr, "couldn't open %s\n", fname);
1983 return -1;
1984 }
1985 fprintf(ofp, "# perf script event handlers, "
1986 "generated by perf script -g python\n");
1987
1988 fprintf(ofp, "# Licensed under the terms of the GNU GPL"
1989 " License version 2\n\n");
1990
1991 fprintf(ofp, "# The common_* event handler fields are the most useful "
1992 "fields common to\n");
1993
1994 fprintf(ofp, "# all events. They don't necessarily correspond to "
1995 "the 'common_*' fields\n");
1996
1997 fprintf(ofp, "# in the format files. Those fields not available as "
1998 "handler params can\n");
1999
2000 fprintf(ofp, "# be retrieved using Python functions of the form "
2001 "common_*(context).\n");
2002
2003 fprintf(ofp, "# See the perf-script-python Documentation for the list "
2004 "of available functions.\n\n");
2005
2006 fprintf(ofp, "from __future__ import print_function\n\n");
2007 fprintf(ofp, "import os\n");
2008 fprintf(ofp, "import sys\n\n");
2009
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");
2014
2015 fprintf(ofp, "def trace_begin():\n");
2016 fprintf(ofp, "\tprint(\"in trace_begin\")\n\n");
2017
2018 fprintf(ofp, "def trace_end():\n");
2019 fprintf(ofp, "\tprint(\"in trace_end\")\n\n");
2020
2021 nr_events = tep_get_events_count(pevent);
2022 all_events = tep_list_events(pevent, TEP_EVENT_SORT_ID);
2023
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, ");
2035
2036 not_first = 0;
2037 count = 0;
2038
2039 for (f = event->format.fields; f; f = f->next) {
2040 if (not_first++)
2041 fprintf(ofp, ", ");
2042 if (++count % 5 == 0)
2043 fprintf(ofp, "\n\t");
2044
2045 fprintf(ofp, "%s", f->name);
2046 }
2047 if (not_first++)
2048 fprintf(ofp, ", ");
2049 if (++count % 5 == 0)
2050 fprintf(ofp, "\n\t\t");
2051 fprintf(ofp, "perf_sample_dict");
2052
2053 fprintf(ofp, "):\n");
2054
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");
2058
2059 fprintf(ofp, "\t\tprint(\"");
2060
2061 not_first = 0;
2062 count = 0;
2063
2064 for (f = event->format.fields; f; f = f->next) {
2065 if (not_first++)
2066 fprintf(ofp, ", ");
2067 if (count && count % 3 == 0) {
2068 fprintf(ofp, "\" \\\n\t\t\"");
2069 }
2070 count++;
2071
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");
2080 else
2081 fprintf(ofp, "%%u");
2082 }
2083
2084 fprintf(ofp, "\" %% \\\n\t\t(");
2085
2086 not_first = 0;
2087 count = 0;
2088
2089 for (f = event->format.fields; f; f = f->next) {
2090 if (not_first++)
2091 fprintf(ofp, ", ");
2092
2093 if (++count % 5 == 0)
2094 fprintf(ofp, "\n\t\t");
2095
2096 if (f->flags & TEP_FIELD_IS_FLAG) {
2097 if ((count - 1) % 5 != 0) {
2098 fprintf(ofp, "\n\t\t");
2099 count = 4;
2100 }
2101 fprintf(ofp, "flag_str(\"");
2102 fprintf(ofp, "%s__%s\", ", event->system,
2103 event->name);
2104 fprintf(ofp, "\"%s\", %s)", f->name,
2105 f->name);
2106 } else if (f->flags & TEP_FIELD_IS_SYMBOLIC) {
2107 if ((count - 1) % 5 != 0) {
2108 fprintf(ofp, "\n\t\t");
2109 count = 4;
2110 }
2111 fprintf(ofp, "symbol_str(\"");
2112 fprintf(ofp, "%s__%s\", ", event->system,
2113 event->name);
2114 fprintf(ofp, "\"%s\", %s)", f->name,
2115 f->name);
2116 } else
2117 fprintf(ofp, "%s", f->name);
2118 }
2119
2120 fprintf(ofp, "))\n\n");
2121
2122 fprintf(ofp, "\t\tprint('Sample: {'+"
2123 "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
2124
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");
2135
2136 }
2137
2138 fprintf(ofp, "def trace_unhandled(event_name, context, "
2139 "event_fields_dict, perf_sample_dict):\n");
2140
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");
2144
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");
2149
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");
2153
2154 fclose(ofp);
2155
2156 fprintf(stderr, "generated Python script: %s\n", fname);
2157
2158 return 0;
2159}
2160
2161struct scripting_ops python_scripting_ops = {
2162 .name = "Python",
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,
2174};
1/*
2 * trace-event-python. Feed trace events to an embedded Python interpreter.
3 *
4 * Copyright (C) 2010 Tom Zanussi <tzanussi@gmail.com>
5 *
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.
10 *
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.
15 *
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
19 *
20 */
21
22#include <Python.h>
23
24#include <inttypes.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
28#include <stdbool.h>
29#include <errno.h>
30#include <linux/bitmap.h>
31#include <linux/compiler.h>
32#include <linux/time64.h>
33
34#include "../build-id.h"
35#include "../counts.h"
36#include "../debug.h"
37#include "../dso.h"
38#include "../callchain.h"
39#include "../evsel.h"
40#include "../event.h"
41#include "../thread.h"
42#include "../comm.h"
43#include "../machine.h"
44#include "../db-export.h"
45#include "../thread-stack.h"
46#include "../trace-event.h"
47#include "../call-path.h"
48#include "map.h"
49#include "symbol.h"
50#include "thread_map.h"
51#include "print_binary.h"
52#include "stat.h"
53#include "mem-events.h"
54
55#if PY_MAJOR_VERSION < 3
56#define _PyUnicode_FromString(arg) \
57 PyString_FromString(arg)
58#define _PyUnicode_FromStringAndSize(arg1, arg2) \
59 PyString_FromStringAndSize((arg1), (arg2))
60#define _PyBytes_FromStringAndSize(arg1, arg2) \
61 PyString_FromStringAndSize((arg1), (arg2))
62#define _PyLong_FromLong(arg) \
63 PyInt_FromLong(arg)
64#define _PyLong_AsLong(arg) \
65 PyInt_AsLong(arg)
66#define _PyCapsule_New(arg1, arg2, arg3) \
67 PyCObject_FromVoidPtr((arg1), (arg2))
68
69PyMODINIT_FUNC initperf_trace_context(void);
70#else
71#define _PyUnicode_FromString(arg) \
72 PyUnicode_FromString(arg)
73#define _PyUnicode_FromStringAndSize(arg1, arg2) \
74 PyUnicode_FromStringAndSize((arg1), (arg2))
75#define _PyBytes_FromStringAndSize(arg1, arg2) \
76 PyBytes_FromStringAndSize((arg1), (arg2))
77#define _PyLong_FromLong(arg) \
78 PyLong_FromLong(arg)
79#define _PyLong_AsLong(arg) \
80 PyLong_AsLong(arg)
81#define _PyCapsule_New(arg1, arg2, arg3) \
82 PyCapsule_New((arg1), (arg2), (arg3))
83
84PyMODINIT_FUNC PyInit_perf_trace_context(void);
85#endif
86
87#define TRACE_EVENT_TYPE_MAX \
88 ((1 << (sizeof(unsigned short) * 8)) - 1)
89
90static DECLARE_BITMAP(events_defined, TRACE_EVENT_TYPE_MAX);
91
92#define MAX_FIELDS 64
93#define N_COMMON_FIELDS 7
94
95extern struct scripting_context *scripting_context;
96
97static char *cur_field_name;
98static int zero_flag_atom;
99
100static PyObject *main_module, *main_dict;
101
102struct tables {
103 struct db_export dbe;
104 PyObject *evsel_handler;
105 PyObject *machine_handler;
106 PyObject *thread_handler;
107 PyObject *comm_handler;
108 PyObject *comm_thread_handler;
109 PyObject *dso_handler;
110 PyObject *symbol_handler;
111 PyObject *branch_type_handler;
112 PyObject *sample_handler;
113 PyObject *call_path_handler;
114 PyObject *call_return_handler;
115 PyObject *synth_handler;
116 PyObject *context_switch_handler;
117 bool db_export_mode;
118};
119
120static struct tables tables_global;
121
122static void handler_call_die(const char *handler_name) __noreturn;
123static void handler_call_die(const char *handler_name)
124{
125 PyErr_Print();
126 Py_FatalError("problem in Python trace event handler");
127 // Py_FatalError does not return
128 // but we have to make the compiler happy
129 abort();
130}
131
132/*
133 * Insert val into into the dictionary and decrement the reference counter.
134 * This is necessary for dictionaries since PyDict_SetItemString() does not
135 * steal a reference, as opposed to PyTuple_SetItem().
136 */
137static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
138{
139 PyDict_SetItemString(dict, key, val);
140 Py_DECREF(val);
141}
142
143static PyObject *get_handler(const char *handler_name)
144{
145 PyObject *handler;
146
147 handler = PyDict_GetItemString(main_dict, handler_name);
148 if (handler && !PyCallable_Check(handler))
149 return NULL;
150 return handler;
151}
152
153static int get_argument_count(PyObject *handler)
154{
155 int arg_count = 0;
156
157 /*
158 * The attribute for the code object is func_code in Python 2,
159 * whereas it is __code__ in Python 3.0+.
160 */
161 PyObject *code_obj = PyObject_GetAttrString(handler,
162 "func_code");
163 if (PyErr_Occurred()) {
164 PyErr_Clear();
165 code_obj = PyObject_GetAttrString(handler,
166 "__code__");
167 }
168 PyErr_Clear();
169 if (code_obj) {
170 PyObject *arg_count_obj = PyObject_GetAttrString(code_obj,
171 "co_argcount");
172 if (arg_count_obj) {
173 arg_count = (int) _PyLong_AsLong(arg_count_obj);
174 Py_DECREF(arg_count_obj);
175 }
176 Py_DECREF(code_obj);
177 }
178 return arg_count;
179}
180
181static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
182{
183 PyObject *retval;
184
185 retval = PyObject_CallObject(handler, args);
186 if (retval == NULL)
187 handler_call_die(die_msg);
188 Py_DECREF(retval);
189}
190
191static void try_call_object(const char *handler_name, PyObject *args)
192{
193 PyObject *handler;
194
195 handler = get_handler(handler_name);
196 if (handler)
197 call_object(handler, args, handler_name);
198}
199
200static void define_value(enum tep_print_arg_type field_type,
201 const char *ev_name,
202 const char *field_name,
203 const char *field_value,
204 const char *field_str)
205{
206 const char *handler_name = "define_flag_value";
207 PyObject *t;
208 unsigned long long value;
209 unsigned n = 0;
210
211 if (field_type == TEP_PRINT_SYMBOL)
212 handler_name = "define_symbolic_value";
213
214 t = PyTuple_New(4);
215 if (!t)
216 Py_FatalError("couldn't create Python tuple");
217
218 value = eval_flag(field_value);
219
220 PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
221 PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
222 PyTuple_SetItem(t, n++, _PyLong_FromLong(value));
223 PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_str));
224
225 try_call_object(handler_name, t);
226
227 Py_DECREF(t);
228}
229
230static void define_values(enum tep_print_arg_type field_type,
231 struct tep_print_flag_sym *field,
232 const char *ev_name,
233 const char *field_name)
234{
235 define_value(field_type, ev_name, field_name, field->value,
236 field->str);
237
238 if (field->next)
239 define_values(field_type, field->next, ev_name, field_name);
240}
241
242static void define_field(enum tep_print_arg_type field_type,
243 const char *ev_name,
244 const char *field_name,
245 const char *delim)
246{
247 const char *handler_name = "define_flag_field";
248 PyObject *t;
249 unsigned n = 0;
250
251 if (field_type == TEP_PRINT_SYMBOL)
252 handler_name = "define_symbolic_field";
253
254 if (field_type == TEP_PRINT_FLAGS)
255 t = PyTuple_New(3);
256 else
257 t = PyTuple_New(2);
258 if (!t)
259 Py_FatalError("couldn't create Python tuple");
260
261 PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
262 PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
263 if (field_type == TEP_PRINT_FLAGS)
264 PyTuple_SetItem(t, n++, _PyUnicode_FromString(delim));
265
266 try_call_object(handler_name, t);
267
268 Py_DECREF(t);
269}
270
271static void define_event_symbols(struct tep_event *event,
272 const char *ev_name,
273 struct tep_print_arg *args)
274{
275 if (args == NULL)
276 return;
277
278 switch (args->type) {
279 case TEP_PRINT_NULL:
280 break;
281 case TEP_PRINT_ATOM:
282 define_value(TEP_PRINT_FLAGS, ev_name, cur_field_name, "0",
283 args->atom.atom);
284 zero_flag_atom = 0;
285 break;
286 case TEP_PRINT_FIELD:
287 free(cur_field_name);
288 cur_field_name = strdup(args->field.name);
289 break;
290 case TEP_PRINT_FLAGS:
291 define_event_symbols(event, ev_name, args->flags.field);
292 define_field(TEP_PRINT_FLAGS, ev_name, cur_field_name,
293 args->flags.delim);
294 define_values(TEP_PRINT_FLAGS, args->flags.flags, ev_name,
295 cur_field_name);
296 break;
297 case TEP_PRINT_SYMBOL:
298 define_event_symbols(event, ev_name, args->symbol.field);
299 define_field(TEP_PRINT_SYMBOL, ev_name, cur_field_name, NULL);
300 define_values(TEP_PRINT_SYMBOL, args->symbol.symbols, ev_name,
301 cur_field_name);
302 break;
303 case TEP_PRINT_HEX:
304 case TEP_PRINT_HEX_STR:
305 define_event_symbols(event, ev_name, args->hex.field);
306 define_event_symbols(event, ev_name, args->hex.size);
307 break;
308 case TEP_PRINT_INT_ARRAY:
309 define_event_symbols(event, ev_name, args->int_array.field);
310 define_event_symbols(event, ev_name, args->int_array.count);
311 define_event_symbols(event, ev_name, args->int_array.el_size);
312 break;
313 case TEP_PRINT_STRING:
314 break;
315 case TEP_PRINT_TYPE:
316 define_event_symbols(event, ev_name, args->typecast.item);
317 break;
318 case TEP_PRINT_OP:
319 if (strcmp(args->op.op, ":") == 0)
320 zero_flag_atom = 1;
321 define_event_symbols(event, ev_name, args->op.left);
322 define_event_symbols(event, ev_name, args->op.right);
323 break;
324 default:
325 /* gcc warns for these? */
326 case TEP_PRINT_BSTRING:
327 case TEP_PRINT_DYNAMIC_ARRAY:
328 case TEP_PRINT_DYNAMIC_ARRAY_LEN:
329 case TEP_PRINT_FUNC:
330 case TEP_PRINT_BITMASK:
331 /* we should warn... */
332 return;
333 }
334
335 if (args->next)
336 define_event_symbols(event, ev_name, args->next);
337}
338
339static PyObject *get_field_numeric_entry(struct tep_event *event,
340 struct tep_format_field *field, void *data)
341{
342 bool is_array = field->flags & TEP_FIELD_IS_ARRAY;
343 PyObject *obj = NULL, *list = NULL;
344 unsigned long long val;
345 unsigned int item_size, n_items, i;
346
347 if (is_array) {
348 list = PyList_New(field->arraylen);
349 item_size = field->size / field->arraylen;
350 n_items = field->arraylen;
351 } else {
352 item_size = field->size;
353 n_items = 1;
354 }
355
356 for (i = 0; i < n_items; i++) {
357
358 val = read_size(event, data + field->offset + i * item_size,
359 item_size);
360 if (field->flags & TEP_FIELD_IS_SIGNED) {
361 if ((long long)val >= LONG_MIN &&
362 (long long)val <= LONG_MAX)
363 obj = _PyLong_FromLong(val);
364 else
365 obj = PyLong_FromLongLong(val);
366 } else {
367 if (val <= LONG_MAX)
368 obj = _PyLong_FromLong(val);
369 else
370 obj = PyLong_FromUnsignedLongLong(val);
371 }
372 if (is_array)
373 PyList_SET_ITEM(list, i, obj);
374 }
375 if (is_array)
376 obj = list;
377 return obj;
378}
379
380static const char *get_dsoname(struct map *map)
381{
382 const char *dsoname = "[unknown]";
383
384 if (map && map->dso) {
385 if (symbol_conf.show_kernel_path && map->dso->long_name)
386 dsoname = map->dso->long_name;
387 else
388 dsoname = map->dso->name;
389 }
390
391 return dsoname;
392}
393
394static PyObject *python_process_callchain(struct perf_sample *sample,
395 struct evsel *evsel,
396 struct addr_location *al)
397{
398 PyObject *pylist;
399
400 pylist = PyList_New(0);
401 if (!pylist)
402 Py_FatalError("couldn't create Python list");
403
404 if (!symbol_conf.use_callchain || !sample->callchain)
405 goto exit;
406
407 if (thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
408 sample, NULL, NULL,
409 scripting_max_stack) != 0) {
410 pr_err("Failed to resolve callchain. Skipping\n");
411 goto exit;
412 }
413 callchain_cursor_commit(&callchain_cursor);
414
415
416 while (1) {
417 PyObject *pyelem;
418 struct callchain_cursor_node *node;
419 node = callchain_cursor_current(&callchain_cursor);
420 if (!node)
421 break;
422
423 pyelem = PyDict_New();
424 if (!pyelem)
425 Py_FatalError("couldn't create Python dictionary");
426
427
428 pydict_set_item_string_decref(pyelem, "ip",
429 PyLong_FromUnsignedLongLong(node->ip));
430
431 if (node->sym) {
432 PyObject *pysym = PyDict_New();
433 if (!pysym)
434 Py_FatalError("couldn't create Python dictionary");
435 pydict_set_item_string_decref(pysym, "start",
436 PyLong_FromUnsignedLongLong(node->sym->start));
437 pydict_set_item_string_decref(pysym, "end",
438 PyLong_FromUnsignedLongLong(node->sym->end));
439 pydict_set_item_string_decref(pysym, "binding",
440 _PyLong_FromLong(node->sym->binding));
441 pydict_set_item_string_decref(pysym, "name",
442 _PyUnicode_FromStringAndSize(node->sym->name,
443 node->sym->namelen));
444 pydict_set_item_string_decref(pyelem, "sym", pysym);
445 }
446
447 if (node->map) {
448 const char *dsoname = get_dsoname(node->map);
449
450 pydict_set_item_string_decref(pyelem, "dso",
451 _PyUnicode_FromString(dsoname));
452 }
453
454 callchain_cursor_advance(&callchain_cursor);
455 PyList_Append(pylist, pyelem);
456 Py_DECREF(pyelem);
457 }
458
459exit:
460 return pylist;
461}
462
463static PyObject *python_process_brstack(struct perf_sample *sample,
464 struct thread *thread)
465{
466 struct branch_stack *br = sample->branch_stack;
467 PyObject *pylist;
468 u64 i;
469
470 pylist = PyList_New(0);
471 if (!pylist)
472 Py_FatalError("couldn't create Python list");
473
474 if (!(br && br->nr))
475 goto exit;
476
477 for (i = 0; i < br->nr; i++) {
478 PyObject *pyelem;
479 struct addr_location al;
480 const char *dsoname;
481
482 pyelem = PyDict_New();
483 if (!pyelem)
484 Py_FatalError("couldn't create Python dictionary");
485
486 pydict_set_item_string_decref(pyelem, "from",
487 PyLong_FromUnsignedLongLong(br->entries[i].from));
488 pydict_set_item_string_decref(pyelem, "to",
489 PyLong_FromUnsignedLongLong(br->entries[i].to));
490 pydict_set_item_string_decref(pyelem, "mispred",
491 PyBool_FromLong(br->entries[i].flags.mispred));
492 pydict_set_item_string_decref(pyelem, "predicted",
493 PyBool_FromLong(br->entries[i].flags.predicted));
494 pydict_set_item_string_decref(pyelem, "in_tx",
495 PyBool_FromLong(br->entries[i].flags.in_tx));
496 pydict_set_item_string_decref(pyelem, "abort",
497 PyBool_FromLong(br->entries[i].flags.abort));
498 pydict_set_item_string_decref(pyelem, "cycles",
499 PyLong_FromUnsignedLongLong(br->entries[i].flags.cycles));
500
501 thread__find_map_fb(thread, sample->cpumode,
502 br->entries[i].from, &al);
503 dsoname = get_dsoname(al.map);
504 pydict_set_item_string_decref(pyelem, "from_dsoname",
505 _PyUnicode_FromString(dsoname));
506
507 thread__find_map_fb(thread, sample->cpumode,
508 br->entries[i].to, &al);
509 dsoname = get_dsoname(al.map);
510 pydict_set_item_string_decref(pyelem, "to_dsoname",
511 _PyUnicode_FromString(dsoname));
512
513 PyList_Append(pylist, pyelem);
514 Py_DECREF(pyelem);
515 }
516
517exit:
518 return pylist;
519}
520
521static unsigned long get_offset(struct symbol *sym, struct addr_location *al)
522{
523 unsigned long offset;
524
525 if (al->addr < sym->end)
526 offset = al->addr - sym->start;
527 else
528 offset = al->addr - al->map->start - sym->start;
529
530 return offset;
531}
532
533static int get_symoff(struct symbol *sym, struct addr_location *al,
534 bool print_off, char *bf, int size)
535{
536 unsigned long offset;
537
538 if (!sym || !sym->name[0])
539 return scnprintf(bf, size, "%s", "[unknown]");
540
541 if (!print_off)
542 return scnprintf(bf, size, "%s", sym->name);
543
544 offset = get_offset(sym, al);
545
546 return scnprintf(bf, size, "%s+0x%x", sym->name, offset);
547}
548
549static int get_br_mspred(struct branch_flags *flags, char *bf, int size)
550{
551 if (!flags->mispred && !flags->predicted)
552 return scnprintf(bf, size, "%s", "-");
553
554 if (flags->mispred)
555 return scnprintf(bf, size, "%s", "M");
556
557 return scnprintf(bf, size, "%s", "P");
558}
559
560static PyObject *python_process_brstacksym(struct perf_sample *sample,
561 struct thread *thread)
562{
563 struct branch_stack *br = sample->branch_stack;
564 PyObject *pylist;
565 u64 i;
566 char bf[512];
567 struct addr_location al;
568
569 pylist = PyList_New(0);
570 if (!pylist)
571 Py_FatalError("couldn't create Python list");
572
573 if (!(br && br->nr))
574 goto exit;
575
576 for (i = 0; i < br->nr; i++) {
577 PyObject *pyelem;
578
579 pyelem = PyDict_New();
580 if (!pyelem)
581 Py_FatalError("couldn't create Python dictionary");
582
583 thread__find_symbol_fb(thread, sample->cpumode,
584 br->entries[i].from, &al);
585 get_symoff(al.sym, &al, true, bf, sizeof(bf));
586 pydict_set_item_string_decref(pyelem, "from",
587 _PyUnicode_FromString(bf));
588
589 thread__find_symbol_fb(thread, sample->cpumode,
590 br->entries[i].to, &al);
591 get_symoff(al.sym, &al, true, bf, sizeof(bf));
592 pydict_set_item_string_decref(pyelem, "to",
593 _PyUnicode_FromString(bf));
594
595 get_br_mspred(&br->entries[i].flags, bf, sizeof(bf));
596 pydict_set_item_string_decref(pyelem, "pred",
597 _PyUnicode_FromString(bf));
598
599 if (br->entries[i].flags.in_tx) {
600 pydict_set_item_string_decref(pyelem, "in_tx",
601 _PyUnicode_FromString("X"));
602 } else {
603 pydict_set_item_string_decref(pyelem, "in_tx",
604 _PyUnicode_FromString("-"));
605 }
606
607 if (br->entries[i].flags.abort) {
608 pydict_set_item_string_decref(pyelem, "abort",
609 _PyUnicode_FromString("A"));
610 } else {
611 pydict_set_item_string_decref(pyelem, "abort",
612 _PyUnicode_FromString("-"));
613 }
614
615 PyList_Append(pylist, pyelem);
616 Py_DECREF(pyelem);
617 }
618
619exit:
620 return pylist;
621}
622
623static PyObject *get_sample_value_as_tuple(struct sample_read_value *value)
624{
625 PyObject *t;
626
627 t = PyTuple_New(2);
628 if (!t)
629 Py_FatalError("couldn't create Python tuple");
630 PyTuple_SetItem(t, 0, PyLong_FromUnsignedLongLong(value->id));
631 PyTuple_SetItem(t, 1, PyLong_FromUnsignedLongLong(value->value));
632 return t;
633}
634
635static void set_sample_read_in_dict(PyObject *dict_sample,
636 struct perf_sample *sample,
637 struct evsel *evsel)
638{
639 u64 read_format = evsel->core.attr.read_format;
640 PyObject *values;
641 unsigned int i;
642
643 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
644 pydict_set_item_string_decref(dict_sample, "time_enabled",
645 PyLong_FromUnsignedLongLong(sample->read.time_enabled));
646 }
647
648 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
649 pydict_set_item_string_decref(dict_sample, "time_running",
650 PyLong_FromUnsignedLongLong(sample->read.time_running));
651 }
652
653 if (read_format & PERF_FORMAT_GROUP)
654 values = PyList_New(sample->read.group.nr);
655 else
656 values = PyList_New(1);
657
658 if (!values)
659 Py_FatalError("couldn't create Python list");
660
661 if (read_format & PERF_FORMAT_GROUP) {
662 for (i = 0; i < sample->read.group.nr; i++) {
663 PyObject *t = get_sample_value_as_tuple(&sample->read.group.values[i]);
664 PyList_SET_ITEM(values, i, t);
665 }
666 } else {
667 PyObject *t = get_sample_value_as_tuple(&sample->read.one);
668 PyList_SET_ITEM(values, 0, t);
669 }
670 pydict_set_item_string_decref(dict_sample, "values", values);
671}
672
673static void set_sample_datasrc_in_dict(PyObject *dict,
674 struct perf_sample *sample)
675{
676 struct mem_info mi = { .data_src.val = sample->data_src };
677 char decode[100];
678
679 pydict_set_item_string_decref(dict, "datasrc",
680 PyLong_FromUnsignedLongLong(sample->data_src));
681
682 perf_script__meminfo_scnprintf(decode, 100, &mi);
683
684 pydict_set_item_string_decref(dict, "datasrc_decode",
685 _PyUnicode_FromString(decode));
686}
687
688static int regs_map(struct regs_dump *regs, uint64_t mask, char *bf, int size)
689{
690 unsigned int i = 0, r;
691 int printed = 0;
692
693 bf[0] = 0;
694
695 for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
696 u64 val = regs->regs[i++];
697
698 printed += scnprintf(bf + printed, size - printed,
699 "%5s:0x%" PRIx64 " ",
700 perf_reg_name(r), val);
701 }
702
703 return printed;
704}
705
706static void set_regs_in_dict(PyObject *dict,
707 struct perf_sample *sample,
708 struct evsel *evsel)
709{
710 struct perf_event_attr *attr = &evsel->core.attr;
711 char bf[512];
712
713 regs_map(&sample->intr_regs, attr->sample_regs_intr, bf, sizeof(bf));
714
715 pydict_set_item_string_decref(dict, "iregs",
716 _PyUnicode_FromString(bf));
717
718 regs_map(&sample->user_regs, attr->sample_regs_user, bf, sizeof(bf));
719
720 pydict_set_item_string_decref(dict, "uregs",
721 _PyUnicode_FromString(bf));
722}
723
724static PyObject *get_perf_sample_dict(struct perf_sample *sample,
725 struct evsel *evsel,
726 struct addr_location *al,
727 PyObject *callchain)
728{
729 PyObject *dict, *dict_sample, *brstack, *brstacksym;
730
731 dict = PyDict_New();
732 if (!dict)
733 Py_FatalError("couldn't create Python dictionary");
734
735 dict_sample = PyDict_New();
736 if (!dict_sample)
737 Py_FatalError("couldn't create Python dictionary");
738
739 pydict_set_item_string_decref(dict, "ev_name", _PyUnicode_FromString(perf_evsel__name(evsel)));
740 pydict_set_item_string_decref(dict, "attr", _PyBytes_FromStringAndSize((const char *)&evsel->core.attr, sizeof(evsel->core.attr)));
741
742 pydict_set_item_string_decref(dict_sample, "pid",
743 _PyLong_FromLong(sample->pid));
744 pydict_set_item_string_decref(dict_sample, "tid",
745 _PyLong_FromLong(sample->tid));
746 pydict_set_item_string_decref(dict_sample, "cpu",
747 _PyLong_FromLong(sample->cpu));
748 pydict_set_item_string_decref(dict_sample, "ip",
749 PyLong_FromUnsignedLongLong(sample->ip));
750 pydict_set_item_string_decref(dict_sample, "time",
751 PyLong_FromUnsignedLongLong(sample->time));
752 pydict_set_item_string_decref(dict_sample, "period",
753 PyLong_FromUnsignedLongLong(sample->period));
754 pydict_set_item_string_decref(dict_sample, "phys_addr",
755 PyLong_FromUnsignedLongLong(sample->phys_addr));
756 pydict_set_item_string_decref(dict_sample, "addr",
757 PyLong_FromUnsignedLongLong(sample->addr));
758 set_sample_read_in_dict(dict_sample, sample, evsel);
759 pydict_set_item_string_decref(dict_sample, "weight",
760 PyLong_FromUnsignedLongLong(sample->weight));
761 pydict_set_item_string_decref(dict_sample, "transaction",
762 PyLong_FromUnsignedLongLong(sample->transaction));
763 set_sample_datasrc_in_dict(dict_sample, sample);
764 pydict_set_item_string_decref(dict, "sample", dict_sample);
765
766 pydict_set_item_string_decref(dict, "raw_buf", _PyBytes_FromStringAndSize(
767 (const char *)sample->raw_data, sample->raw_size));
768 pydict_set_item_string_decref(dict, "comm",
769 _PyUnicode_FromString(thread__comm_str(al->thread)));
770 if (al->map) {
771 pydict_set_item_string_decref(dict, "dso",
772 _PyUnicode_FromString(al->map->dso->name));
773 }
774 if (al->sym) {
775 pydict_set_item_string_decref(dict, "symbol",
776 _PyUnicode_FromString(al->sym->name));
777 }
778
779 pydict_set_item_string_decref(dict, "callchain", callchain);
780
781 brstack = python_process_brstack(sample, al->thread);
782 pydict_set_item_string_decref(dict, "brstack", brstack);
783
784 brstacksym = python_process_brstacksym(sample, al->thread);
785 pydict_set_item_string_decref(dict, "brstacksym", brstacksym);
786
787 set_regs_in_dict(dict, sample, evsel);
788
789 return dict;
790}
791
792static void python_process_tracepoint(struct perf_sample *sample,
793 struct evsel *evsel,
794 struct addr_location *al)
795{
796 struct tep_event *event = evsel->tp_format;
797 PyObject *handler, *context, *t, *obj = NULL, *callchain;
798 PyObject *dict = NULL, *all_entries_dict = NULL;
799 static char handler_name[256];
800 struct tep_format_field *field;
801 unsigned long s, ns;
802 unsigned n = 0;
803 int pid;
804 int cpu = sample->cpu;
805 void *data = sample->raw_data;
806 unsigned long long nsecs = sample->time;
807 const char *comm = thread__comm_str(al->thread);
808 const char *default_handler_name = "trace_unhandled";
809
810 if (!event) {
811 snprintf(handler_name, sizeof(handler_name),
812 "ug! no event found for type %" PRIu64, (u64)evsel->core.attr.config);
813 Py_FatalError(handler_name);
814 }
815
816 pid = raw_field_value(event, "common_pid", data);
817
818 sprintf(handler_name, "%s__%s", event->system, event->name);
819
820 if (!test_and_set_bit(event->id, events_defined))
821 define_event_symbols(event, handler_name, event->print_fmt.args);
822
823 handler = get_handler(handler_name);
824 if (!handler) {
825 handler = get_handler(default_handler_name);
826 if (!handler)
827 return;
828 dict = PyDict_New();
829 if (!dict)
830 Py_FatalError("couldn't create Python dict");
831 }
832
833 t = PyTuple_New(MAX_FIELDS);
834 if (!t)
835 Py_FatalError("couldn't create Python tuple");
836
837
838 s = nsecs / NSEC_PER_SEC;
839 ns = nsecs - s * NSEC_PER_SEC;
840
841 scripting_context->event_data = data;
842 scripting_context->pevent = evsel->tp_format->tep;
843
844 context = _PyCapsule_New(scripting_context, NULL, NULL);
845
846 PyTuple_SetItem(t, n++, _PyUnicode_FromString(handler_name));
847 PyTuple_SetItem(t, n++, context);
848
849 /* ip unwinding */
850 callchain = python_process_callchain(sample, evsel, al);
851 /* Need an additional reference for the perf_sample dict */
852 Py_INCREF(callchain);
853
854 if (!dict) {
855 PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
856 PyTuple_SetItem(t, n++, _PyLong_FromLong(s));
857 PyTuple_SetItem(t, n++, _PyLong_FromLong(ns));
858 PyTuple_SetItem(t, n++, _PyLong_FromLong(pid));
859 PyTuple_SetItem(t, n++, _PyUnicode_FromString(comm));
860 PyTuple_SetItem(t, n++, callchain);
861 } else {
862 pydict_set_item_string_decref(dict, "common_cpu", _PyLong_FromLong(cpu));
863 pydict_set_item_string_decref(dict, "common_s", _PyLong_FromLong(s));
864 pydict_set_item_string_decref(dict, "common_ns", _PyLong_FromLong(ns));
865 pydict_set_item_string_decref(dict, "common_pid", _PyLong_FromLong(pid));
866 pydict_set_item_string_decref(dict, "common_comm", _PyUnicode_FromString(comm));
867 pydict_set_item_string_decref(dict, "common_callchain", callchain);
868 }
869 for (field = event->format.fields; field; field = field->next) {
870 unsigned int offset, len;
871 unsigned long long val;
872
873 if (field->flags & TEP_FIELD_IS_ARRAY) {
874 offset = field->offset;
875 len = field->size;
876 if (field->flags & TEP_FIELD_IS_DYNAMIC) {
877 val = tep_read_number(scripting_context->pevent,
878 data + offset, len);
879 offset = val;
880 len = offset >> 16;
881 offset &= 0xffff;
882 }
883 if (field->flags & TEP_FIELD_IS_STRING &&
884 is_printable_array(data + offset, len)) {
885 obj = _PyUnicode_FromString((char *) data + offset);
886 } else {
887 obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
888 field->flags &= ~TEP_FIELD_IS_STRING;
889 }
890 } else { /* FIELD_IS_NUMERIC */
891 obj = get_field_numeric_entry(event, field, data);
892 }
893 if (!dict)
894 PyTuple_SetItem(t, n++, obj);
895 else
896 pydict_set_item_string_decref(dict, field->name, obj);
897
898 }
899
900 if (dict)
901 PyTuple_SetItem(t, n++, dict);
902
903 if (get_argument_count(handler) == (int) n + 1) {
904 all_entries_dict = get_perf_sample_dict(sample, evsel, al,
905 callchain);
906 PyTuple_SetItem(t, n++, all_entries_dict);
907 } else {
908 Py_DECREF(callchain);
909 }
910
911 if (_PyTuple_Resize(&t, n) == -1)
912 Py_FatalError("error resizing Python tuple");
913
914 if (!dict)
915 call_object(handler, t, handler_name);
916 else
917 call_object(handler, t, default_handler_name);
918
919 Py_DECREF(t);
920}
921
922static PyObject *tuple_new(unsigned int sz)
923{
924 PyObject *t;
925
926 t = PyTuple_New(sz);
927 if (!t)
928 Py_FatalError("couldn't create Python tuple");
929 return t;
930}
931
932static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
933{
934#if BITS_PER_LONG == 64
935 return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
936#endif
937#if BITS_PER_LONG == 32
938 return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
939#endif
940}
941
942static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
943{
944 return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
945}
946
947static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
948{
949 return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
950}
951
952static int tuple_set_bytes(PyObject *t, unsigned int pos, void *bytes,
953 unsigned int sz)
954{
955 return PyTuple_SetItem(t, pos, _PyBytes_FromStringAndSize(bytes, sz));
956}
957
958static int python_export_evsel(struct db_export *dbe, struct evsel *evsel)
959{
960 struct tables *tables = container_of(dbe, struct tables, dbe);
961 PyObject *t;
962
963 t = tuple_new(2);
964
965 tuple_set_u64(t, 0, evsel->db_id);
966 tuple_set_string(t, 1, perf_evsel__name(evsel));
967
968 call_object(tables->evsel_handler, t, "evsel_table");
969
970 Py_DECREF(t);
971
972 return 0;
973}
974
975static int python_export_machine(struct db_export *dbe,
976 struct machine *machine)
977{
978 struct tables *tables = container_of(dbe, struct tables, dbe);
979 PyObject *t;
980
981 t = tuple_new(3);
982
983 tuple_set_u64(t, 0, machine->db_id);
984 tuple_set_s32(t, 1, machine->pid);
985 tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
986
987 call_object(tables->machine_handler, t, "machine_table");
988
989 Py_DECREF(t);
990
991 return 0;
992}
993
994static int python_export_thread(struct db_export *dbe, struct thread *thread,
995 u64 main_thread_db_id, struct machine *machine)
996{
997 struct tables *tables = container_of(dbe, struct tables, dbe);
998 PyObject *t;
999
1000 t = tuple_new(5);
1001
1002 tuple_set_u64(t, 0, thread->db_id);
1003 tuple_set_u64(t, 1, machine->db_id);
1004 tuple_set_u64(t, 2, main_thread_db_id);
1005 tuple_set_s32(t, 3, thread->pid_);
1006 tuple_set_s32(t, 4, thread->tid);
1007
1008 call_object(tables->thread_handler, t, "thread_table");
1009
1010 Py_DECREF(t);
1011
1012 return 0;
1013}
1014
1015static int python_export_comm(struct db_export *dbe, struct comm *comm,
1016 struct thread *thread)
1017{
1018 struct tables *tables = container_of(dbe, struct tables, dbe);
1019 PyObject *t;
1020
1021 t = tuple_new(5);
1022
1023 tuple_set_u64(t, 0, comm->db_id);
1024 tuple_set_string(t, 1, comm__str(comm));
1025 tuple_set_u64(t, 2, thread->db_id);
1026 tuple_set_u64(t, 3, comm->start);
1027 tuple_set_s32(t, 4, comm->exec);
1028
1029 call_object(tables->comm_handler, t, "comm_table");
1030
1031 Py_DECREF(t);
1032
1033 return 0;
1034}
1035
1036static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
1037 struct comm *comm, struct thread *thread)
1038{
1039 struct tables *tables = container_of(dbe, struct tables, dbe);
1040 PyObject *t;
1041
1042 t = tuple_new(3);
1043
1044 tuple_set_u64(t, 0, db_id);
1045 tuple_set_u64(t, 1, comm->db_id);
1046 tuple_set_u64(t, 2, thread->db_id);
1047
1048 call_object(tables->comm_thread_handler, t, "comm_thread_table");
1049
1050 Py_DECREF(t);
1051
1052 return 0;
1053}
1054
1055static int python_export_dso(struct db_export *dbe, struct dso *dso,
1056 struct machine *machine)
1057{
1058 struct tables *tables = container_of(dbe, struct tables, dbe);
1059 char sbuild_id[SBUILD_ID_SIZE];
1060 PyObject *t;
1061
1062 build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);
1063
1064 t = tuple_new(5);
1065
1066 tuple_set_u64(t, 0, dso->db_id);
1067 tuple_set_u64(t, 1, machine->db_id);
1068 tuple_set_string(t, 2, dso->short_name);
1069 tuple_set_string(t, 3, dso->long_name);
1070 tuple_set_string(t, 4, sbuild_id);
1071
1072 call_object(tables->dso_handler, t, "dso_table");
1073
1074 Py_DECREF(t);
1075
1076 return 0;
1077}
1078
1079static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
1080 struct dso *dso)
1081{
1082 struct tables *tables = container_of(dbe, struct tables, dbe);
1083 u64 *sym_db_id = symbol__priv(sym);
1084 PyObject *t;
1085
1086 t = tuple_new(6);
1087
1088 tuple_set_u64(t, 0, *sym_db_id);
1089 tuple_set_u64(t, 1, dso->db_id);
1090 tuple_set_u64(t, 2, sym->start);
1091 tuple_set_u64(t, 3, sym->end);
1092 tuple_set_s32(t, 4, sym->binding);
1093 tuple_set_string(t, 5, sym->name);
1094
1095 call_object(tables->symbol_handler, t, "symbol_table");
1096
1097 Py_DECREF(t);
1098
1099 return 0;
1100}
1101
1102static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
1103 const char *name)
1104{
1105 struct tables *tables = container_of(dbe, struct tables, dbe);
1106 PyObject *t;
1107
1108 t = tuple_new(2);
1109
1110 tuple_set_s32(t, 0, branch_type);
1111 tuple_set_string(t, 1, name);
1112
1113 call_object(tables->branch_type_handler, t, "branch_type_table");
1114
1115 Py_DECREF(t);
1116
1117 return 0;
1118}
1119
1120static void python_export_sample_table(struct db_export *dbe,
1121 struct export_sample *es)
1122{
1123 struct tables *tables = container_of(dbe, struct tables, dbe);
1124 PyObject *t;
1125
1126 t = tuple_new(24);
1127
1128 tuple_set_u64(t, 0, es->db_id);
1129 tuple_set_u64(t, 1, es->evsel->db_id);
1130 tuple_set_u64(t, 2, es->al->machine->db_id);
1131 tuple_set_u64(t, 3, es->al->thread->db_id);
1132 tuple_set_u64(t, 4, es->comm_db_id);
1133 tuple_set_u64(t, 5, es->dso_db_id);
1134 tuple_set_u64(t, 6, es->sym_db_id);
1135 tuple_set_u64(t, 7, es->offset);
1136 tuple_set_u64(t, 8, es->sample->ip);
1137 tuple_set_u64(t, 9, es->sample->time);
1138 tuple_set_s32(t, 10, es->sample->cpu);
1139 tuple_set_u64(t, 11, es->addr_dso_db_id);
1140 tuple_set_u64(t, 12, es->addr_sym_db_id);
1141 tuple_set_u64(t, 13, es->addr_offset);
1142 tuple_set_u64(t, 14, es->sample->addr);
1143 tuple_set_u64(t, 15, es->sample->period);
1144 tuple_set_u64(t, 16, es->sample->weight);
1145 tuple_set_u64(t, 17, es->sample->transaction);
1146 tuple_set_u64(t, 18, es->sample->data_src);
1147 tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
1148 tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
1149 tuple_set_u64(t, 21, es->call_path_id);
1150 tuple_set_u64(t, 22, es->sample->insn_cnt);
1151 tuple_set_u64(t, 23, es->sample->cyc_cnt);
1152
1153 call_object(tables->sample_handler, t, "sample_table");
1154
1155 Py_DECREF(t);
1156}
1157
1158static void python_export_synth(struct db_export *dbe, struct export_sample *es)
1159{
1160 struct tables *tables = container_of(dbe, struct tables, dbe);
1161 PyObject *t;
1162
1163 t = tuple_new(3);
1164
1165 tuple_set_u64(t, 0, es->db_id);
1166 tuple_set_u64(t, 1, es->evsel->core.attr.config);
1167 tuple_set_bytes(t, 2, es->sample->raw_data, es->sample->raw_size);
1168
1169 call_object(tables->synth_handler, t, "synth_data");
1170
1171 Py_DECREF(t);
1172}
1173
1174static int python_export_sample(struct db_export *dbe,
1175 struct export_sample *es)
1176{
1177 struct tables *tables = container_of(dbe, struct tables, dbe);
1178
1179 python_export_sample_table(dbe, es);
1180
1181 if (es->evsel->core.attr.type == PERF_TYPE_SYNTH && tables->synth_handler)
1182 python_export_synth(dbe, es);
1183
1184 return 0;
1185}
1186
1187static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
1188{
1189 struct tables *tables = container_of(dbe, struct tables, dbe);
1190 PyObject *t;
1191 u64 parent_db_id, sym_db_id;
1192
1193 parent_db_id = cp->parent ? cp->parent->db_id : 0;
1194 sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
1195
1196 t = tuple_new(4);
1197
1198 tuple_set_u64(t, 0, cp->db_id);
1199 tuple_set_u64(t, 1, parent_db_id);
1200 tuple_set_u64(t, 2, sym_db_id);
1201 tuple_set_u64(t, 3, cp->ip);
1202
1203 call_object(tables->call_path_handler, t, "call_path_table");
1204
1205 Py_DECREF(t);
1206
1207 return 0;
1208}
1209
1210static int python_export_call_return(struct db_export *dbe,
1211 struct call_return *cr)
1212{
1213 struct tables *tables = container_of(dbe, struct tables, dbe);
1214 u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
1215 PyObject *t;
1216
1217 t = tuple_new(14);
1218
1219 tuple_set_u64(t, 0, cr->db_id);
1220 tuple_set_u64(t, 1, cr->thread->db_id);
1221 tuple_set_u64(t, 2, comm_db_id);
1222 tuple_set_u64(t, 3, cr->cp->db_id);
1223 tuple_set_u64(t, 4, cr->call_time);
1224 tuple_set_u64(t, 5, cr->return_time);
1225 tuple_set_u64(t, 6, cr->branch_count);
1226 tuple_set_u64(t, 7, cr->call_ref);
1227 tuple_set_u64(t, 8, cr->return_ref);
1228 tuple_set_u64(t, 9, cr->cp->parent->db_id);
1229 tuple_set_s32(t, 10, cr->flags);
1230 tuple_set_u64(t, 11, cr->parent_db_id);
1231 tuple_set_u64(t, 12, cr->insn_count);
1232 tuple_set_u64(t, 13, cr->cyc_count);
1233
1234 call_object(tables->call_return_handler, t, "call_return_table");
1235
1236 Py_DECREF(t);
1237
1238 return 0;
1239}
1240
1241static int python_export_context_switch(struct db_export *dbe, u64 db_id,
1242 struct machine *machine,
1243 struct perf_sample *sample,
1244 u64 th_out_id, u64 comm_out_id,
1245 u64 th_in_id, u64 comm_in_id, int flags)
1246{
1247 struct tables *tables = container_of(dbe, struct tables, dbe);
1248 PyObject *t;
1249
1250 t = tuple_new(9);
1251
1252 tuple_set_u64(t, 0, db_id);
1253 tuple_set_u64(t, 1, machine->db_id);
1254 tuple_set_u64(t, 2, sample->time);
1255 tuple_set_s32(t, 3, sample->cpu);
1256 tuple_set_u64(t, 4, th_out_id);
1257 tuple_set_u64(t, 5, comm_out_id);
1258 tuple_set_u64(t, 6, th_in_id);
1259 tuple_set_u64(t, 7, comm_in_id);
1260 tuple_set_s32(t, 8, flags);
1261
1262 call_object(tables->context_switch_handler, t, "context_switch");
1263
1264 Py_DECREF(t);
1265
1266 return 0;
1267}
1268
1269static int python_process_call_return(struct call_return *cr, u64 *parent_db_id,
1270 void *data)
1271{
1272 struct db_export *dbe = data;
1273
1274 return db_export__call_return(dbe, cr, parent_db_id);
1275}
1276
1277static void python_process_general_event(struct perf_sample *sample,
1278 struct evsel *evsel,
1279 struct addr_location *al)
1280{
1281 PyObject *handler, *t, *dict, *callchain;
1282 static char handler_name[64];
1283 unsigned n = 0;
1284
1285 snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
1286
1287 handler = get_handler(handler_name);
1288 if (!handler)
1289 return;
1290
1291 /*
1292 * Use the MAX_FIELDS to make the function expandable, though
1293 * currently there is only one item for the tuple.
1294 */
1295 t = PyTuple_New(MAX_FIELDS);
1296 if (!t)
1297 Py_FatalError("couldn't create Python tuple");
1298
1299 /* ip unwinding */
1300 callchain = python_process_callchain(sample, evsel, al);
1301 dict = get_perf_sample_dict(sample, evsel, al, callchain);
1302
1303 PyTuple_SetItem(t, n++, dict);
1304 if (_PyTuple_Resize(&t, n) == -1)
1305 Py_FatalError("error resizing Python tuple");
1306
1307 call_object(handler, t, handler_name);
1308
1309 Py_DECREF(t);
1310}
1311
1312static void python_process_event(union perf_event *event,
1313 struct perf_sample *sample,
1314 struct evsel *evsel,
1315 struct addr_location *al)
1316{
1317 struct tables *tables = &tables_global;
1318
1319 switch (evsel->core.attr.type) {
1320 case PERF_TYPE_TRACEPOINT:
1321 python_process_tracepoint(sample, evsel, al);
1322 break;
1323 /* Reserve for future process_hw/sw/raw APIs */
1324 default:
1325 if (tables->db_export_mode)
1326 db_export__sample(&tables->dbe, event, sample, evsel, al);
1327 else
1328 python_process_general_event(sample, evsel, al);
1329 }
1330}
1331
1332static void python_process_switch(union perf_event *event,
1333 struct perf_sample *sample,
1334 struct machine *machine)
1335{
1336 struct tables *tables = &tables_global;
1337
1338 if (tables->db_export_mode)
1339 db_export__switch(&tables->dbe, event, sample, machine);
1340}
1341
1342static void get_handler_name(char *str, size_t size,
1343 struct evsel *evsel)
1344{
1345 char *p = str;
1346
1347 scnprintf(str, size, "stat__%s", perf_evsel__name(evsel));
1348
1349 while ((p = strchr(p, ':'))) {
1350 *p = '_';
1351 p++;
1352 }
1353}
1354
1355static void
1356process_stat(struct evsel *counter, int cpu, int thread, u64 tstamp,
1357 struct perf_counts_values *count)
1358{
1359 PyObject *handler, *t;
1360 static char handler_name[256];
1361 int n = 0;
1362
1363 t = PyTuple_New(MAX_FIELDS);
1364 if (!t)
1365 Py_FatalError("couldn't create Python tuple");
1366
1367 get_handler_name(handler_name, sizeof(handler_name),
1368 counter);
1369
1370 handler = get_handler(handler_name);
1371 if (!handler) {
1372 pr_debug("can't find python handler %s\n", handler_name);
1373 return;
1374 }
1375
1376 PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
1377 PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
1378
1379 tuple_set_u64(t, n++, tstamp);
1380 tuple_set_u64(t, n++, count->val);
1381 tuple_set_u64(t, n++, count->ena);
1382 tuple_set_u64(t, n++, count->run);
1383
1384 if (_PyTuple_Resize(&t, n) == -1)
1385 Py_FatalError("error resizing Python tuple");
1386
1387 call_object(handler, t, handler_name);
1388
1389 Py_DECREF(t);
1390}
1391
1392static void python_process_stat(struct perf_stat_config *config,
1393 struct evsel *counter, u64 tstamp)
1394{
1395 struct perf_thread_map *threads = counter->core.threads;
1396 struct perf_cpu_map *cpus = counter->core.cpus;
1397 int cpu, thread;
1398
1399 if (config->aggr_mode == AGGR_GLOBAL) {
1400 process_stat(counter, -1, -1, tstamp,
1401 &counter->counts->aggr);
1402 return;
1403 }
1404
1405 for (thread = 0; thread < threads->nr; thread++) {
1406 for (cpu = 0; cpu < cpus->nr; cpu++) {
1407 process_stat(counter, cpus->map[cpu],
1408 perf_thread_map__pid(threads, thread), tstamp,
1409 perf_counts(counter->counts, cpu, thread));
1410 }
1411 }
1412}
1413
1414static void python_process_stat_interval(u64 tstamp)
1415{
1416 PyObject *handler, *t;
1417 static const char handler_name[] = "stat__interval";
1418 int n = 0;
1419
1420 t = PyTuple_New(MAX_FIELDS);
1421 if (!t)
1422 Py_FatalError("couldn't create Python tuple");
1423
1424 handler = get_handler(handler_name);
1425 if (!handler) {
1426 pr_debug("can't find python handler %s\n", handler_name);
1427 return;
1428 }
1429
1430 tuple_set_u64(t, n++, tstamp);
1431
1432 if (_PyTuple_Resize(&t, n) == -1)
1433 Py_FatalError("error resizing Python tuple");
1434
1435 call_object(handler, t, handler_name);
1436
1437 Py_DECREF(t);
1438}
1439
1440static int run_start_sub(void)
1441{
1442 main_module = PyImport_AddModule("__main__");
1443 if (main_module == NULL)
1444 return -1;
1445 Py_INCREF(main_module);
1446
1447 main_dict = PyModule_GetDict(main_module);
1448 if (main_dict == NULL)
1449 goto error;
1450 Py_INCREF(main_dict);
1451
1452 try_call_object("trace_begin", NULL);
1453
1454 return 0;
1455
1456error:
1457 Py_XDECREF(main_dict);
1458 Py_XDECREF(main_module);
1459 return -1;
1460}
1461
1462#define SET_TABLE_HANDLER_(name, handler_name, table_name) do { \
1463 tables->handler_name = get_handler(#table_name); \
1464 if (tables->handler_name) \
1465 tables->dbe.export_ ## name = python_export_ ## name; \
1466} while (0)
1467
1468#define SET_TABLE_HANDLER(name) \
1469 SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
1470
1471static void set_table_handlers(struct tables *tables)
1472{
1473 const char *perf_db_export_mode = "perf_db_export_mode";
1474 const char *perf_db_export_calls = "perf_db_export_calls";
1475 const char *perf_db_export_callchains = "perf_db_export_callchains";
1476 PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
1477 bool export_calls = false;
1478 bool export_callchains = false;
1479 int ret;
1480
1481 memset(tables, 0, sizeof(struct tables));
1482 if (db_export__init(&tables->dbe))
1483 Py_FatalError("failed to initialize export");
1484
1485 db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
1486 if (!db_export_mode)
1487 return;
1488
1489 ret = PyObject_IsTrue(db_export_mode);
1490 if (ret == -1)
1491 handler_call_die(perf_db_export_mode);
1492 if (!ret)
1493 return;
1494
1495 /* handle export calls */
1496 tables->dbe.crp = NULL;
1497 db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
1498 if (db_export_calls) {
1499 ret = PyObject_IsTrue(db_export_calls);
1500 if (ret == -1)
1501 handler_call_die(perf_db_export_calls);
1502 export_calls = !!ret;
1503 }
1504
1505 if (export_calls) {
1506 tables->dbe.crp =
1507 call_return_processor__new(python_process_call_return,
1508 &tables->dbe);
1509 if (!tables->dbe.crp)
1510 Py_FatalError("failed to create calls processor");
1511 }
1512
1513 /* handle export callchains */
1514 tables->dbe.cpr = NULL;
1515 db_export_callchains = PyDict_GetItemString(main_dict,
1516 perf_db_export_callchains);
1517 if (db_export_callchains) {
1518 ret = PyObject_IsTrue(db_export_callchains);
1519 if (ret == -1)
1520 handler_call_die(perf_db_export_callchains);
1521 export_callchains = !!ret;
1522 }
1523
1524 if (export_callchains) {
1525 /*
1526 * Attempt to use the call path root from the call return
1527 * processor, if the call return processor is in use. Otherwise,
1528 * we allocate a new call path root. This prevents exporting
1529 * duplicate call path ids when both are in use simultaniously.
1530 */
1531 if (tables->dbe.crp)
1532 tables->dbe.cpr = tables->dbe.crp->cpr;
1533 else
1534 tables->dbe.cpr = call_path_root__new();
1535
1536 if (!tables->dbe.cpr)
1537 Py_FatalError("failed to create call path root");
1538 }
1539
1540 tables->db_export_mode = true;
1541 /*
1542 * Reserve per symbol space for symbol->db_id via symbol__priv()
1543 */
1544 symbol_conf.priv_size = sizeof(u64);
1545
1546 SET_TABLE_HANDLER(evsel);
1547 SET_TABLE_HANDLER(machine);
1548 SET_TABLE_HANDLER(thread);
1549 SET_TABLE_HANDLER(comm);
1550 SET_TABLE_HANDLER(comm_thread);
1551 SET_TABLE_HANDLER(dso);
1552 SET_TABLE_HANDLER(symbol);
1553 SET_TABLE_HANDLER(branch_type);
1554 SET_TABLE_HANDLER(sample);
1555 SET_TABLE_HANDLER(call_path);
1556 SET_TABLE_HANDLER(call_return);
1557 SET_TABLE_HANDLER(context_switch);
1558
1559 /*
1560 * Synthesized events are samples but with architecture-specific data
1561 * stored in sample->raw_data. They are exported via
1562 * python_export_sample() and consequently do not need a separate export
1563 * callback.
1564 */
1565 tables->synth_handler = get_handler("synth_data");
1566}
1567
1568#if PY_MAJOR_VERSION < 3
1569static void _free_command_line(const char **command_line, int num)
1570{
1571 free(command_line);
1572}
1573#else
1574static void _free_command_line(wchar_t **command_line, int num)
1575{
1576 int i;
1577 for (i = 0; i < num; i++)
1578 PyMem_RawFree(command_line[i]);
1579 free(command_line);
1580}
1581#endif
1582
1583
1584/*
1585 * Start trace script
1586 */
1587static int python_start_script(const char *script, int argc, const char **argv)
1588{
1589 struct tables *tables = &tables_global;
1590 PyMODINIT_FUNC (*initfunc)(void);
1591#if PY_MAJOR_VERSION < 3
1592 const char **command_line;
1593#else
1594 wchar_t **command_line;
1595#endif
1596 /*
1597 * Use a non-const name variable to cope with python 2.6's
1598 * PyImport_AppendInittab prototype
1599 */
1600 char buf[PATH_MAX], name[19] = "perf_trace_context";
1601 int i, err = 0;
1602 FILE *fp;
1603
1604#if PY_MAJOR_VERSION < 3
1605 initfunc = initperf_trace_context;
1606 command_line = malloc((argc + 1) * sizeof(const char *));
1607 command_line[0] = script;
1608 for (i = 1; i < argc + 1; i++)
1609 command_line[i] = argv[i - 1];
1610#else
1611 initfunc = PyInit_perf_trace_context;
1612 command_line = malloc((argc + 1) * sizeof(wchar_t *));
1613 command_line[0] = Py_DecodeLocale(script, NULL);
1614 for (i = 1; i < argc + 1; i++)
1615 command_line[i] = Py_DecodeLocale(argv[i - 1], NULL);
1616#endif
1617
1618 PyImport_AppendInittab(name, initfunc);
1619 Py_Initialize();
1620
1621#if PY_MAJOR_VERSION < 3
1622 PySys_SetArgv(argc + 1, (char **)command_line);
1623#else
1624 PySys_SetArgv(argc + 1, command_line);
1625#endif
1626
1627 fp = fopen(script, "r");
1628 if (!fp) {
1629 sprintf(buf, "Can't open python script \"%s\"", script);
1630 perror(buf);
1631 err = -1;
1632 goto error;
1633 }
1634
1635 err = PyRun_SimpleFile(fp, script);
1636 if (err) {
1637 fprintf(stderr, "Error running python script %s\n", script);
1638 goto error;
1639 }
1640
1641 err = run_start_sub();
1642 if (err) {
1643 fprintf(stderr, "Error starting python script %s\n", script);
1644 goto error;
1645 }
1646
1647 set_table_handlers(tables);
1648
1649 if (tables->db_export_mode) {
1650 err = db_export__branch_types(&tables->dbe);
1651 if (err)
1652 goto error;
1653 }
1654
1655 _free_command_line(command_line, argc + 1);
1656
1657 return err;
1658error:
1659 Py_Finalize();
1660 _free_command_line(command_line, argc + 1);
1661
1662 return err;
1663}
1664
1665static int python_flush_script(void)
1666{
1667 return 0;
1668}
1669
1670/*
1671 * Stop trace script
1672 */
1673static int python_stop_script(void)
1674{
1675 struct tables *tables = &tables_global;
1676
1677 try_call_object("trace_end", NULL);
1678
1679 db_export__exit(&tables->dbe);
1680
1681 Py_XDECREF(main_dict);
1682 Py_XDECREF(main_module);
1683 Py_Finalize();
1684
1685 return 0;
1686}
1687
1688static int python_generate_script(struct tep_handle *pevent, const char *outfile)
1689{
1690 int i, not_first, count, nr_events;
1691 struct tep_event **all_events;
1692 struct tep_event *event = NULL;
1693 struct tep_format_field *f;
1694 char fname[PATH_MAX];
1695 FILE *ofp;
1696
1697 sprintf(fname, "%s.py", outfile);
1698 ofp = fopen(fname, "w");
1699 if (ofp == NULL) {
1700 fprintf(stderr, "couldn't open %s\n", fname);
1701 return -1;
1702 }
1703 fprintf(ofp, "# perf script event handlers, "
1704 "generated by perf script -g python\n");
1705
1706 fprintf(ofp, "# Licensed under the terms of the GNU GPL"
1707 " License version 2\n\n");
1708
1709 fprintf(ofp, "# The common_* event handler fields are the most useful "
1710 "fields common to\n");
1711
1712 fprintf(ofp, "# all events. They don't necessarily correspond to "
1713 "the 'common_*' fields\n");
1714
1715 fprintf(ofp, "# in the format files. Those fields not available as "
1716 "handler params can\n");
1717
1718 fprintf(ofp, "# be retrieved using Python functions of the form "
1719 "common_*(context).\n");
1720
1721 fprintf(ofp, "# See the perf-script-python Documentation for the list "
1722 "of available functions.\n\n");
1723
1724 fprintf(ofp, "from __future__ import print_function\n\n");
1725 fprintf(ofp, "import os\n");
1726 fprintf(ofp, "import sys\n\n");
1727
1728 fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
1729 fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
1730 fprintf(ofp, "\nfrom perf_trace_context import *\n");
1731 fprintf(ofp, "from Core import *\n\n\n");
1732
1733 fprintf(ofp, "def trace_begin():\n");
1734 fprintf(ofp, "\tprint(\"in trace_begin\")\n\n");
1735
1736 fprintf(ofp, "def trace_end():\n");
1737 fprintf(ofp, "\tprint(\"in trace_end\")\n\n");
1738
1739 nr_events = tep_get_events_count(pevent);
1740 all_events = tep_list_events(pevent, TEP_EVENT_SORT_ID);
1741
1742 for (i = 0; all_events && i < nr_events; i++) {
1743 event = all_events[i];
1744 fprintf(ofp, "def %s__%s(", event->system, event->name);
1745 fprintf(ofp, "event_name, ");
1746 fprintf(ofp, "context, ");
1747 fprintf(ofp, "common_cpu,\n");
1748 fprintf(ofp, "\tcommon_secs, ");
1749 fprintf(ofp, "common_nsecs, ");
1750 fprintf(ofp, "common_pid, ");
1751 fprintf(ofp, "common_comm,\n\t");
1752 fprintf(ofp, "common_callchain, ");
1753
1754 not_first = 0;
1755 count = 0;
1756
1757 for (f = event->format.fields; f; f = f->next) {
1758 if (not_first++)
1759 fprintf(ofp, ", ");
1760 if (++count % 5 == 0)
1761 fprintf(ofp, "\n\t");
1762
1763 fprintf(ofp, "%s", f->name);
1764 }
1765 if (not_first++)
1766 fprintf(ofp, ", ");
1767 if (++count % 5 == 0)
1768 fprintf(ofp, "\n\t\t");
1769 fprintf(ofp, "perf_sample_dict");
1770
1771 fprintf(ofp, "):\n");
1772
1773 fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
1774 "common_secs, common_nsecs,\n\t\t\t"
1775 "common_pid, common_comm)\n\n");
1776
1777 fprintf(ofp, "\t\tprint(\"");
1778
1779 not_first = 0;
1780 count = 0;
1781
1782 for (f = event->format.fields; f; f = f->next) {
1783 if (not_first++)
1784 fprintf(ofp, ", ");
1785 if (count && count % 3 == 0) {
1786 fprintf(ofp, "\" \\\n\t\t\"");
1787 }
1788 count++;
1789
1790 fprintf(ofp, "%s=", f->name);
1791 if (f->flags & TEP_FIELD_IS_STRING ||
1792 f->flags & TEP_FIELD_IS_FLAG ||
1793 f->flags & TEP_FIELD_IS_ARRAY ||
1794 f->flags & TEP_FIELD_IS_SYMBOLIC)
1795 fprintf(ofp, "%%s");
1796 else if (f->flags & TEP_FIELD_IS_SIGNED)
1797 fprintf(ofp, "%%d");
1798 else
1799 fprintf(ofp, "%%u");
1800 }
1801
1802 fprintf(ofp, "\" %% \\\n\t\t(");
1803
1804 not_first = 0;
1805 count = 0;
1806
1807 for (f = event->format.fields; f; f = f->next) {
1808 if (not_first++)
1809 fprintf(ofp, ", ");
1810
1811 if (++count % 5 == 0)
1812 fprintf(ofp, "\n\t\t");
1813
1814 if (f->flags & TEP_FIELD_IS_FLAG) {
1815 if ((count - 1) % 5 != 0) {
1816 fprintf(ofp, "\n\t\t");
1817 count = 4;
1818 }
1819 fprintf(ofp, "flag_str(\"");
1820 fprintf(ofp, "%s__%s\", ", event->system,
1821 event->name);
1822 fprintf(ofp, "\"%s\", %s)", f->name,
1823 f->name);
1824 } else if (f->flags & TEP_FIELD_IS_SYMBOLIC) {
1825 if ((count - 1) % 5 != 0) {
1826 fprintf(ofp, "\n\t\t");
1827 count = 4;
1828 }
1829 fprintf(ofp, "symbol_str(\"");
1830 fprintf(ofp, "%s__%s\", ", event->system,
1831 event->name);
1832 fprintf(ofp, "\"%s\", %s)", f->name,
1833 f->name);
1834 } else
1835 fprintf(ofp, "%s", f->name);
1836 }
1837
1838 fprintf(ofp, "))\n\n");
1839
1840 fprintf(ofp, "\t\tprint('Sample: {'+"
1841 "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
1842
1843 fprintf(ofp, "\t\tfor node in common_callchain:");
1844 fprintf(ofp, "\n\t\t\tif 'sym' in node:");
1845 fprintf(ofp, "\n\t\t\t\tprint(\"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name']))");
1846 fprintf(ofp, "\n\t\t\telse:");
1847 fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x]\" %% (node['ip']))\n\n");
1848 fprintf(ofp, "\t\tprint()\n\n");
1849
1850 }
1851
1852 fprintf(ofp, "def trace_unhandled(event_name, context, "
1853 "event_fields_dict, perf_sample_dict):\n");
1854
1855 fprintf(ofp, "\t\tprint(get_dict_as_string(event_fields_dict))\n");
1856 fprintf(ofp, "\t\tprint('Sample: {'+"
1857 "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
1858
1859 fprintf(ofp, "def print_header("
1860 "event_name, cpu, secs, nsecs, pid, comm):\n"
1861 "\tprint(\"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
1862 "(event_name, cpu, secs, nsecs, pid, comm), end=\"\")\n\n");
1863
1864 fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
1865 "\treturn delimiter.join"
1866 "(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
1867
1868 fclose(ofp);
1869
1870 fprintf(stderr, "generated Python script: %s\n", fname);
1871
1872 return 0;
1873}
1874
1875struct scripting_ops python_scripting_ops = {
1876 .name = "Python",
1877 .start_script = python_start_script,
1878 .flush_script = python_flush_script,
1879 .stop_script = python_stop_script,
1880 .process_event = python_process_event,
1881 .process_switch = python_process_switch,
1882 .process_stat = python_process_stat,
1883 .process_stat_interval = python_process_stat_interval,
1884 .generate_script = python_generate_script,
1885};