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
34#include "../../perf.h"
35#include "../debug.h"
36#include "../callchain.h"
37#include "../evsel.h"
38#include "../util.h"
39#include "../event.h"
40#include "../thread.h"
41#include "../comm.h"
42#include "../machine.h"
43#include "../db-export.h"
44#include "../thread-stack.h"
45#include "../trace-event.h"
46#include "../call-path.h"
47#include "thread_map.h"
48#include "cpumap.h"
49#include "print_binary.h"
50#include "stat.h"
51
52#if PY_MAJOR_VERSION < 3
53#define _PyUnicode_FromString(arg) \
54 PyString_FromString(arg)
55#define _PyUnicode_FromStringAndSize(arg1, arg2) \
56 PyString_FromStringAndSize((arg1), (arg2))
57#define _PyBytes_FromStringAndSize(arg1, arg2) \
58 PyString_FromStringAndSize((arg1), (arg2))
59#define _PyLong_FromLong(arg) \
60 PyInt_FromLong(arg)
61#define _PyLong_AsLong(arg) \
62 PyInt_AsLong(arg)
63#define _PyCapsule_New(arg1, arg2, arg3) \
64 PyCObject_FromVoidPtr((arg1), (arg2))
65
66PyMODINIT_FUNC initperf_trace_context(void);
67#else
68#define _PyUnicode_FromString(arg) \
69 PyUnicode_FromString(arg)
70#define _PyUnicode_FromStringAndSize(arg1, arg2) \
71 PyUnicode_FromStringAndSize((arg1), (arg2))
72#define _PyBytes_FromStringAndSize(arg1, arg2) \
73 PyBytes_FromStringAndSize((arg1), (arg2))
74#define _PyLong_FromLong(arg) \
75 PyLong_FromLong(arg)
76#define _PyLong_AsLong(arg) \
77 PyLong_AsLong(arg)
78#define _PyCapsule_New(arg1, arg2, arg3) \
79 PyCapsule_New((arg1), (arg2), (arg3))
80
81PyMODINIT_FUNC PyInit_perf_trace_context(void);
82#endif
83
84#define TRACE_EVENT_TYPE_MAX \
85 ((1 << (sizeof(unsigned short) * 8)) - 1)
86
87static DECLARE_BITMAP(events_defined, TRACE_EVENT_TYPE_MAX);
88
89#define MAX_FIELDS 64
90#define N_COMMON_FIELDS 7
91
92extern struct scripting_context *scripting_context;
93
94static char *cur_field_name;
95static int zero_flag_atom;
96
97static PyObject *main_module, *main_dict;
98
99struct tables {
100 struct db_export dbe;
101 PyObject *evsel_handler;
102 PyObject *machine_handler;
103 PyObject *thread_handler;
104 PyObject *comm_handler;
105 PyObject *comm_thread_handler;
106 PyObject *dso_handler;
107 PyObject *symbol_handler;
108 PyObject *branch_type_handler;
109 PyObject *sample_handler;
110 PyObject *call_path_handler;
111 PyObject *call_return_handler;
112 bool db_export_mode;
113};
114
115static struct tables tables_global;
116
117static void handler_call_die(const char *handler_name) __noreturn;
118static void handler_call_die(const char *handler_name)
119{
120 PyErr_Print();
121 Py_FatalError("problem in Python trace event handler");
122 // Py_FatalError does not return
123 // but we have to make the compiler happy
124 abort();
125}
126
127/*
128 * Insert val into into the dictionary and decrement the reference counter.
129 * This is necessary for dictionaries since PyDict_SetItemString() does not
130 * steal a reference, as opposed to PyTuple_SetItem().
131 */
132static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
133{
134 PyDict_SetItemString(dict, key, val);
135 Py_DECREF(val);
136}
137
138static PyObject *get_handler(const char *handler_name)
139{
140 PyObject *handler;
141
142 handler = PyDict_GetItemString(main_dict, handler_name);
143 if (handler && !PyCallable_Check(handler))
144 return NULL;
145 return handler;
146}
147
148static int get_argument_count(PyObject *handler)
149{
150 int arg_count = 0;
151
152 /*
153 * The attribute for the code object is func_code in Python 2,
154 * whereas it is __code__ in Python 3.0+.
155 */
156 PyObject *code_obj = PyObject_GetAttrString(handler,
157 "func_code");
158 if (PyErr_Occurred()) {
159 PyErr_Clear();
160 code_obj = PyObject_GetAttrString(handler,
161 "__code__");
162 }
163 PyErr_Clear();
164 if (code_obj) {
165 PyObject *arg_count_obj = PyObject_GetAttrString(code_obj,
166 "co_argcount");
167 if (arg_count_obj) {
168 arg_count = (int) _PyLong_AsLong(arg_count_obj);
169 Py_DECREF(arg_count_obj);
170 }
171 Py_DECREF(code_obj);
172 }
173 return arg_count;
174}
175
176static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
177{
178 PyObject *retval;
179
180 retval = PyObject_CallObject(handler, args);
181 if (retval == NULL)
182 handler_call_die(die_msg);
183 Py_DECREF(retval);
184}
185
186static void try_call_object(const char *handler_name, PyObject *args)
187{
188 PyObject *handler;
189
190 handler = get_handler(handler_name);
191 if (handler)
192 call_object(handler, args, handler_name);
193}
194
195static void define_value(enum print_arg_type field_type,
196 const char *ev_name,
197 const char *field_name,
198 const char *field_value,
199 const char *field_str)
200{
201 const char *handler_name = "define_flag_value";
202 PyObject *t;
203 unsigned long long value;
204 unsigned n = 0;
205
206 if (field_type == PRINT_SYMBOL)
207 handler_name = "define_symbolic_value";
208
209 t = PyTuple_New(4);
210 if (!t)
211 Py_FatalError("couldn't create Python tuple");
212
213 value = eval_flag(field_value);
214
215 PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
216 PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
217 PyTuple_SetItem(t, n++, _PyLong_FromLong(value));
218 PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_str));
219
220 try_call_object(handler_name, t);
221
222 Py_DECREF(t);
223}
224
225static void define_values(enum print_arg_type field_type,
226 struct print_flag_sym *field,
227 const char *ev_name,
228 const char *field_name)
229{
230 define_value(field_type, ev_name, field_name, field->value,
231 field->str);
232
233 if (field->next)
234 define_values(field_type, field->next, ev_name, field_name);
235}
236
237static void define_field(enum print_arg_type field_type,
238 const char *ev_name,
239 const char *field_name,
240 const char *delim)
241{
242 const char *handler_name = "define_flag_field";
243 PyObject *t;
244 unsigned n = 0;
245
246 if (field_type == PRINT_SYMBOL)
247 handler_name = "define_symbolic_field";
248
249 if (field_type == PRINT_FLAGS)
250 t = PyTuple_New(3);
251 else
252 t = PyTuple_New(2);
253 if (!t)
254 Py_FatalError("couldn't create Python tuple");
255
256 PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
257 PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
258 if (field_type == PRINT_FLAGS)
259 PyTuple_SetItem(t, n++, _PyUnicode_FromString(delim));
260
261 try_call_object(handler_name, t);
262
263 Py_DECREF(t);
264}
265
266static void define_event_symbols(struct event_format *event,
267 const char *ev_name,
268 struct print_arg *args)
269{
270 if (args == NULL)
271 return;
272
273 switch (args->type) {
274 case PRINT_NULL:
275 break;
276 case PRINT_ATOM:
277 define_value(PRINT_FLAGS, ev_name, cur_field_name, "0",
278 args->atom.atom);
279 zero_flag_atom = 0;
280 break;
281 case PRINT_FIELD:
282 free(cur_field_name);
283 cur_field_name = strdup(args->field.name);
284 break;
285 case PRINT_FLAGS:
286 define_event_symbols(event, ev_name, args->flags.field);
287 define_field(PRINT_FLAGS, ev_name, cur_field_name,
288 args->flags.delim);
289 define_values(PRINT_FLAGS, args->flags.flags, ev_name,
290 cur_field_name);
291 break;
292 case PRINT_SYMBOL:
293 define_event_symbols(event, ev_name, args->symbol.field);
294 define_field(PRINT_SYMBOL, ev_name, cur_field_name, NULL);
295 define_values(PRINT_SYMBOL, args->symbol.symbols, ev_name,
296 cur_field_name);
297 break;
298 case PRINT_HEX:
299 case PRINT_HEX_STR:
300 define_event_symbols(event, ev_name, args->hex.field);
301 define_event_symbols(event, ev_name, args->hex.size);
302 break;
303 case PRINT_INT_ARRAY:
304 define_event_symbols(event, ev_name, args->int_array.field);
305 define_event_symbols(event, ev_name, args->int_array.count);
306 define_event_symbols(event, ev_name, args->int_array.el_size);
307 break;
308 case PRINT_STRING:
309 break;
310 case PRINT_TYPE:
311 define_event_symbols(event, ev_name, args->typecast.item);
312 break;
313 case PRINT_OP:
314 if (strcmp(args->op.op, ":") == 0)
315 zero_flag_atom = 1;
316 define_event_symbols(event, ev_name, args->op.left);
317 define_event_symbols(event, ev_name, args->op.right);
318 break;
319 default:
320 /* gcc warns for these? */
321 case PRINT_BSTRING:
322 case PRINT_DYNAMIC_ARRAY:
323 case PRINT_DYNAMIC_ARRAY_LEN:
324 case PRINT_FUNC:
325 case PRINT_BITMASK:
326 /* we should warn... */
327 return;
328 }
329
330 if (args->next)
331 define_event_symbols(event, ev_name, args->next);
332}
333
334static PyObject *get_field_numeric_entry(struct event_format *event,
335 struct format_field *field, void *data)
336{
337 bool is_array = field->flags & FIELD_IS_ARRAY;
338 PyObject *obj = NULL, *list = NULL;
339 unsigned long long val;
340 unsigned int item_size, n_items, i;
341
342 if (is_array) {
343 list = PyList_New(field->arraylen);
344 item_size = field->size / field->arraylen;
345 n_items = field->arraylen;
346 } else {
347 item_size = field->size;
348 n_items = 1;
349 }
350
351 for (i = 0; i < n_items; i++) {
352
353 val = read_size(event, data + field->offset + i * item_size,
354 item_size);
355 if (field->flags & FIELD_IS_SIGNED) {
356 if ((long long)val >= LONG_MIN &&
357 (long long)val <= LONG_MAX)
358 obj = _PyLong_FromLong(val);
359 else
360 obj = PyLong_FromLongLong(val);
361 } else {
362 if (val <= LONG_MAX)
363 obj = _PyLong_FromLong(val);
364 else
365 obj = PyLong_FromUnsignedLongLong(val);
366 }
367 if (is_array)
368 PyList_SET_ITEM(list, i, obj);
369 }
370 if (is_array)
371 obj = list;
372 return obj;
373}
374
375
376static PyObject *python_process_callchain(struct perf_sample *sample,
377 struct perf_evsel *evsel,
378 struct addr_location *al)
379{
380 PyObject *pylist;
381
382 pylist = PyList_New(0);
383 if (!pylist)
384 Py_FatalError("couldn't create Python list");
385
386 if (!symbol_conf.use_callchain || !sample->callchain)
387 goto exit;
388
389 if (thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
390 sample, NULL, NULL,
391 scripting_max_stack) != 0) {
392 pr_err("Failed to resolve callchain. Skipping\n");
393 goto exit;
394 }
395 callchain_cursor_commit(&callchain_cursor);
396
397
398 while (1) {
399 PyObject *pyelem;
400 struct callchain_cursor_node *node;
401 node = callchain_cursor_current(&callchain_cursor);
402 if (!node)
403 break;
404
405 pyelem = PyDict_New();
406 if (!pyelem)
407 Py_FatalError("couldn't create Python dictionary");
408
409
410 pydict_set_item_string_decref(pyelem, "ip",
411 PyLong_FromUnsignedLongLong(node->ip));
412
413 if (node->sym) {
414 PyObject *pysym = PyDict_New();
415 if (!pysym)
416 Py_FatalError("couldn't create Python dictionary");
417 pydict_set_item_string_decref(pysym, "start",
418 PyLong_FromUnsignedLongLong(node->sym->start));
419 pydict_set_item_string_decref(pysym, "end",
420 PyLong_FromUnsignedLongLong(node->sym->end));
421 pydict_set_item_string_decref(pysym, "binding",
422 _PyLong_FromLong(node->sym->binding));
423 pydict_set_item_string_decref(pysym, "name",
424 _PyUnicode_FromStringAndSize(node->sym->name,
425 node->sym->namelen));
426 pydict_set_item_string_decref(pyelem, "sym", pysym);
427 }
428
429 if (node->map) {
430 struct map *map = node->map;
431 const char *dsoname = "[unknown]";
432 if (map && map->dso) {
433 if (symbol_conf.show_kernel_path && map->dso->long_name)
434 dsoname = map->dso->long_name;
435 else
436 dsoname = map->dso->name;
437 }
438 pydict_set_item_string_decref(pyelem, "dso",
439 _PyUnicode_FromString(dsoname));
440 }
441
442 callchain_cursor_advance(&callchain_cursor);
443 PyList_Append(pylist, pyelem);
444 Py_DECREF(pyelem);
445 }
446
447exit:
448 return pylist;
449}
450
451static PyObject *get_sample_value_as_tuple(struct sample_read_value *value)
452{
453 PyObject *t;
454
455 t = PyTuple_New(2);
456 if (!t)
457 Py_FatalError("couldn't create Python tuple");
458 PyTuple_SetItem(t, 0, PyLong_FromUnsignedLongLong(value->id));
459 PyTuple_SetItem(t, 1, PyLong_FromUnsignedLongLong(value->value));
460 return t;
461}
462
463static void set_sample_read_in_dict(PyObject *dict_sample,
464 struct perf_sample *sample,
465 struct perf_evsel *evsel)
466{
467 u64 read_format = evsel->attr.read_format;
468 PyObject *values;
469 unsigned int i;
470
471 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
472 pydict_set_item_string_decref(dict_sample, "time_enabled",
473 PyLong_FromUnsignedLongLong(sample->read.time_enabled));
474 }
475
476 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
477 pydict_set_item_string_decref(dict_sample, "time_running",
478 PyLong_FromUnsignedLongLong(sample->read.time_running));
479 }
480
481 if (read_format & PERF_FORMAT_GROUP)
482 values = PyList_New(sample->read.group.nr);
483 else
484 values = PyList_New(1);
485
486 if (!values)
487 Py_FatalError("couldn't create Python list");
488
489 if (read_format & PERF_FORMAT_GROUP) {
490 for (i = 0; i < sample->read.group.nr; i++) {
491 PyObject *t = get_sample_value_as_tuple(&sample->read.group.values[i]);
492 PyList_SET_ITEM(values, i, t);
493 }
494 } else {
495 PyObject *t = get_sample_value_as_tuple(&sample->read.one);
496 PyList_SET_ITEM(values, 0, t);
497 }
498 pydict_set_item_string_decref(dict_sample, "values", values);
499}
500
501static PyObject *get_perf_sample_dict(struct perf_sample *sample,
502 struct perf_evsel *evsel,
503 struct addr_location *al,
504 PyObject *callchain)
505{
506 PyObject *dict, *dict_sample;
507
508 dict = PyDict_New();
509 if (!dict)
510 Py_FatalError("couldn't create Python dictionary");
511
512 dict_sample = PyDict_New();
513 if (!dict_sample)
514 Py_FatalError("couldn't create Python dictionary");
515
516 pydict_set_item_string_decref(dict, "ev_name", _PyUnicode_FromString(perf_evsel__name(evsel)));
517 pydict_set_item_string_decref(dict, "attr", _PyUnicode_FromStringAndSize(
518 (const char *)&evsel->attr, sizeof(evsel->attr)));
519
520 pydict_set_item_string_decref(dict_sample, "pid",
521 _PyLong_FromLong(sample->pid));
522 pydict_set_item_string_decref(dict_sample, "tid",
523 _PyLong_FromLong(sample->tid));
524 pydict_set_item_string_decref(dict_sample, "cpu",
525 _PyLong_FromLong(sample->cpu));
526 pydict_set_item_string_decref(dict_sample, "ip",
527 PyLong_FromUnsignedLongLong(sample->ip));
528 pydict_set_item_string_decref(dict_sample, "time",
529 PyLong_FromUnsignedLongLong(sample->time));
530 pydict_set_item_string_decref(dict_sample, "period",
531 PyLong_FromUnsignedLongLong(sample->period));
532 pydict_set_item_string_decref(dict_sample, "phys_addr",
533 PyLong_FromUnsignedLongLong(sample->phys_addr));
534 pydict_set_item_string_decref(dict_sample, "addr",
535 PyLong_FromUnsignedLongLong(sample->addr));
536 set_sample_read_in_dict(dict_sample, sample, evsel);
537 pydict_set_item_string_decref(dict, "sample", dict_sample);
538
539 pydict_set_item_string_decref(dict, "raw_buf", _PyBytes_FromStringAndSize(
540 (const char *)sample->raw_data, sample->raw_size));
541 pydict_set_item_string_decref(dict, "comm",
542 _PyUnicode_FromString(thread__comm_str(al->thread)));
543 if (al->map) {
544 pydict_set_item_string_decref(dict, "dso",
545 _PyUnicode_FromString(al->map->dso->name));
546 }
547 if (al->sym) {
548 pydict_set_item_string_decref(dict, "symbol",
549 _PyUnicode_FromString(al->sym->name));
550 }
551
552 pydict_set_item_string_decref(dict, "callchain", callchain);
553
554 return dict;
555}
556
557static void python_process_tracepoint(struct perf_sample *sample,
558 struct perf_evsel *evsel,
559 struct addr_location *al)
560{
561 struct event_format *event = evsel->tp_format;
562 PyObject *handler, *context, *t, *obj = NULL, *callchain;
563 PyObject *dict = NULL, *all_entries_dict = NULL;
564 static char handler_name[256];
565 struct format_field *field;
566 unsigned long s, ns;
567 unsigned n = 0;
568 int pid;
569 int cpu = sample->cpu;
570 void *data = sample->raw_data;
571 unsigned long long nsecs = sample->time;
572 const char *comm = thread__comm_str(al->thread);
573 const char *default_handler_name = "trace_unhandled";
574
575 if (!event) {
576 snprintf(handler_name, sizeof(handler_name),
577 "ug! no event found for type %" PRIu64, (u64)evsel->attr.config);
578 Py_FatalError(handler_name);
579 }
580
581 pid = raw_field_value(event, "common_pid", data);
582
583 sprintf(handler_name, "%s__%s", event->system, event->name);
584
585 if (!test_and_set_bit(event->id, events_defined))
586 define_event_symbols(event, handler_name, event->print_fmt.args);
587
588 handler = get_handler(handler_name);
589 if (!handler) {
590 handler = get_handler(default_handler_name);
591 if (!handler)
592 return;
593 dict = PyDict_New();
594 if (!dict)
595 Py_FatalError("couldn't create Python dict");
596 }
597
598 t = PyTuple_New(MAX_FIELDS);
599 if (!t)
600 Py_FatalError("couldn't create Python tuple");
601
602
603 s = nsecs / NSEC_PER_SEC;
604 ns = nsecs - s * NSEC_PER_SEC;
605
606 scripting_context->event_data = data;
607 scripting_context->pevent = evsel->tp_format->pevent;
608
609 context = _PyCapsule_New(scripting_context, NULL, NULL);
610
611 PyTuple_SetItem(t, n++, _PyUnicode_FromString(handler_name));
612 PyTuple_SetItem(t, n++, context);
613
614 /* ip unwinding */
615 callchain = python_process_callchain(sample, evsel, al);
616 /* Need an additional reference for the perf_sample dict */
617 Py_INCREF(callchain);
618
619 if (!dict) {
620 PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
621 PyTuple_SetItem(t, n++, _PyLong_FromLong(s));
622 PyTuple_SetItem(t, n++, _PyLong_FromLong(ns));
623 PyTuple_SetItem(t, n++, _PyLong_FromLong(pid));
624 PyTuple_SetItem(t, n++, _PyUnicode_FromString(comm));
625 PyTuple_SetItem(t, n++, callchain);
626 } else {
627 pydict_set_item_string_decref(dict, "common_cpu", _PyLong_FromLong(cpu));
628 pydict_set_item_string_decref(dict, "common_s", _PyLong_FromLong(s));
629 pydict_set_item_string_decref(dict, "common_ns", _PyLong_FromLong(ns));
630 pydict_set_item_string_decref(dict, "common_pid", _PyLong_FromLong(pid));
631 pydict_set_item_string_decref(dict, "common_comm", _PyUnicode_FromString(comm));
632 pydict_set_item_string_decref(dict, "common_callchain", callchain);
633 }
634 for (field = event->format.fields; field; field = field->next) {
635 unsigned int offset, len;
636 unsigned long long val;
637
638 if (field->flags & FIELD_IS_ARRAY) {
639 offset = field->offset;
640 len = field->size;
641 if (field->flags & FIELD_IS_DYNAMIC) {
642 val = pevent_read_number(scripting_context->pevent,
643 data + offset, len);
644 offset = val;
645 len = offset >> 16;
646 offset &= 0xffff;
647 }
648 if (field->flags & FIELD_IS_STRING &&
649 is_printable_array(data + offset, len)) {
650 obj = _PyUnicode_FromString((char *) data + offset);
651 } else {
652 obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
653 field->flags &= ~FIELD_IS_STRING;
654 }
655 } else { /* FIELD_IS_NUMERIC */
656 obj = get_field_numeric_entry(event, field, data);
657 }
658 if (!dict)
659 PyTuple_SetItem(t, n++, obj);
660 else
661 pydict_set_item_string_decref(dict, field->name, obj);
662
663 }
664
665 if (dict)
666 PyTuple_SetItem(t, n++, dict);
667
668 if (get_argument_count(handler) == (int) n + 1) {
669 all_entries_dict = get_perf_sample_dict(sample, evsel, al,
670 callchain);
671 PyTuple_SetItem(t, n++, all_entries_dict);
672 } else {
673 Py_DECREF(callchain);
674 }
675
676 if (_PyTuple_Resize(&t, n) == -1)
677 Py_FatalError("error resizing Python tuple");
678
679 if (!dict) {
680 call_object(handler, t, handler_name);
681 } else {
682 call_object(handler, t, default_handler_name);
683 Py_DECREF(dict);
684 }
685
686 Py_XDECREF(all_entries_dict);
687 Py_DECREF(t);
688}
689
690static PyObject *tuple_new(unsigned int sz)
691{
692 PyObject *t;
693
694 t = PyTuple_New(sz);
695 if (!t)
696 Py_FatalError("couldn't create Python tuple");
697 return t;
698}
699
700static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
701{
702#if BITS_PER_LONG == 64
703 return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
704#endif
705#if BITS_PER_LONG == 32
706 return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
707#endif
708}
709
710static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
711{
712 return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
713}
714
715static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
716{
717 return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
718}
719
720static int python_export_evsel(struct db_export *dbe, struct perf_evsel *evsel)
721{
722 struct tables *tables = container_of(dbe, struct tables, dbe);
723 PyObject *t;
724
725 t = tuple_new(2);
726
727 tuple_set_u64(t, 0, evsel->db_id);
728 tuple_set_string(t, 1, perf_evsel__name(evsel));
729
730 call_object(tables->evsel_handler, t, "evsel_table");
731
732 Py_DECREF(t);
733
734 return 0;
735}
736
737static int python_export_machine(struct db_export *dbe,
738 struct machine *machine)
739{
740 struct tables *tables = container_of(dbe, struct tables, dbe);
741 PyObject *t;
742
743 t = tuple_new(3);
744
745 tuple_set_u64(t, 0, machine->db_id);
746 tuple_set_s32(t, 1, machine->pid);
747 tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
748
749 call_object(tables->machine_handler, t, "machine_table");
750
751 Py_DECREF(t);
752
753 return 0;
754}
755
756static int python_export_thread(struct db_export *dbe, struct thread *thread,
757 u64 main_thread_db_id, struct machine *machine)
758{
759 struct tables *tables = container_of(dbe, struct tables, dbe);
760 PyObject *t;
761
762 t = tuple_new(5);
763
764 tuple_set_u64(t, 0, thread->db_id);
765 tuple_set_u64(t, 1, machine->db_id);
766 tuple_set_u64(t, 2, main_thread_db_id);
767 tuple_set_s32(t, 3, thread->pid_);
768 tuple_set_s32(t, 4, thread->tid);
769
770 call_object(tables->thread_handler, t, "thread_table");
771
772 Py_DECREF(t);
773
774 return 0;
775}
776
777static int python_export_comm(struct db_export *dbe, struct comm *comm)
778{
779 struct tables *tables = container_of(dbe, struct tables, dbe);
780 PyObject *t;
781
782 t = tuple_new(2);
783
784 tuple_set_u64(t, 0, comm->db_id);
785 tuple_set_string(t, 1, comm__str(comm));
786
787 call_object(tables->comm_handler, t, "comm_table");
788
789 Py_DECREF(t);
790
791 return 0;
792}
793
794static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
795 struct comm *comm, struct thread *thread)
796{
797 struct tables *tables = container_of(dbe, struct tables, dbe);
798 PyObject *t;
799
800 t = tuple_new(3);
801
802 tuple_set_u64(t, 0, db_id);
803 tuple_set_u64(t, 1, comm->db_id);
804 tuple_set_u64(t, 2, thread->db_id);
805
806 call_object(tables->comm_thread_handler, t, "comm_thread_table");
807
808 Py_DECREF(t);
809
810 return 0;
811}
812
813static int python_export_dso(struct db_export *dbe, struct dso *dso,
814 struct machine *machine)
815{
816 struct tables *tables = container_of(dbe, struct tables, dbe);
817 char sbuild_id[SBUILD_ID_SIZE];
818 PyObject *t;
819
820 build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);
821
822 t = tuple_new(5);
823
824 tuple_set_u64(t, 0, dso->db_id);
825 tuple_set_u64(t, 1, machine->db_id);
826 tuple_set_string(t, 2, dso->short_name);
827 tuple_set_string(t, 3, dso->long_name);
828 tuple_set_string(t, 4, sbuild_id);
829
830 call_object(tables->dso_handler, t, "dso_table");
831
832 Py_DECREF(t);
833
834 return 0;
835}
836
837static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
838 struct dso *dso)
839{
840 struct tables *tables = container_of(dbe, struct tables, dbe);
841 u64 *sym_db_id = symbol__priv(sym);
842 PyObject *t;
843
844 t = tuple_new(6);
845
846 tuple_set_u64(t, 0, *sym_db_id);
847 tuple_set_u64(t, 1, dso->db_id);
848 tuple_set_u64(t, 2, sym->start);
849 tuple_set_u64(t, 3, sym->end);
850 tuple_set_s32(t, 4, sym->binding);
851 tuple_set_string(t, 5, sym->name);
852
853 call_object(tables->symbol_handler, t, "symbol_table");
854
855 Py_DECREF(t);
856
857 return 0;
858}
859
860static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
861 const char *name)
862{
863 struct tables *tables = container_of(dbe, struct tables, dbe);
864 PyObject *t;
865
866 t = tuple_new(2);
867
868 tuple_set_s32(t, 0, branch_type);
869 tuple_set_string(t, 1, name);
870
871 call_object(tables->branch_type_handler, t, "branch_type_table");
872
873 Py_DECREF(t);
874
875 return 0;
876}
877
878static int python_export_sample(struct db_export *dbe,
879 struct export_sample *es)
880{
881 struct tables *tables = container_of(dbe, struct tables, dbe);
882 PyObject *t;
883
884 t = tuple_new(22);
885
886 tuple_set_u64(t, 0, es->db_id);
887 tuple_set_u64(t, 1, es->evsel->db_id);
888 tuple_set_u64(t, 2, es->al->machine->db_id);
889 tuple_set_u64(t, 3, es->al->thread->db_id);
890 tuple_set_u64(t, 4, es->comm_db_id);
891 tuple_set_u64(t, 5, es->dso_db_id);
892 tuple_set_u64(t, 6, es->sym_db_id);
893 tuple_set_u64(t, 7, es->offset);
894 tuple_set_u64(t, 8, es->sample->ip);
895 tuple_set_u64(t, 9, es->sample->time);
896 tuple_set_s32(t, 10, es->sample->cpu);
897 tuple_set_u64(t, 11, es->addr_dso_db_id);
898 tuple_set_u64(t, 12, es->addr_sym_db_id);
899 tuple_set_u64(t, 13, es->addr_offset);
900 tuple_set_u64(t, 14, es->sample->addr);
901 tuple_set_u64(t, 15, es->sample->period);
902 tuple_set_u64(t, 16, es->sample->weight);
903 tuple_set_u64(t, 17, es->sample->transaction);
904 tuple_set_u64(t, 18, es->sample->data_src);
905 tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
906 tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
907 tuple_set_u64(t, 21, es->call_path_id);
908
909 call_object(tables->sample_handler, t, "sample_table");
910
911 Py_DECREF(t);
912
913 return 0;
914}
915
916static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
917{
918 struct tables *tables = container_of(dbe, struct tables, dbe);
919 PyObject *t;
920 u64 parent_db_id, sym_db_id;
921
922 parent_db_id = cp->parent ? cp->parent->db_id : 0;
923 sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
924
925 t = tuple_new(4);
926
927 tuple_set_u64(t, 0, cp->db_id);
928 tuple_set_u64(t, 1, parent_db_id);
929 tuple_set_u64(t, 2, sym_db_id);
930 tuple_set_u64(t, 3, cp->ip);
931
932 call_object(tables->call_path_handler, t, "call_path_table");
933
934 Py_DECREF(t);
935
936 return 0;
937}
938
939static int python_export_call_return(struct db_export *dbe,
940 struct call_return *cr)
941{
942 struct tables *tables = container_of(dbe, struct tables, dbe);
943 u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
944 PyObject *t;
945
946 t = tuple_new(11);
947
948 tuple_set_u64(t, 0, cr->db_id);
949 tuple_set_u64(t, 1, cr->thread->db_id);
950 tuple_set_u64(t, 2, comm_db_id);
951 tuple_set_u64(t, 3, cr->cp->db_id);
952 tuple_set_u64(t, 4, cr->call_time);
953 tuple_set_u64(t, 5, cr->return_time);
954 tuple_set_u64(t, 6, cr->branch_count);
955 tuple_set_u64(t, 7, cr->call_ref);
956 tuple_set_u64(t, 8, cr->return_ref);
957 tuple_set_u64(t, 9, cr->cp->parent->db_id);
958 tuple_set_s32(t, 10, cr->flags);
959
960 call_object(tables->call_return_handler, t, "call_return_table");
961
962 Py_DECREF(t);
963
964 return 0;
965}
966
967static int python_process_call_return(struct call_return *cr, void *data)
968{
969 struct db_export *dbe = data;
970
971 return db_export__call_return(dbe, cr);
972}
973
974static void python_process_general_event(struct perf_sample *sample,
975 struct perf_evsel *evsel,
976 struct addr_location *al)
977{
978 PyObject *handler, *t, *dict, *callchain;
979 static char handler_name[64];
980 unsigned n = 0;
981
982 snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
983
984 handler = get_handler(handler_name);
985 if (!handler)
986 return;
987
988 /*
989 * Use the MAX_FIELDS to make the function expandable, though
990 * currently there is only one item for the tuple.
991 */
992 t = PyTuple_New(MAX_FIELDS);
993 if (!t)
994 Py_FatalError("couldn't create Python tuple");
995
996 /* ip unwinding */
997 callchain = python_process_callchain(sample, evsel, al);
998 dict = get_perf_sample_dict(sample, evsel, al, callchain);
999
1000 PyTuple_SetItem(t, n++, dict);
1001 if (_PyTuple_Resize(&t, n) == -1)
1002 Py_FatalError("error resizing Python tuple");
1003
1004 call_object(handler, t, handler_name);
1005
1006 Py_DECREF(dict);
1007 Py_DECREF(t);
1008}
1009
1010static void python_process_event(union perf_event *event,
1011 struct perf_sample *sample,
1012 struct perf_evsel *evsel,
1013 struct addr_location *al)
1014{
1015 struct tables *tables = &tables_global;
1016
1017 switch (evsel->attr.type) {
1018 case PERF_TYPE_TRACEPOINT:
1019 python_process_tracepoint(sample, evsel, al);
1020 break;
1021 /* Reserve for future process_hw/sw/raw APIs */
1022 default:
1023 if (tables->db_export_mode)
1024 db_export__sample(&tables->dbe, event, sample, evsel, al);
1025 else
1026 python_process_general_event(sample, evsel, al);
1027 }
1028}
1029
1030static void get_handler_name(char *str, size_t size,
1031 struct perf_evsel *evsel)
1032{
1033 char *p = str;
1034
1035 scnprintf(str, size, "stat__%s", perf_evsel__name(evsel));
1036
1037 while ((p = strchr(p, ':'))) {
1038 *p = '_';
1039 p++;
1040 }
1041}
1042
1043static void
1044process_stat(struct perf_evsel *counter, int cpu, int thread, u64 tstamp,
1045 struct perf_counts_values *count)
1046{
1047 PyObject *handler, *t;
1048 static char handler_name[256];
1049 int n = 0;
1050
1051 t = PyTuple_New(MAX_FIELDS);
1052 if (!t)
1053 Py_FatalError("couldn't create Python tuple");
1054
1055 get_handler_name(handler_name, sizeof(handler_name),
1056 counter);
1057
1058 handler = get_handler(handler_name);
1059 if (!handler) {
1060 pr_debug("can't find python handler %s\n", handler_name);
1061 return;
1062 }
1063
1064 PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
1065 PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
1066
1067 tuple_set_u64(t, n++, tstamp);
1068 tuple_set_u64(t, n++, count->val);
1069 tuple_set_u64(t, n++, count->ena);
1070 tuple_set_u64(t, n++, count->run);
1071
1072 if (_PyTuple_Resize(&t, n) == -1)
1073 Py_FatalError("error resizing Python tuple");
1074
1075 call_object(handler, t, handler_name);
1076
1077 Py_DECREF(t);
1078}
1079
1080static void python_process_stat(struct perf_stat_config *config,
1081 struct perf_evsel *counter, u64 tstamp)
1082{
1083 struct thread_map *threads = counter->threads;
1084 struct cpu_map *cpus = counter->cpus;
1085 int cpu, thread;
1086
1087 if (config->aggr_mode == AGGR_GLOBAL) {
1088 process_stat(counter, -1, -1, tstamp,
1089 &counter->counts->aggr);
1090 return;
1091 }
1092
1093 for (thread = 0; thread < threads->nr; thread++) {
1094 for (cpu = 0; cpu < cpus->nr; cpu++) {
1095 process_stat(counter, cpus->map[cpu],
1096 thread_map__pid(threads, thread), tstamp,
1097 perf_counts(counter->counts, cpu, thread));
1098 }
1099 }
1100}
1101
1102static void python_process_stat_interval(u64 tstamp)
1103{
1104 PyObject *handler, *t;
1105 static const char handler_name[] = "stat__interval";
1106 int n = 0;
1107
1108 t = PyTuple_New(MAX_FIELDS);
1109 if (!t)
1110 Py_FatalError("couldn't create Python tuple");
1111
1112 handler = get_handler(handler_name);
1113 if (!handler) {
1114 pr_debug("can't find python handler %s\n", handler_name);
1115 return;
1116 }
1117
1118 tuple_set_u64(t, n++, tstamp);
1119
1120 if (_PyTuple_Resize(&t, n) == -1)
1121 Py_FatalError("error resizing Python tuple");
1122
1123 call_object(handler, t, handler_name);
1124
1125 Py_DECREF(t);
1126}
1127
1128static int run_start_sub(void)
1129{
1130 main_module = PyImport_AddModule("__main__");
1131 if (main_module == NULL)
1132 return -1;
1133 Py_INCREF(main_module);
1134
1135 main_dict = PyModule_GetDict(main_module);
1136 if (main_dict == NULL)
1137 goto error;
1138 Py_INCREF(main_dict);
1139
1140 try_call_object("trace_begin", NULL);
1141
1142 return 0;
1143
1144error:
1145 Py_XDECREF(main_dict);
1146 Py_XDECREF(main_module);
1147 return -1;
1148}
1149
1150#define SET_TABLE_HANDLER_(name, handler_name, table_name) do { \
1151 tables->handler_name = get_handler(#table_name); \
1152 if (tables->handler_name) \
1153 tables->dbe.export_ ## name = python_export_ ## name; \
1154} while (0)
1155
1156#define SET_TABLE_HANDLER(name) \
1157 SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
1158
1159static void set_table_handlers(struct tables *tables)
1160{
1161 const char *perf_db_export_mode = "perf_db_export_mode";
1162 const char *perf_db_export_calls = "perf_db_export_calls";
1163 const char *perf_db_export_callchains = "perf_db_export_callchains";
1164 PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
1165 bool export_calls = false;
1166 bool export_callchains = false;
1167 int ret;
1168
1169 memset(tables, 0, sizeof(struct tables));
1170 if (db_export__init(&tables->dbe))
1171 Py_FatalError("failed to initialize export");
1172
1173 db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
1174 if (!db_export_mode)
1175 return;
1176
1177 ret = PyObject_IsTrue(db_export_mode);
1178 if (ret == -1)
1179 handler_call_die(perf_db_export_mode);
1180 if (!ret)
1181 return;
1182
1183 /* handle export calls */
1184 tables->dbe.crp = NULL;
1185 db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
1186 if (db_export_calls) {
1187 ret = PyObject_IsTrue(db_export_calls);
1188 if (ret == -1)
1189 handler_call_die(perf_db_export_calls);
1190 export_calls = !!ret;
1191 }
1192
1193 if (export_calls) {
1194 tables->dbe.crp =
1195 call_return_processor__new(python_process_call_return,
1196 &tables->dbe);
1197 if (!tables->dbe.crp)
1198 Py_FatalError("failed to create calls processor");
1199 }
1200
1201 /* handle export callchains */
1202 tables->dbe.cpr = NULL;
1203 db_export_callchains = PyDict_GetItemString(main_dict,
1204 perf_db_export_callchains);
1205 if (db_export_callchains) {
1206 ret = PyObject_IsTrue(db_export_callchains);
1207 if (ret == -1)
1208 handler_call_die(perf_db_export_callchains);
1209 export_callchains = !!ret;
1210 }
1211
1212 if (export_callchains) {
1213 /*
1214 * Attempt to use the call path root from the call return
1215 * processor, if the call return processor is in use. Otherwise,
1216 * we allocate a new call path root. This prevents exporting
1217 * duplicate call path ids when both are in use simultaniously.
1218 */
1219 if (tables->dbe.crp)
1220 tables->dbe.cpr = tables->dbe.crp->cpr;
1221 else
1222 tables->dbe.cpr = call_path_root__new();
1223
1224 if (!tables->dbe.cpr)
1225 Py_FatalError("failed to create call path root");
1226 }
1227
1228 tables->db_export_mode = true;
1229 /*
1230 * Reserve per symbol space for symbol->db_id via symbol__priv()
1231 */
1232 symbol_conf.priv_size = sizeof(u64);
1233
1234 SET_TABLE_HANDLER(evsel);
1235 SET_TABLE_HANDLER(machine);
1236 SET_TABLE_HANDLER(thread);
1237 SET_TABLE_HANDLER(comm);
1238 SET_TABLE_HANDLER(comm_thread);
1239 SET_TABLE_HANDLER(dso);
1240 SET_TABLE_HANDLER(symbol);
1241 SET_TABLE_HANDLER(branch_type);
1242 SET_TABLE_HANDLER(sample);
1243 SET_TABLE_HANDLER(call_path);
1244 SET_TABLE_HANDLER(call_return);
1245}
1246
1247#if PY_MAJOR_VERSION < 3
1248static void _free_command_line(const char **command_line, int num)
1249{
1250 free(command_line);
1251}
1252#else
1253static void _free_command_line(wchar_t **command_line, int num)
1254{
1255 int i;
1256 for (i = 0; i < num; i++)
1257 PyMem_RawFree(command_line[i]);
1258 free(command_line);
1259}
1260#endif
1261
1262
1263/*
1264 * Start trace script
1265 */
1266static int python_start_script(const char *script, int argc, const char **argv)
1267{
1268 struct tables *tables = &tables_global;
1269#if PY_MAJOR_VERSION < 3
1270 const char **command_line;
1271#else
1272 wchar_t **command_line;
1273#endif
1274 char buf[PATH_MAX];
1275 int i, err = 0;
1276 FILE *fp;
1277
1278#if PY_MAJOR_VERSION < 3
1279 command_line = malloc((argc + 1) * sizeof(const char *));
1280 command_line[0] = script;
1281 for (i = 1; i < argc + 1; i++)
1282 command_line[i] = argv[i - 1];
1283#else
1284 command_line = malloc((argc + 1) * sizeof(wchar_t *));
1285 command_line[0] = Py_DecodeLocale(script, NULL);
1286 for (i = 1; i < argc + 1; i++)
1287 command_line[i] = Py_DecodeLocale(argv[i - 1], NULL);
1288#endif
1289
1290 Py_Initialize();
1291
1292#if PY_MAJOR_VERSION < 3
1293 initperf_trace_context();
1294 PySys_SetArgv(argc + 1, (char **)command_line);
1295#else
1296 PyInit_perf_trace_context();
1297 PySys_SetArgv(argc + 1, command_line);
1298#endif
1299
1300 fp = fopen(script, "r");
1301 if (!fp) {
1302 sprintf(buf, "Can't open python script \"%s\"", script);
1303 perror(buf);
1304 err = -1;
1305 goto error;
1306 }
1307
1308 err = PyRun_SimpleFile(fp, script);
1309 if (err) {
1310 fprintf(stderr, "Error running python script %s\n", script);
1311 goto error;
1312 }
1313
1314 err = run_start_sub();
1315 if (err) {
1316 fprintf(stderr, "Error starting python script %s\n", script);
1317 goto error;
1318 }
1319
1320 set_table_handlers(tables);
1321
1322 if (tables->db_export_mode) {
1323 err = db_export__branch_types(&tables->dbe);
1324 if (err)
1325 goto error;
1326 }
1327
1328 _free_command_line(command_line, argc + 1);
1329
1330 return err;
1331error:
1332 Py_Finalize();
1333 _free_command_line(command_line, argc + 1);
1334
1335 return err;
1336}
1337
1338static int python_flush_script(void)
1339{
1340 struct tables *tables = &tables_global;
1341
1342 return db_export__flush(&tables->dbe);
1343}
1344
1345/*
1346 * Stop trace script
1347 */
1348static int python_stop_script(void)
1349{
1350 struct tables *tables = &tables_global;
1351
1352 try_call_object("trace_end", NULL);
1353
1354 db_export__exit(&tables->dbe);
1355
1356 Py_XDECREF(main_dict);
1357 Py_XDECREF(main_module);
1358 Py_Finalize();
1359
1360 return 0;
1361}
1362
1363static int python_generate_script(struct pevent *pevent, const char *outfile)
1364{
1365 struct event_format *event = NULL;
1366 struct format_field *f;
1367 char fname[PATH_MAX];
1368 int not_first, count;
1369 FILE *ofp;
1370
1371 sprintf(fname, "%s.py", outfile);
1372 ofp = fopen(fname, "w");
1373 if (ofp == NULL) {
1374 fprintf(stderr, "couldn't open %s\n", fname);
1375 return -1;
1376 }
1377 fprintf(ofp, "# perf script event handlers, "
1378 "generated by perf script -g python\n");
1379
1380 fprintf(ofp, "# Licensed under the terms of the GNU GPL"
1381 " License version 2\n\n");
1382
1383 fprintf(ofp, "# The common_* event handler fields are the most useful "
1384 "fields common to\n");
1385
1386 fprintf(ofp, "# all events. They don't necessarily correspond to "
1387 "the 'common_*' fields\n");
1388
1389 fprintf(ofp, "# in the format files. Those fields not available as "
1390 "handler params can\n");
1391
1392 fprintf(ofp, "# be retrieved using Python functions of the form "
1393 "common_*(context).\n");
1394
1395 fprintf(ofp, "# See the perf-script-python Documentation for the list "
1396 "of available functions.\n\n");
1397
1398 fprintf(ofp, "import os\n");
1399 fprintf(ofp, "import sys\n\n");
1400
1401 fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
1402 fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
1403 fprintf(ofp, "\nfrom perf_trace_context import *\n");
1404 fprintf(ofp, "from Core import *\n\n\n");
1405
1406 fprintf(ofp, "def trace_begin():\n");
1407 fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
1408
1409 fprintf(ofp, "def trace_end():\n");
1410 fprintf(ofp, "\tprint \"in trace_end\"\n\n");
1411
1412 while ((event = trace_find_next_event(pevent, event))) {
1413 fprintf(ofp, "def %s__%s(", event->system, event->name);
1414 fprintf(ofp, "event_name, ");
1415 fprintf(ofp, "context, ");
1416 fprintf(ofp, "common_cpu,\n");
1417 fprintf(ofp, "\tcommon_secs, ");
1418 fprintf(ofp, "common_nsecs, ");
1419 fprintf(ofp, "common_pid, ");
1420 fprintf(ofp, "common_comm,\n\t");
1421 fprintf(ofp, "common_callchain, ");
1422
1423 not_first = 0;
1424 count = 0;
1425
1426 for (f = event->format.fields; f; f = f->next) {
1427 if (not_first++)
1428 fprintf(ofp, ", ");
1429 if (++count % 5 == 0)
1430 fprintf(ofp, "\n\t");
1431
1432 fprintf(ofp, "%s", f->name);
1433 }
1434 if (not_first++)
1435 fprintf(ofp, ", ");
1436 if (++count % 5 == 0)
1437 fprintf(ofp, "\n\t\t");
1438 fprintf(ofp, "perf_sample_dict");
1439
1440 fprintf(ofp, "):\n");
1441
1442 fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
1443 "common_secs, common_nsecs,\n\t\t\t"
1444 "common_pid, common_comm)\n\n");
1445
1446 fprintf(ofp, "\t\tprint \"");
1447
1448 not_first = 0;
1449 count = 0;
1450
1451 for (f = event->format.fields; f; f = f->next) {
1452 if (not_first++)
1453 fprintf(ofp, ", ");
1454 if (count && count % 3 == 0) {
1455 fprintf(ofp, "\" \\\n\t\t\"");
1456 }
1457 count++;
1458
1459 fprintf(ofp, "%s=", f->name);
1460 if (f->flags & FIELD_IS_STRING ||
1461 f->flags & FIELD_IS_FLAG ||
1462 f->flags & FIELD_IS_ARRAY ||
1463 f->flags & FIELD_IS_SYMBOLIC)
1464 fprintf(ofp, "%%s");
1465 else if (f->flags & FIELD_IS_SIGNED)
1466 fprintf(ofp, "%%d");
1467 else
1468 fprintf(ofp, "%%u");
1469 }
1470
1471 fprintf(ofp, "\" %% \\\n\t\t(");
1472
1473 not_first = 0;
1474 count = 0;
1475
1476 for (f = event->format.fields; f; f = f->next) {
1477 if (not_first++)
1478 fprintf(ofp, ", ");
1479
1480 if (++count % 5 == 0)
1481 fprintf(ofp, "\n\t\t");
1482
1483 if (f->flags & FIELD_IS_FLAG) {
1484 if ((count - 1) % 5 != 0) {
1485 fprintf(ofp, "\n\t\t");
1486 count = 4;
1487 }
1488 fprintf(ofp, "flag_str(\"");
1489 fprintf(ofp, "%s__%s\", ", event->system,
1490 event->name);
1491 fprintf(ofp, "\"%s\", %s)", f->name,
1492 f->name);
1493 } else if (f->flags & FIELD_IS_SYMBOLIC) {
1494 if ((count - 1) % 5 != 0) {
1495 fprintf(ofp, "\n\t\t");
1496 count = 4;
1497 }
1498 fprintf(ofp, "symbol_str(\"");
1499 fprintf(ofp, "%s__%s\", ", event->system,
1500 event->name);
1501 fprintf(ofp, "\"%s\", %s)", f->name,
1502 f->name);
1503 } else
1504 fprintf(ofp, "%s", f->name);
1505 }
1506
1507 fprintf(ofp, ")\n\n");
1508
1509 fprintf(ofp, "\t\tprint 'Sample: {'+"
1510 "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}'\n\n");
1511
1512 fprintf(ofp, "\t\tfor node in common_callchain:");
1513 fprintf(ofp, "\n\t\t\tif 'sym' in node:");
1514 fprintf(ofp, "\n\t\t\t\tprint \"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name'])");
1515 fprintf(ofp, "\n\t\t\telse:");
1516 fprintf(ofp, "\n\t\t\t\tprint \"\t[%%x]\" %% (node['ip'])\n\n");
1517 fprintf(ofp, "\t\tprint \"\\n\"\n\n");
1518
1519 }
1520
1521 fprintf(ofp, "def trace_unhandled(event_name, context, "
1522 "event_fields_dict, perf_sample_dict):\n");
1523
1524 fprintf(ofp, "\t\tprint get_dict_as_string(event_fields_dict)\n");
1525 fprintf(ofp, "\t\tprint 'Sample: {'+"
1526 "get_dict_as_string(perf_sample_dict['sample'], ', ')+'}'\n\n");
1527
1528 fprintf(ofp, "def print_header("
1529 "event_name, cpu, secs, nsecs, pid, comm):\n"
1530 "\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
1531 "(event_name, cpu, secs, nsecs, pid, comm),\n\n");
1532
1533 fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
1534 "\treturn delimiter.join"
1535 "(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
1536
1537 fclose(ofp);
1538
1539 fprintf(stderr, "generated Python script: %s\n", fname);
1540
1541 return 0;
1542}
1543
1544struct scripting_ops python_scripting_ops = {
1545 .name = "Python",
1546 .start_script = python_start_script,
1547 .flush_script = python_flush_script,
1548 .stop_script = python_stop_script,
1549 .process_event = python_process_event,
1550 .process_stat = python_process_stat,
1551 .process_stat_interval = python_process_stat_interval,
1552 .generate_script = python_generate_script,
1553};
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};