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