]> Git Repo - linux.git/blob - tools/perf/util/scripting-engines/trace-event-python.c
perf tools: Add branch_type and in_tx to Python export
[linux.git] / tools / perf / util / scripting-engines / trace-event-python.c
1 /*
2  * trace-event-python.  Feed trace events to an embedded Python interpreter.
3  *
4  * Copyright (C) 2010 Tom Zanussi <[email protected]>
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>
27 #include <stdbool.h>
28 #include <errno.h>
29
30 #include "../../perf.h"
31 #include "../debug.h"
32 #include "../callchain.h"
33 #include "../evsel.h"
34 #include "../util.h"
35 #include "../event.h"
36 #include "../thread.h"
37 #include "../comm.h"
38 #include "../machine.h"
39 #include "../db-export.h"
40 #include "../trace-event.h"
41 #include "../machine.h"
42
43 PyMODINIT_FUNC initperf_trace_context(void);
44
45 #define FTRACE_MAX_EVENT                                \
46         ((1 << (sizeof(unsigned short) * 8)) - 1)
47
48 struct event_format *events[FTRACE_MAX_EVENT];
49
50 #define MAX_FIELDS      64
51 #define N_COMMON_FIELDS 7
52
53 extern struct scripting_context *scripting_context;
54
55 static char *cur_field_name;
56 static int zero_flag_atom;
57
58 static PyObject *main_module, *main_dict;
59
60 struct 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;
69         PyObject                *branch_type_handler;
70         PyObject                *sample_handler;
71         bool                    db_export_mode;
72 };
73
74 static struct tables tables_global;
75
76 static void handler_call_die(const char *handler_name) NORETURN;
77 static void handler_call_die(const char *handler_name)
78 {
79         PyErr_Print();
80         Py_FatalError("problem in Python trace event handler");
81         // Py_FatalError does not return
82         // but we have to make the compiler happy
83         abort();
84 }
85
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  */
91 static 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
97 static 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
107 static 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
117 static 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
126 static 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";
133         PyObject *t;
134         unsigned long long value;
135         unsigned n = 0;
136
137         if (field_type == PRINT_SYMBOL)
138                 handler_name = "define_symbolic_value";
139
140         t = PyTuple_New(4);
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
151         try_call_object(handler_name, t);
152
153         Py_DECREF(t);
154 }
155
156 static 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
168 static 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";
174         PyObject *t;
175         unsigned n = 0;
176
177         if (field_type == PRINT_SYMBOL)
178                 handler_name = "define_symbolic_field";
179
180         if (field_type == PRINT_FLAGS)
181                 t = PyTuple_New(3);
182         else
183                 t = PyTuple_New(2);
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
192         try_call_object(handler_name, t);
193
194         Py_DECREF(t);
195 }
196
197 static void define_event_symbols(struct event_format *event,
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:
210                 free(cur_field_name);
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;
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;
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:
242                 /* gcc warns for these? */
243         case PRINT_BSTRING:
244         case PRINT_DYNAMIC_ARRAY:
245         case PRINT_FUNC:
246         case PRINT_BITMASK:
247                 /* we should warn... */
248                 return;
249         }
250
251         if (args->next)
252                 define_event_symbols(event, ev_name, args->next);
253 }
254
255 static inline struct event_format *find_cache_event(struct perf_evsel *evsel)
256 {
257         static char ev_name[256];
258         struct event_format *event;
259         int type = evsel->attr.config;
260
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          */
266         if (events[type])
267                 return events[type];
268
269         events[type] = event = evsel->tp_format;
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
280 static PyObject *get_field_numeric_entry(struct event_format *event,
281                 struct format_field *field, void *data)
282 {
283         bool is_array = field->flags & FIELD_IS_ARRAY;
284         PyObject *obj, *list = NULL;
285         unsigned long long val;
286         unsigned int item_size, n_items, i;
287
288         if (is_array) {
289                 list = PyList_New(field->arraylen);
290                 item_size = field->size / field->arraylen;
291                 n_items = field->arraylen;
292         } else {
293                 item_size = field->size;
294                 n_items = 1;
295         }
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;
318         return obj;
319 }
320
321
322 static 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
335         if (thread__resolve_callchain(al->thread, evsel,
336                                       sample, NULL, NULL,
337                                       PERF_MAX_STACK_DEPTH) != 0) {
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
393 exit:
394         return pylist;
395 }
396
397
398 static void python_process_tracepoint(struct perf_sample *sample,
399                                       struct perf_evsel *evsel,
400                                       struct thread *thread,
401                                       struct addr_location *al)
402 {
403         PyObject *handler, *context, *t, *obj, *callchain;
404         PyObject *dict = NULL;
405         static char handler_name[256];
406         struct format_field *field;
407         unsigned long s, ns;
408         struct event_format *event;
409         unsigned n = 0;
410         int pid;
411         int cpu = sample->cpu;
412         void *data = sample->raw_data;
413         unsigned long long nsecs = sample->time;
414         const char *comm = thread__comm_str(thread);
415
416         t = PyTuple_New(MAX_FIELDS);
417         if (!t)
418                 Py_FatalError("couldn't create Python tuple");
419
420         event = find_cache_event(evsel);
421         if (!event)
422                 die("ug! no event found for type %d", (int)evsel->attr.config);
423
424         pid = raw_field_value(event, "common_pid", data);
425
426         sprintf(handler_name, "%s__%s", event->system, event->name);
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 / NSECS_PER_SEC;
435         ns = nsecs - s * NSECS_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                 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;
471                         obj = PyString_FromString((char *)data + offset);
472                 } else { /* FIELD_IS_NUMERIC */
473                         obj = get_field_numeric_entry(event, field, data);
474                 }
475                 if (handler)
476                         PyTuple_SetItem(t, n++, obj);
477                 else
478                         pydict_set_item_string_decref(dict, field->name, obj);
479
480         }
481
482         if (!handler)
483                 PyTuple_SetItem(t, n++, dict);
484
485         if (_PyTuple_Resize(&t, n) == -1)
486                 Py_FatalError("error resizing Python tuple");
487
488         if (handler) {
489                 call_object(handler, t, handler_name);
490         } else {
491                 try_call_object("trace_unhandled", t);
492                 Py_DECREF(dict);
493         }
494
495         Py_DECREF(t);
496 }
497
498 static 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
508 static 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
518 static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
519 {
520         return PyTuple_SetItem(t, pos, PyInt_FromLong(val));
521 }
522
523 static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
524 {
525         return PyTuple_SetItem(t, pos, PyString_FromString(s));
526 }
527
528 static 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
545 static 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
564 static 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
585 static 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
602 static 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
621 static 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
645 static 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
668 static 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
686 static 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
692         t = tuple_new(21);
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);
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));
715
716         call_object(tables->sample_handler, t, "sample_table");
717
718         Py_DECREF(t);
719
720         return 0;
721 }
722
723 static void python_process_general_event(struct perf_sample *sample,
724                                          struct perf_evsel *evsel,
725                                          struct thread *thread,
726                                          struct addr_location *al)
727 {
728         PyObject *handler, *t, *dict, *callchain, *dict_sample;
729         static char handler_name[64];
730         unsigned n = 0;
731
732         /*
733          * Use the MAX_FIELDS to make the function expandable, though
734          * currently there is only one item for the tuple.
735          */
736         t = PyTuple_New(MAX_FIELDS);
737         if (!t)
738                 Py_FatalError("couldn't create Python tuple");
739
740         dict = PyDict_New();
741         if (!dict)
742                 Py_FatalError("couldn't create Python dictionary");
743
744         dict_sample = PyDict_New();
745         if (!dict_sample)
746                 Py_FatalError("couldn't create Python dictionary");
747
748         snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
749
750         handler = get_handler(handler_name);
751         if (!handler)
752                 goto exit;
753
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(
756                         (const char *)&evsel->attr, sizeof(evsel->attr)));
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
772         pydict_set_item_string_decref(dict, "raw_buf", PyString_FromStringAndSize(
773                         (const char *)sample->raw_data, sample->raw_size));
774         pydict_set_item_string_decref(dict, "comm",
775                         PyString_FromString(thread__comm_str(thread)));
776         if (al->map) {
777                 pydict_set_item_string_decref(dict, "dso",
778                         PyString_FromString(al->map->dso->name));
779         }
780         if (al->sym) {
781                 pydict_set_item_string_decref(dict, "symbol",
782                         PyString_FromString(al->sym->name));
783         }
784
785         /* ip unwinding */
786         callchain = python_process_callchain(sample, evsel, al);
787         pydict_set_item_string_decref(dict, "callchain", callchain);
788
789         PyTuple_SetItem(t, n++, dict);
790         if (_PyTuple_Resize(&t, n) == -1)
791                 Py_FatalError("error resizing Python tuple");
792
793         call_object(handler, t, handler_name);
794 exit:
795         Py_DECREF(dict);
796         Py_DECREF(t);
797 }
798
799 static void python_process_event(union perf_event *event,
800                                  struct perf_sample *sample,
801                                  struct perf_evsel *evsel,
802                                  struct thread *thread,
803                                  struct addr_location *al)
804 {
805         struct tables *tables = &tables_global;
806
807         switch (evsel->attr.type) {
808         case PERF_TYPE_TRACEPOINT:
809                 python_process_tracepoint(sample, evsel, thread, al);
810                 break;
811         /* Reserve for future process_hw/sw/raw APIs */
812         default:
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);
818         }
819 }
820
821 static int run_start_sub(void)
822 {
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);
829         if (main_dict == NULL)
830                 goto error;
831         Py_INCREF(main_dict);
832
833         try_call_object("trace_begin", NULL);
834
835         return 0;
836
837 error:
838         Py_XDECREF(main_dict);
839         Py_XDECREF(main_module);
840         return -1;
841 }
842
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
852 static 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);
885         SET_TABLE_HANDLER(branch_type);
886         SET_TABLE_HANDLER(sample);
887 }
888
889 /*
890  * Start trace script
891  */
892 static int python_start_script(const char *script, int argc, const char **argv)
893 {
894         struct tables *tables = &tables_global;
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);
932
933         set_table_handlers(tables);
934
935         if (tables->db_export_mode) {
936                 err = db_export__branch_types(&tables->dbe);
937                 if (err)
938                         goto error;
939         }
940
941         return err;
942 error:
943         Py_Finalize();
944         free(command_line);
945
946         return err;
947 }
948
949 static int python_flush_script(void)
950 {
951         return 0;
952 }
953
954 /*
955  * Stop trace script
956  */
957 static int python_stop_script(void)
958 {
959         struct tables *tables = &tables_global;
960
961         try_call_object("trace_end", NULL);
962
963         db_export__exit(&tables->dbe);
964
965         Py_XDECREF(main_dict);
966         Py_XDECREF(main_module);
967         Py_Finalize();
968
969         return 0;
970 }
971
972 static int python_generate_script(struct pevent *pevent, const char *outfile)
973 {
974         struct event_format *event = NULL;
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         }
986         fprintf(ofp, "# perf script event handlers, "
987                 "generated by perf script -g python\n");
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
1021         while ((event = trace_find_next_event(pevent, event))) {
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");
1030                 fprintf(ofp, "common_callchain, ");
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 ||
1065                             f->flags & FIELD_IS_ARRAY ||
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
1074                 fprintf(ofp, "\" %% \\\n\t\t(");
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
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
1119         }
1120
1121         fprintf(ofp, "def trace_unhandled(event_name, context, "
1122                 "event_fields_dict):\n");
1123
1124         fprintf(ofp, "\t\tprint ' '.join(['%%s=%%s'%%(k,str(v))"
1125                 "for k,v in sorted(event_fields_dict.items())])\n\n");
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
1139 struct scripting_ops python_scripting_ops = {
1140         .name = "Python",
1141         .start_script = python_start_script,
1142         .flush_script = python_flush_script,
1143         .stop_script = python_stop_script,
1144         .process_event = python_process_event,
1145         .generate_script = python_generate_script,
1146 };
This page took 0.104423 seconds and 4 git commands to generate.