]> git.proxmox.com Git - mirror_ubuntu-focal-kernel.git/blame - tools/perf/util/scripting-engines/trace-event-python.c
perf tools: Add call information to the database export API
[mirror_ubuntu-focal-kernel.git] / tools / perf / util / scripting-engines / trace-event-python.c
CommitLineData
7e4b21b8
TZ
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 <stdio.h>
25#include <stdlib.h>
26#include <string.h>
df919b40 27#include <stdbool.h>
7e4b21b8
TZ
28#include <errno.h>
29
30#include "../../perf.h"
84f5d36f 31#include "../debug.h"
8f651eae 32#include "../callchain.h"
fcf65bf1 33#include "../evsel.h"
7e4b21b8 34#include "../util.h"
743eb868
ACM
35#include "../event.h"
36#include "../thread.h"
df919b40
AH
37#include "../comm.h"
38#include "../machine.h"
39#include "../db-export.h"
7e4b21b8 40#include "../trace-event.h"
0f5f5bcd 41#include "../machine.h"
7e4b21b8
TZ
42
43PyMODINIT_FUNC initperf_trace_context(void);
44
45#define FTRACE_MAX_EVENT \
46 ((1 << (sizeof(unsigned short) * 8)) - 1)
47
aaf045f7 48struct event_format *events[FTRACE_MAX_EVENT];
7e4b21b8
TZ
49
50#define MAX_FIELDS 64
51#define N_COMMON_FIELDS 7
52
53extern struct scripting_context *scripting_context;
54
55static char *cur_field_name;
56static int zero_flag_atom;
57
58static PyObject *main_module, *main_dict;
59
df919b40
AH
60struct tables {
61 struct db_export dbe;
62 PyObject *evsel_handler;
63 PyObject *machine_handler;
64 PyObject *thread_handler;
65 PyObject *comm_handler;
66 PyObject *comm_thread_handler;
67 PyObject *dso_handler;
68 PyObject *symbol_handler;
c29414f5 69 PyObject *branch_type_handler;
df919b40
AH
70 PyObject *sample_handler;
71 bool db_export_mode;
72};
73
74static struct tables tables_global;
75
05f832e3 76static void handler_call_die(const char *handler_name) NORETURN;
7e4b21b8
TZ
77static void handler_call_die(const char *handler_name)
78{
79 PyErr_Print();
80 Py_FatalError("problem in Python trace event handler");
05f832e3
JS
81 // Py_FatalError does not return
82 // but we have to make the compiler happy
83 abort();
7e4b21b8
TZ
84}
85
c0268e8d
JS
86/*
87 * Insert val into into the dictionary and decrement the reference counter.
88 * This is necessary for dictionaries since PyDict_SetItemString() does not
89 * steal a reference, as opposed to PyTuple_SetItem().
90 */
91static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
92{
93 PyDict_SetItemString(dict, key, val);
94 Py_DECREF(val);
95}
96
a5563edf
AH
97static PyObject *get_handler(const char *handler_name)
98{
99 PyObject *handler;
100
101 handler = PyDict_GetItemString(main_dict, handler_name);
102 if (handler && !PyCallable_Check(handler))
103 return NULL;
104 return handler;
105}
106
107static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
108{
109 PyObject *retval;
110
111 retval = PyObject_CallObject(handler, args);
112 if (retval == NULL)
113 handler_call_die(die_msg);
114 Py_DECREF(retval);
115}
116
117static void try_call_object(const char *handler_name, PyObject *args)
118{
119 PyObject *handler;
120
121 handler = get_handler(handler_name);
122 if (handler)
123 call_object(handler, args, handler_name);
124}
125
7e4b21b8
TZ
126static void define_value(enum print_arg_type field_type,
127 const char *ev_name,
128 const char *field_name,
129 const char *field_value,
130 const char *field_str)
131{
132 const char *handler_name = "define_flag_value";
a5563edf 133 PyObject *t;
7e4b21b8
TZ
134 unsigned long long value;
135 unsigned n = 0;
136
137 if (field_type == PRINT_SYMBOL)
138 handler_name = "define_symbolic_value";
139
44ad9cd8 140 t = PyTuple_New(4);
7e4b21b8
TZ
141 if (!t)
142 Py_FatalError("couldn't create Python tuple");
143
144 value = eval_flag(field_value);
145
146 PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
147 PyTuple_SetItem(t, n++, PyString_FromString(field_name));
148 PyTuple_SetItem(t, n++, PyInt_FromLong(value));
149 PyTuple_SetItem(t, n++, PyString_FromString(field_str));
150
a5563edf 151 try_call_object(handler_name, t);
7e4b21b8
TZ
152
153 Py_DECREF(t);
154}
155
156static void define_values(enum print_arg_type field_type,
157 struct print_flag_sym *field,
158 const char *ev_name,
159 const char *field_name)
160{
161 define_value(field_type, ev_name, field_name, field->value,
162 field->str);
163
164 if (field->next)
165 define_values(field_type, field->next, ev_name, field_name);
166}
167
168static void define_field(enum print_arg_type field_type,
169 const char *ev_name,
170 const char *field_name,
171 const char *delim)
172{
173 const char *handler_name = "define_flag_field";
a5563edf 174 PyObject *t;
7e4b21b8
TZ
175 unsigned n = 0;
176
177 if (field_type == PRINT_SYMBOL)
178 handler_name = "define_symbolic_field";
179
44ad9cd8
TZ
180 if (field_type == PRINT_FLAGS)
181 t = PyTuple_New(3);
182 else
183 t = PyTuple_New(2);
7e4b21b8
TZ
184 if (!t)
185 Py_FatalError("couldn't create Python tuple");
186
187 PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
188 PyTuple_SetItem(t, n++, PyString_FromString(field_name));
189 if (field_type == PRINT_FLAGS)
190 PyTuple_SetItem(t, n++, PyString_FromString(delim));
191
a5563edf 192 try_call_object(handler_name, t);
7e4b21b8
TZ
193
194 Py_DECREF(t);
195}
196
aaf045f7 197static void define_event_symbols(struct event_format *event,
7e4b21b8
TZ
198 const char *ev_name,
199 struct print_arg *args)
200{
201 switch (args->type) {
202 case PRINT_NULL:
203 break;
204 case PRINT_ATOM:
205 define_value(PRINT_FLAGS, ev_name, cur_field_name, "0",
206 args->atom.atom);
207 zero_flag_atom = 0;
208 break;
209 case PRINT_FIELD:
f5385650 210 free(cur_field_name);
7e4b21b8
TZ
211 cur_field_name = strdup(args->field.name);
212 break;
213 case PRINT_FLAGS:
214 define_event_symbols(event, ev_name, args->flags.field);
215 define_field(PRINT_FLAGS, ev_name, cur_field_name,
216 args->flags.delim);
217 define_values(PRINT_FLAGS, args->flags.flags, ev_name,
218 cur_field_name);
219 break;
220 case PRINT_SYMBOL:
221 define_event_symbols(event, ev_name, args->symbol.field);
222 define_field(PRINT_SYMBOL, ev_name, cur_field_name, NULL);
223 define_values(PRINT_SYMBOL, args->symbol.symbols, ev_name,
224 cur_field_name);
225 break;
e080e6f1
NK
226 case PRINT_HEX:
227 define_event_symbols(event, ev_name, args->hex.field);
228 define_event_symbols(event, ev_name, args->hex.size);
229 break;
7e4b21b8
TZ
230 case PRINT_STRING:
231 break;
232 case PRINT_TYPE:
233 define_event_symbols(event, ev_name, args->typecast.item);
234 break;
235 case PRINT_OP:
236 if (strcmp(args->op.op, ":") == 0)
237 zero_flag_atom = 1;
238 define_event_symbols(event, ev_name, args->op.left);
239 define_event_symbols(event, ev_name, args->op.right);
240 break;
241 default:
aaf045f7
SR
242 /* gcc warns for these? */
243 case PRINT_BSTRING:
244 case PRINT_DYNAMIC_ARRAY:
245 case PRINT_FUNC:
473a778a 246 case PRINT_BITMASK:
7e4b21b8
TZ
247 /* we should warn... */
248 return;
249 }
250
251 if (args->next)
252 define_event_symbols(event, ev_name, args->next);
253}
254
fcf65bf1 255static inline struct event_format *find_cache_event(struct perf_evsel *evsel)
7e4b21b8
TZ
256{
257 static char ev_name[256];
aaf045f7 258 struct event_format *event;
fcf65bf1 259 int type = evsel->attr.config;
7e4b21b8 260
fcf65bf1
ACM
261 /*
262 * XXX: Do we really need to cache this since now we have evsel->tp_format
263 * cached already? Need to re-read this "cache" routine that as well calls
264 * define_event_symbols() :-\
265 */
7e4b21b8
TZ
266 if (events[type])
267 return events[type];
268
fcf65bf1 269 events[type] = event = evsel->tp_format;
7e4b21b8
TZ
270 if (!event)
271 return NULL;
272
273 sprintf(ev_name, "%s__%s", event->system, event->name);
274
275 define_event_symbols(event, ev_name, event->print_fmt.args);
276
277 return event;
278}
279
33058b94
SAS
280static PyObject *get_field_numeric_entry(struct event_format *event,
281 struct format_field *field, void *data)
282{
8ac631cd
SAS
283 bool is_array = field->flags & FIELD_IS_ARRAY;
284 PyObject *obj, *list = NULL;
33058b94 285 unsigned long long val;
8ac631cd 286 unsigned int item_size, n_items, i;
33058b94 287
8ac631cd
SAS
288 if (is_array) {
289 list = PyList_New(field->arraylen);
290 item_size = field->size / field->arraylen;
291 n_items = field->arraylen;
33058b94 292 } else {
8ac631cd
SAS
293 item_size = field->size;
294 n_items = 1;
33058b94 295 }
8ac631cd
SAS
296
297 for (i = 0; i < n_items; i++) {
298
299 val = read_size(event, data + field->offset + i * item_size,
300 item_size);
301 if (field->flags & FIELD_IS_SIGNED) {
302 if ((long long)val >= LONG_MIN &&
303 (long long)val <= LONG_MAX)
304 obj = PyInt_FromLong(val);
305 else
306 obj = PyLong_FromLongLong(val);
307 } else {
308 if (val <= LONG_MAX)
309 obj = PyInt_FromLong(val);
310 else
311 obj = PyLong_FromUnsignedLongLong(val);
312 }
313 if (is_array)
314 PyList_SET_ITEM(list, i, obj);
315 }
316 if (is_array)
317 obj = list;
33058b94
SAS
318 return obj;
319}
320
0f5f5bcd
JS
321
322static PyObject *python_process_callchain(struct perf_sample *sample,
323 struct perf_evsel *evsel,
324 struct addr_location *al)
325{
326 PyObject *pylist;
327
328 pylist = PyList_New(0);
329 if (!pylist)
330 Py_FatalError("couldn't create Python list");
331
332 if (!symbol_conf.use_callchain || !sample->callchain)
333 goto exit;
334
cc8b7c2b
ACM
335 if (thread__resolve_callchain(al->thread, evsel,
336 sample, NULL, NULL,
337 PERF_MAX_STACK_DEPTH) != 0) {
0f5f5bcd
JS
338 pr_err("Failed to resolve callchain. Skipping\n");
339 goto exit;
340 }
341 callchain_cursor_commit(&callchain_cursor);
342
343
344 while (1) {
345 PyObject *pyelem;
346 struct callchain_cursor_node *node;
347 node = callchain_cursor_current(&callchain_cursor);
348 if (!node)
349 break;
350
351 pyelem = PyDict_New();
352 if (!pyelem)
353 Py_FatalError("couldn't create Python dictionary");
354
355
356 pydict_set_item_string_decref(pyelem, "ip",
357 PyLong_FromUnsignedLongLong(node->ip));
358
359 if (node->sym) {
360 PyObject *pysym = PyDict_New();
361 if (!pysym)
362 Py_FatalError("couldn't create Python dictionary");
363 pydict_set_item_string_decref(pysym, "start",
364 PyLong_FromUnsignedLongLong(node->sym->start));
365 pydict_set_item_string_decref(pysym, "end",
366 PyLong_FromUnsignedLongLong(node->sym->end));
367 pydict_set_item_string_decref(pysym, "binding",
368 PyInt_FromLong(node->sym->binding));
369 pydict_set_item_string_decref(pysym, "name",
370 PyString_FromStringAndSize(node->sym->name,
371 node->sym->namelen));
372 pydict_set_item_string_decref(pyelem, "sym", pysym);
373 }
374
375 if (node->map) {
376 struct map *map = node->map;
377 const char *dsoname = "[unknown]";
378 if (map && map->dso && (map->dso->name || map->dso->long_name)) {
379 if (symbol_conf.show_kernel_path && map->dso->long_name)
380 dsoname = map->dso->long_name;
381 else if (map->dso->name)
382 dsoname = map->dso->name;
383 }
384 pydict_set_item_string_decref(pyelem, "dso",
385 PyString_FromString(dsoname));
386 }
387
388 callchain_cursor_advance(&callchain_cursor);
389 PyList_Append(pylist, pyelem);
390 Py_DECREF(pyelem);
391 }
392
393exit:
394 return pylist;
395}
396
397
b7fff6b5
ACM
398static void python_process_tracepoint(struct perf_sample *sample,
399 struct perf_evsel *evsel,
400 struct thread *thread,
401 struct addr_location *al)
7e4b21b8 402{
a5563edf 403 PyObject *handler, *context, *t, *obj, *callchain;
0f5f5bcd 404 PyObject *dict = NULL;
7e4b21b8
TZ
405 static char handler_name[256];
406 struct format_field *field;
7e4b21b8 407 unsigned long s, ns;
aaf045f7 408 struct event_format *event;
7e4b21b8 409 unsigned n = 0;
7e4b21b8 410 int pid;
be6d842a
DA
411 int cpu = sample->cpu;
412 void *data = sample->raw_data;
413 unsigned long long nsecs = sample->time;
b9c5143a 414 const char *comm = thread__comm_str(thread);
7e4b21b8
TZ
415
416 t = PyTuple_New(MAX_FIELDS);
417 if (!t)
418 Py_FatalError("couldn't create Python tuple");
419
fcf65bf1 420 event = find_cache_event(evsel);
7e4b21b8 421 if (!event)
fcf65bf1 422 die("ug! no event found for type %d", (int)evsel->attr.config);
7e4b21b8 423
97822433 424 pid = raw_field_value(event, "common_pid", data);
7e4b21b8
TZ
425
426 sprintf(handler_name, "%s__%s", event->system, event->name);
427
a5563edf 428 handler = get_handler(handler_name);
c0251485
PT
429 if (!handler) {
430 dict = PyDict_New();
431 if (!dict)
432 Py_FatalError("couldn't create Python dict");
433 }
7e4b21b8
TZ
434 s = nsecs / NSECS_PER_SEC;
435 ns = nsecs - s * NSECS_PER_SEC;
436
437 scripting_context->event_data = data;
2de9533d 438 scripting_context->pevent = evsel->tp_format->pevent;
7e4b21b8
TZ
439
440 context = PyCObject_FromVoidPtr(scripting_context, NULL);
441
442 PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
fb7d0b3c 443 PyTuple_SetItem(t, n++, context);
7e4b21b8 444
0f5f5bcd
JS
445 /* ip unwinding */
446 callchain = python_process_callchain(sample, evsel, al);
447
c0251485
PT
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));
0f5f5bcd 454 PyTuple_SetItem(t, n++, callchain);
c0251485 455 } else {
c0268e8d
JS
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));
0f5f5bcd 461 pydict_set_item_string_decref(dict, "common_callchain", callchain);
c0251485 462 }
7e4b21b8
TZ
463 for (field = event->format.fields; field; field = field->next) {
464 if (field->flags & FIELD_IS_STRING) {
465 int offset;
466 if (field->flags & FIELD_IS_DYNAMIC) {
467 offset = *(int *)(data + field->offset);
468 offset &= 0xffff;
469 } else
470 offset = field->offset;
b1dcc03c 471 obj = PyString_FromString((char *)data + offset);
7e4b21b8 472 } else { /* FIELD_IS_NUMERIC */
33058b94 473 obj = get_field_numeric_entry(event, field, data);
7e4b21b8 474 }
c0251485
PT
475 if (handler)
476 PyTuple_SetItem(t, n++, obj);
477 else
c0268e8d 478 pydict_set_item_string_decref(dict, field->name, obj);
c0251485 479
7e4b21b8 480 }
0f5f5bcd 481
c0251485
PT
482 if (!handler)
483 PyTuple_SetItem(t, n++, dict);
7e4b21b8
TZ
484
485 if (_PyTuple_Resize(&t, n) == -1)
486 Py_FatalError("error resizing Python tuple");
487
c0251485 488 if (handler) {
a5563edf 489 call_object(handler, t, handler_name);
7e4b21b8 490 } else {
a5563edf 491 try_call_object("trace_unhandled", t);
c0251485 492 Py_DECREF(dict);
7e4b21b8
TZ
493 }
494
495 Py_DECREF(t);
496}
497
df919b40
AH
498static PyObject *tuple_new(unsigned int sz)
499{
500 PyObject *t;
501
502 t = PyTuple_New(sz);
503 if (!t)
504 Py_FatalError("couldn't create Python tuple");
505 return t;
506}
507
508static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
509{
510#if BITS_PER_LONG == 64
511 return PyTuple_SetItem(t, pos, PyInt_FromLong(val));
512#endif
513#if BITS_PER_LONG == 32
514 return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
515#endif
516}
517
518static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
519{
520 return PyTuple_SetItem(t, pos, PyInt_FromLong(val));
521}
522
523static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
524{
525 return PyTuple_SetItem(t, pos, PyString_FromString(s));
526}
527
528static int python_export_evsel(struct db_export *dbe, struct perf_evsel *evsel)
529{
530 struct tables *tables = container_of(dbe, struct tables, dbe);
531 PyObject *t;
532
533 t = tuple_new(2);
534
535 tuple_set_u64(t, 0, evsel->db_id);
536 tuple_set_string(t, 1, perf_evsel__name(evsel));
537
538 call_object(tables->evsel_handler, t, "evsel_table");
539
540 Py_DECREF(t);
541
542 return 0;
543}
544
545static int python_export_machine(struct db_export *dbe,
546 struct machine *machine)
547{
548 struct tables *tables = container_of(dbe, struct tables, dbe);
549 PyObject *t;
550
551 t = tuple_new(3);
552
553 tuple_set_u64(t, 0, machine->db_id);
554 tuple_set_s32(t, 1, machine->pid);
555 tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
556
557 call_object(tables->machine_handler, t, "machine_table");
558
559 Py_DECREF(t);
560
561 return 0;
562}
563
564static int python_export_thread(struct db_export *dbe, struct thread *thread,
565 u64 main_thread_db_id, struct machine *machine)
566{
567 struct tables *tables = container_of(dbe, struct tables, dbe);
568 PyObject *t;
569
570 t = tuple_new(5);
571
572 tuple_set_u64(t, 0, thread->db_id);
573 tuple_set_u64(t, 1, machine->db_id);
574 tuple_set_u64(t, 2, main_thread_db_id);
575 tuple_set_s32(t, 3, thread->pid_);
576 tuple_set_s32(t, 4, thread->tid);
577
578 call_object(tables->thread_handler, t, "thread_table");
579
580 Py_DECREF(t);
581
582 return 0;
583}
584
585static int python_export_comm(struct db_export *dbe, struct comm *comm)
586{
587 struct tables *tables = container_of(dbe, struct tables, dbe);
588 PyObject *t;
589
590 t = tuple_new(2);
591
592 tuple_set_u64(t, 0, comm->db_id);
593 tuple_set_string(t, 1, comm__str(comm));
594
595 call_object(tables->comm_handler, t, "comm_table");
596
597 Py_DECREF(t);
598
599 return 0;
600}
601
602static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
603 struct comm *comm, struct thread *thread)
604{
605 struct tables *tables = container_of(dbe, struct tables, dbe);
606 PyObject *t;
607
608 t = tuple_new(3);
609
610 tuple_set_u64(t, 0, db_id);
611 tuple_set_u64(t, 1, comm->db_id);
612 tuple_set_u64(t, 2, thread->db_id);
613
614 call_object(tables->comm_thread_handler, t, "comm_thread_table");
615
616 Py_DECREF(t);
617
618 return 0;
619}
620
621static int python_export_dso(struct db_export *dbe, struct dso *dso,
622 struct machine *machine)
623{
624 struct tables *tables = container_of(dbe, struct tables, dbe);
625 char sbuild_id[BUILD_ID_SIZE * 2 + 1];
626 PyObject *t;
627
628 build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);
629
630 t = tuple_new(5);
631
632 tuple_set_u64(t, 0, dso->db_id);
633 tuple_set_u64(t, 1, machine->db_id);
634 tuple_set_string(t, 2, dso->short_name);
635 tuple_set_string(t, 3, dso->long_name);
636 tuple_set_string(t, 4, sbuild_id);
637
638 call_object(tables->dso_handler, t, "dso_table");
639
640 Py_DECREF(t);
641
642 return 0;
643}
644
645static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
646 struct dso *dso)
647{
648 struct tables *tables = container_of(dbe, struct tables, dbe);
649 u64 *sym_db_id = symbol__priv(sym);
650 PyObject *t;
651
652 t = tuple_new(6);
653
654 tuple_set_u64(t, 0, *sym_db_id);
655 tuple_set_u64(t, 1, dso->db_id);
656 tuple_set_u64(t, 2, sym->start);
657 tuple_set_u64(t, 3, sym->end);
658 tuple_set_s32(t, 4, sym->binding);
659 tuple_set_string(t, 5, sym->name);
660
661 call_object(tables->symbol_handler, t, "symbol_table");
662
663 Py_DECREF(t);
664
665 return 0;
666}
667
c29414f5
AH
668static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
669 const char *name)
670{
671 struct tables *tables = container_of(dbe, struct tables, dbe);
672 PyObject *t;
673
674 t = tuple_new(2);
675
676 tuple_set_s32(t, 0, branch_type);
677 tuple_set_string(t, 1, name);
678
679 call_object(tables->branch_type_handler, t, "branch_type_table");
680
681 Py_DECREF(t);
682
683 return 0;
684}
685
df919b40
AH
686static int python_export_sample(struct db_export *dbe,
687 struct export_sample *es)
688{
689 struct tables *tables = container_of(dbe, struct tables, dbe);
690 PyObject *t;
691
c29414f5 692 t = tuple_new(21);
df919b40
AH
693
694 tuple_set_u64(t, 0, es->db_id);
695 tuple_set_u64(t, 1, es->evsel->db_id);
696 tuple_set_u64(t, 2, es->al->machine->db_id);
697 tuple_set_u64(t, 3, es->thread->db_id);
698 tuple_set_u64(t, 4, es->comm_db_id);
699 tuple_set_u64(t, 5, es->dso_db_id);
700 tuple_set_u64(t, 6, es->sym_db_id);
701 tuple_set_u64(t, 7, es->offset);
702 tuple_set_u64(t, 8, es->sample->ip);
703 tuple_set_u64(t, 9, es->sample->time);
704 tuple_set_s32(t, 10, es->sample->cpu);
705 tuple_set_u64(t, 11, es->addr_dso_db_id);
706 tuple_set_u64(t, 12, es->addr_sym_db_id);
707 tuple_set_u64(t, 13, es->addr_offset);
708 tuple_set_u64(t, 14, es->sample->addr);
709 tuple_set_u64(t, 15, es->sample->period);
710 tuple_set_u64(t, 16, es->sample->weight);
711 tuple_set_u64(t, 17, es->sample->transaction);
712 tuple_set_u64(t, 18, es->sample->data_src);
c29414f5
AH
713 tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
714 tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
df919b40
AH
715
716 call_object(tables->sample_handler, t, "sample_table");
717
718 Py_DECREF(t);
719
720 return 0;
721}
722
b7fff6b5 723static void python_process_general_event(struct perf_sample *sample,
6a6daec2 724 struct perf_evsel *evsel,
2eaa1b40 725 struct thread *thread,
87b6a3ad 726 struct addr_location *al)
6a6daec2 727{
a5563edf 728 PyObject *handler, *t, *dict, *callchain, *dict_sample;
6a6daec2
FT
729 static char handler_name[64];
730 unsigned n = 0;
6a6daec2 731
fd6b858a
FT
732 /*
733 * Use the MAX_FIELDS to make the function expandable, though
87b6a3ad 734 * currently there is only one item for the tuple.
fd6b858a 735 */
6a6daec2
FT
736 t = PyTuple_New(MAX_FIELDS);
737 if (!t)
738 Py_FatalError("couldn't create Python tuple");
739
fd6b858a
FT
740 dict = PyDict_New();
741 if (!dict)
742 Py_FatalError("couldn't create Python dictionary");
743
57608cfd
JS
744 dict_sample = PyDict_New();
745 if (!dict_sample)
746 Py_FatalError("couldn't create Python dictionary");
747
6a6daec2
FT
748 snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
749
a5563edf
AH
750 handler = get_handler(handler_name);
751 if (!handler)
6a6daec2 752 goto exit;
6a6daec2 753
c0268e8d
JS
754 pydict_set_item_string_decref(dict, "ev_name", PyString_FromString(perf_evsel__name(evsel)));
755 pydict_set_item_string_decref(dict, "attr", PyString_FromStringAndSize(
fd6b858a 756 (const char *)&evsel->attr, sizeof(evsel->attr)));
57608cfd
JS
757
758 pydict_set_item_string_decref(dict_sample, "pid",
759 PyInt_FromLong(sample->pid));
760 pydict_set_item_string_decref(dict_sample, "tid",
761 PyInt_FromLong(sample->tid));
762 pydict_set_item_string_decref(dict_sample, "cpu",
763 PyInt_FromLong(sample->cpu));
764 pydict_set_item_string_decref(dict_sample, "ip",
765 PyLong_FromUnsignedLongLong(sample->ip));
766 pydict_set_item_string_decref(dict_sample, "time",
767 PyLong_FromUnsignedLongLong(sample->time));
768 pydict_set_item_string_decref(dict_sample, "period",
769 PyLong_FromUnsignedLongLong(sample->period));
770 pydict_set_item_string_decref(dict, "sample", dict_sample);
771
c0268e8d 772 pydict_set_item_string_decref(dict, "raw_buf", PyString_FromStringAndSize(
fd6b858a 773 (const char *)sample->raw_data, sample->raw_size));
c0268e8d 774 pydict_set_item_string_decref(dict, "comm",
b9c5143a 775 PyString_FromString(thread__comm_str(thread)));
fd6b858a 776 if (al->map) {
c0268e8d 777 pydict_set_item_string_decref(dict, "dso",
fd6b858a
FT
778 PyString_FromString(al->map->dso->name));
779 }
780 if (al->sym) {
c0268e8d 781 pydict_set_item_string_decref(dict, "symbol",
fd6b858a
FT
782 PyString_FromString(al->sym->name));
783 }
6a6daec2 784
0f5f5bcd
JS
785 /* ip unwinding */
786 callchain = python_process_callchain(sample, evsel, al);
787 pydict_set_item_string_decref(dict, "callchain", callchain);
788
fd6b858a 789 PyTuple_SetItem(t, n++, dict);
6a6daec2
FT
790 if (_PyTuple_Resize(&t, n) == -1)
791 Py_FatalError("error resizing Python tuple");
792
a5563edf 793 call_object(handler, t, handler_name);
6a6daec2 794exit:
fd6b858a 795 Py_DECREF(dict);
6a6daec2
FT
796 Py_DECREF(t);
797}
798
df919b40 799static void python_process_event(union perf_event *event,
6a6daec2
FT
800 struct perf_sample *sample,
801 struct perf_evsel *evsel,
2eaa1b40 802 struct thread *thread,
73994dc1 803 struct addr_location *al)
6a6daec2 804{
df919b40
AH
805 struct tables *tables = &tables_global;
806
6a6daec2
FT
807 switch (evsel->attr.type) {
808 case PERF_TYPE_TRACEPOINT:
b7fff6b5 809 python_process_tracepoint(sample, evsel, thread, al);
6a6daec2
FT
810 break;
811 /* Reserve for future process_hw/sw/raw APIs */
812 default:
df919b40
AH
813 if (tables->db_export_mode)
814 db_export__sample(&tables->dbe, event, sample, evsel,
815 thread, al);
816 else
817 python_process_general_event(sample, evsel, thread, al);
6a6daec2
FT
818 }
819}
820
7e4b21b8
TZ
821static int run_start_sub(void)
822{
7e4b21b8
TZ
823 main_module = PyImport_AddModule("__main__");
824 if (main_module == NULL)
825 return -1;
826 Py_INCREF(main_module);
827
828 main_dict = PyModule_GetDict(main_module);
a5563edf 829 if (main_dict == NULL)
7e4b21b8 830 goto error;
7e4b21b8
TZ
831 Py_INCREF(main_dict);
832
a5563edf 833 try_call_object("trace_begin", NULL);
7e4b21b8 834
a5563edf 835 return 0;
7e4b21b8 836
7e4b21b8
TZ
837error:
838 Py_XDECREF(main_dict);
839 Py_XDECREF(main_module);
a5563edf 840 return -1;
7e4b21b8
TZ
841}
842
df919b40
AH
843#define SET_TABLE_HANDLER_(name, handler_name, table_name) do { \
844 tables->handler_name = get_handler(#table_name); \
845 if (tables->handler_name) \
846 tables->dbe.export_ ## name = python_export_ ## name; \
847} while (0)
848
849#define SET_TABLE_HANDLER(name) \
850 SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
851
852static void set_table_handlers(struct tables *tables)
853{
854 const char *perf_db_export_mode = "perf_db_export_mode";
855 PyObject *db_export_mode;
856 int ret;
857
858 memset(tables, 0, sizeof(struct tables));
859 if (db_export__init(&tables->dbe))
860 Py_FatalError("failed to initialize export");
861
862 db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
863 if (!db_export_mode)
864 return;
865
866 ret = PyObject_IsTrue(db_export_mode);
867 if (ret == -1)
868 handler_call_die(perf_db_export_mode);
869 if (!ret)
870 return;
871
872 tables->db_export_mode = true;
873 /*
874 * Reserve per symbol space for symbol->db_id via symbol__priv()
875 */
876 symbol_conf.priv_size = sizeof(u64);
877
878 SET_TABLE_HANDLER(evsel);
879 SET_TABLE_HANDLER(machine);
880 SET_TABLE_HANDLER(thread);
881 SET_TABLE_HANDLER(comm);
882 SET_TABLE_HANDLER(comm_thread);
883 SET_TABLE_HANDLER(dso);
884 SET_TABLE_HANDLER(symbol);
c29414f5 885 SET_TABLE_HANDLER(branch_type);
df919b40
AH
886 SET_TABLE_HANDLER(sample);
887}
888
7e4b21b8
TZ
889/*
890 * Start trace script
891 */
892static int python_start_script(const char *script, int argc, const char **argv)
893{
df919b40 894 struct tables *tables = &tables_global;
7e4b21b8
TZ
895 const char **command_line;
896 char buf[PATH_MAX];
897 int i, err = 0;
898 FILE *fp;
899
900 command_line = malloc((argc + 1) * sizeof(const char *));
901 command_line[0] = script;
902 for (i = 1; i < argc + 1; i++)
903 command_line[i] = argv[i - 1];
904
905 Py_Initialize();
906
907 initperf_trace_context();
908
909 PySys_SetArgv(argc + 1, (char **)command_line);
910
911 fp = fopen(script, "r");
912 if (!fp) {
913 sprintf(buf, "Can't open python script \"%s\"", script);
914 perror(buf);
915 err = -1;
916 goto error;
917 }
918
919 err = PyRun_SimpleFile(fp, script);
920 if (err) {
921 fprintf(stderr, "Error running python script %s\n", script);
922 goto error;
923 }
924
925 err = run_start_sub();
926 if (err) {
927 fprintf(stderr, "Error starting python script %s\n", script);
928 goto error;
929 }
930
931 free(command_line);
7e4b21b8 932
df919b40
AH
933 set_table_handlers(tables);
934
c29414f5
AH
935 if (tables->db_export_mode) {
936 err = db_export__branch_types(&tables->dbe);
937 if (err)
938 goto error;
939 }
940
7e4b21b8
TZ
941 return err;
942error:
943 Py_Finalize();
944 free(command_line);
945
946 return err;
947}
948
d445dd2a
AH
949static int python_flush_script(void)
950{
951 return 0;
952}
953
7e4b21b8
TZ
954/*
955 * Stop trace script
956 */
957static int python_stop_script(void)
958{
df919b40
AH
959 struct tables *tables = &tables_global;
960
a5563edf 961 try_call_object("trace_end", NULL);
7e4b21b8 962
df919b40
AH
963 db_export__exit(&tables->dbe);
964
7e4b21b8
TZ
965 Py_XDECREF(main_dict);
966 Py_XDECREF(main_module);
967 Py_Finalize();
968
a5563edf 969 return 0;
7e4b21b8
TZ
970}
971
da378962 972static int python_generate_script(struct pevent *pevent, const char *outfile)
7e4b21b8 973{
aaf045f7 974 struct event_format *event = NULL;
7e4b21b8
TZ
975 struct format_field *f;
976 char fname[PATH_MAX];
977 int not_first, count;
978 FILE *ofp;
979
980 sprintf(fname, "%s.py", outfile);
981 ofp = fopen(fname, "w");
982 if (ofp == NULL) {
983 fprintf(stderr, "couldn't open %s\n", fname);
984 return -1;
985 }
133dc4c3
IM
986 fprintf(ofp, "# perf script event handlers, "
987 "generated by perf script -g python\n");
7e4b21b8
TZ
988
989 fprintf(ofp, "# Licensed under the terms of the GNU GPL"
990 " License version 2\n\n");
991
992 fprintf(ofp, "# The common_* event handler fields are the most useful "
993 "fields common to\n");
994
995 fprintf(ofp, "# all events. They don't necessarily correspond to "
996 "the 'common_*' fields\n");
997
998 fprintf(ofp, "# in the format files. Those fields not available as "
999 "handler params can\n");
1000
1001 fprintf(ofp, "# be retrieved using Python functions of the form "
1002 "common_*(context).\n");
1003
1004 fprintf(ofp, "# See the perf-trace-python Documentation for the list "
1005 "of available functions.\n\n");
1006
1007 fprintf(ofp, "import os\n");
1008 fprintf(ofp, "import sys\n\n");
1009
1010 fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
1011 fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
1012 fprintf(ofp, "\nfrom perf_trace_context import *\n");
1013 fprintf(ofp, "from Core import *\n\n\n");
1014
1015 fprintf(ofp, "def trace_begin():\n");
1016 fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
1017
1018 fprintf(ofp, "def trace_end():\n");
1019 fprintf(ofp, "\tprint \"in trace_end\"\n\n");
1020
da378962 1021 while ((event = trace_find_next_event(pevent, event))) {
7e4b21b8
TZ
1022 fprintf(ofp, "def %s__%s(", event->system, event->name);
1023 fprintf(ofp, "event_name, ");
1024 fprintf(ofp, "context, ");
1025 fprintf(ofp, "common_cpu,\n");
1026 fprintf(ofp, "\tcommon_secs, ");
1027 fprintf(ofp, "common_nsecs, ");
1028 fprintf(ofp, "common_pid, ");
1029 fprintf(ofp, "common_comm,\n\t");
0f5f5bcd 1030 fprintf(ofp, "common_callchain, ");
7e4b21b8
TZ
1031
1032 not_first = 0;
1033 count = 0;
1034
1035 for (f = event->format.fields; f; f = f->next) {
1036 if (not_first++)
1037 fprintf(ofp, ", ");
1038 if (++count % 5 == 0)
1039 fprintf(ofp, "\n\t");
1040
1041 fprintf(ofp, "%s", f->name);
1042 }
1043 fprintf(ofp, "):\n");
1044
1045 fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
1046 "common_secs, common_nsecs,\n\t\t\t"
1047 "common_pid, common_comm)\n\n");
1048
1049 fprintf(ofp, "\t\tprint \"");
1050
1051 not_first = 0;
1052 count = 0;
1053
1054 for (f = event->format.fields; f; f = f->next) {
1055 if (not_first++)
1056 fprintf(ofp, ", ");
1057 if (count && count % 3 == 0) {
1058 fprintf(ofp, "\" \\\n\t\t\"");
1059 }
1060 count++;
1061
1062 fprintf(ofp, "%s=", f->name);
1063 if (f->flags & FIELD_IS_STRING ||
1064 f->flags & FIELD_IS_FLAG ||
e646fe73 1065 f->flags & FIELD_IS_ARRAY ||
7e4b21b8
TZ
1066 f->flags & FIELD_IS_SYMBOLIC)
1067 fprintf(ofp, "%%s");
1068 else if (f->flags & FIELD_IS_SIGNED)
1069 fprintf(ofp, "%%d");
1070 else
1071 fprintf(ofp, "%%u");
1072 }
1073
0f5f5bcd 1074 fprintf(ofp, "\" %% \\\n\t\t(");
7e4b21b8
TZ
1075
1076 not_first = 0;
1077 count = 0;
1078
1079 for (f = event->format.fields; f; f = f->next) {
1080 if (not_first++)
1081 fprintf(ofp, ", ");
1082
1083 if (++count % 5 == 0)
1084 fprintf(ofp, "\n\t\t");
1085
1086 if (f->flags & FIELD_IS_FLAG) {
1087 if ((count - 1) % 5 != 0) {
1088 fprintf(ofp, "\n\t\t");
1089 count = 4;
1090 }
1091 fprintf(ofp, "flag_str(\"");
1092 fprintf(ofp, "%s__%s\", ", event->system,
1093 event->name);
1094 fprintf(ofp, "\"%s\", %s)", f->name,
1095 f->name);
1096 } else if (f->flags & FIELD_IS_SYMBOLIC) {
1097 if ((count - 1) % 5 != 0) {
1098 fprintf(ofp, "\n\t\t");
1099 count = 4;
1100 }
1101 fprintf(ofp, "symbol_str(\"");
1102 fprintf(ofp, "%s__%s\", ", event->system,
1103 event->name);
1104 fprintf(ofp, "\"%s\", %s)", f->name,
1105 f->name);
1106 } else
1107 fprintf(ofp, "%s", f->name);
1108 }
1109
0f5f5bcd
JS
1110 fprintf(ofp, ")\n\n");
1111
1112 fprintf(ofp, "\t\tfor node in common_callchain:");
1113 fprintf(ofp, "\n\t\t\tif 'sym' in node:");
1114 fprintf(ofp, "\n\t\t\t\tprint \"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name'])");
1115 fprintf(ofp, "\n\t\t\telse:");
1116 fprintf(ofp, "\n\t\t\t\tprint \"\t[%%x]\" %% (node['ip'])\n\n");
1117 fprintf(ofp, "\t\tprint \"\\n\"\n\n");
1118
7e4b21b8
TZ
1119 }
1120
1121 fprintf(ofp, "def trace_unhandled(event_name, context, "
c0251485 1122 "event_fields_dict):\n");
7e4b21b8 1123
c0251485
PT
1124 fprintf(ofp, "\t\tprint ' '.join(['%%s=%%s'%%(k,str(v))"
1125 "for k,v in sorted(event_fields_dict.items())])\n\n");
7e4b21b8
TZ
1126
1127 fprintf(ofp, "def print_header("
1128 "event_name, cpu, secs, nsecs, pid, comm):\n"
1129 "\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
1130 "(event_name, cpu, secs, nsecs, pid, comm),\n");
1131
1132 fclose(ofp);
1133
1134 fprintf(stderr, "generated Python script: %s\n", fname);
1135
1136 return 0;
1137}
1138
1139struct scripting_ops python_scripting_ops = {
1140 .name = "Python",
1141 .start_script = python_start_script,
d445dd2a 1142 .flush_script = python_flush_script,
7e4b21b8
TZ
1143 .stop_script = python_stop_script,
1144 .process_event = python_process_event,
1145 .generate_script = python_generate_script,
1146};