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