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