perf script python: Add helpers for calling Python objects
[pandora-kernel.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 <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <errno.h>
28
29 #include "../../perf.h"
30 #include "../debug.h"
31 #include "../evsel.h"
32 #include "../util.h"
33 #include "../event.h"
34 #include "../thread.h"
35 #include "../trace-event.h"
36 #include "../machine.h"
37
38 PyMODINIT_FUNC initperf_trace_context(void);
39
40 #define FTRACE_MAX_EVENT                                \
41         ((1 << (sizeof(unsigned short) * 8)) - 1)
42
43 struct event_format *events[FTRACE_MAX_EVENT];
44
45 #define MAX_FIELDS      64
46 #define N_COMMON_FIELDS 7
47
48 extern struct scripting_context *scripting_context;
49
50 static char *cur_field_name;
51 static int zero_flag_atom;
52
53 static PyObject *main_module, *main_dict;
54
55 static void handler_call_die(const char *handler_name) NORETURN;
56 static void handler_call_die(const char *handler_name)
57 {
58         PyErr_Print();
59         Py_FatalError("problem in Python trace event handler");
60         // Py_FatalError does not return
61         // but we have to make the compiler happy
62         abort();
63 }
64
65 /*
66  * Insert val into into the dictionary and decrement the reference counter.
67  * This is necessary for dictionaries since PyDict_SetItemString() does not 
68  * steal a reference, as opposed to PyTuple_SetItem().
69  */
70 static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
71 {
72         PyDict_SetItemString(dict, key, val);
73         Py_DECREF(val);
74 }
75
76 static PyObject *get_handler(const char *handler_name)
77 {
78         PyObject *handler;
79
80         handler = PyDict_GetItemString(main_dict, handler_name);
81         if (handler && !PyCallable_Check(handler))
82                 return NULL;
83         return handler;
84 }
85
86 static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
87 {
88         PyObject *retval;
89
90         retval = PyObject_CallObject(handler, args);
91         if (retval == NULL)
92                 handler_call_die(die_msg);
93         Py_DECREF(retval);
94 }
95
96 static void try_call_object(const char *handler_name, PyObject *args)
97 {
98         PyObject *handler;
99
100         handler = get_handler(handler_name);
101         if (handler)
102                 call_object(handler, args, handler_name);
103 }
104
105 static void define_value(enum print_arg_type field_type,
106                          const char *ev_name,
107                          const char *field_name,
108                          const char *field_value,
109                          const char *field_str)
110 {
111         const char *handler_name = "define_flag_value";
112         PyObject *t;
113         unsigned long long value;
114         unsigned n = 0;
115
116         if (field_type == PRINT_SYMBOL)
117                 handler_name = "define_symbolic_value";
118
119         t = PyTuple_New(4);
120         if (!t)
121                 Py_FatalError("couldn't create Python tuple");
122
123         value = eval_flag(field_value);
124
125         PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
126         PyTuple_SetItem(t, n++, PyString_FromString(field_name));
127         PyTuple_SetItem(t, n++, PyInt_FromLong(value));
128         PyTuple_SetItem(t, n++, PyString_FromString(field_str));
129
130         try_call_object(handler_name, t);
131
132         Py_DECREF(t);
133 }
134
135 static void define_values(enum print_arg_type field_type,
136                           struct print_flag_sym *field,
137                           const char *ev_name,
138                           const char *field_name)
139 {
140         define_value(field_type, ev_name, field_name, field->value,
141                      field->str);
142
143         if (field->next)
144                 define_values(field_type, field->next, ev_name, field_name);
145 }
146
147 static void define_field(enum print_arg_type field_type,
148                          const char *ev_name,
149                          const char *field_name,
150                          const char *delim)
151 {
152         const char *handler_name = "define_flag_field";
153         PyObject *t;
154         unsigned n = 0;
155
156         if (field_type == PRINT_SYMBOL)
157                 handler_name = "define_symbolic_field";
158
159         if (field_type == PRINT_FLAGS)
160                 t = PyTuple_New(3);
161         else
162                 t = PyTuple_New(2);
163         if (!t)
164                 Py_FatalError("couldn't create Python tuple");
165
166         PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
167         PyTuple_SetItem(t, n++, PyString_FromString(field_name));
168         if (field_type == PRINT_FLAGS)
169                 PyTuple_SetItem(t, n++, PyString_FromString(delim));
170
171         try_call_object(handler_name, t);
172
173         Py_DECREF(t);
174 }
175
176 static void define_event_symbols(struct event_format *event,
177                                  const char *ev_name,
178                                  struct print_arg *args)
179 {
180         switch (args->type) {
181         case PRINT_NULL:
182                 break;
183         case PRINT_ATOM:
184                 define_value(PRINT_FLAGS, ev_name, cur_field_name, "0",
185                              args->atom.atom);
186                 zero_flag_atom = 0;
187                 break;
188         case PRINT_FIELD:
189                 free(cur_field_name);
190                 cur_field_name = strdup(args->field.name);
191                 break;
192         case PRINT_FLAGS:
193                 define_event_symbols(event, ev_name, args->flags.field);
194                 define_field(PRINT_FLAGS, ev_name, cur_field_name,
195                              args->flags.delim);
196                 define_values(PRINT_FLAGS, args->flags.flags, ev_name,
197                               cur_field_name);
198                 break;
199         case PRINT_SYMBOL:
200                 define_event_symbols(event, ev_name, args->symbol.field);
201                 define_field(PRINT_SYMBOL, ev_name, cur_field_name, NULL);
202                 define_values(PRINT_SYMBOL, args->symbol.symbols, ev_name,
203                               cur_field_name);
204                 break;
205         case PRINT_HEX:
206                 define_event_symbols(event, ev_name, args->hex.field);
207                 define_event_symbols(event, ev_name, args->hex.size);
208                 break;
209         case PRINT_STRING:
210                 break;
211         case PRINT_TYPE:
212                 define_event_symbols(event, ev_name, args->typecast.item);
213                 break;
214         case PRINT_OP:
215                 if (strcmp(args->op.op, ":") == 0)
216                         zero_flag_atom = 1;
217                 define_event_symbols(event, ev_name, args->op.left);
218                 define_event_symbols(event, ev_name, args->op.right);
219                 break;
220         default:
221                 /* gcc warns for these? */
222         case PRINT_BSTRING:
223         case PRINT_DYNAMIC_ARRAY:
224         case PRINT_FUNC:
225         case PRINT_BITMASK:
226                 /* we should warn... */
227                 return;
228         }
229
230         if (args->next)
231                 define_event_symbols(event, ev_name, args->next);
232 }
233
234 static inline struct event_format *find_cache_event(struct perf_evsel *evsel)
235 {
236         static char ev_name[256];
237         struct event_format *event;
238         int type = evsel->attr.config;
239
240         /*
241          * XXX: Do we really need to cache this since now we have evsel->tp_format
242          * cached already? Need to re-read this "cache" routine that as well calls
243          * define_event_symbols() :-\
244          */
245         if (events[type])
246                 return events[type];
247
248         events[type] = event = evsel->tp_format;
249         if (!event)
250                 return NULL;
251
252         sprintf(ev_name, "%s__%s", event->system, event->name);
253
254         define_event_symbols(event, ev_name, event->print_fmt.args);
255
256         return event;
257 }
258
259 static PyObject *get_field_numeric_entry(struct event_format *event,
260                 struct format_field *field, void *data)
261 {
262         bool is_array = field->flags & FIELD_IS_ARRAY;
263         PyObject *obj, *list = NULL;
264         unsigned long long val;
265         unsigned int item_size, n_items, i;
266
267         if (is_array) {
268                 list = PyList_New(field->arraylen);
269                 item_size = field->size / field->arraylen;
270                 n_items = field->arraylen;
271         } else {
272                 item_size = field->size;
273                 n_items = 1;
274         }
275
276         for (i = 0; i < n_items; i++) {
277
278                 val = read_size(event, data + field->offset + i * item_size,
279                                 item_size);
280                 if (field->flags & FIELD_IS_SIGNED) {
281                         if ((long long)val >= LONG_MIN &&
282                                         (long long)val <= LONG_MAX)
283                                 obj = PyInt_FromLong(val);
284                         else
285                                 obj = PyLong_FromLongLong(val);
286                 } else {
287                         if (val <= LONG_MAX)
288                                 obj = PyInt_FromLong(val);
289                         else
290                                 obj = PyLong_FromUnsignedLongLong(val);
291                 }
292                 if (is_array)
293                         PyList_SET_ITEM(list, i, obj);
294         }
295         if (is_array)
296                 obj = list;
297         return obj;
298 }
299
300
301 static PyObject *python_process_callchain(struct perf_sample *sample,
302                                          struct perf_evsel *evsel,
303                                          struct addr_location *al)
304 {
305         PyObject *pylist;
306
307         pylist = PyList_New(0);
308         if (!pylist)
309                 Py_FatalError("couldn't create Python list");
310
311         if (!symbol_conf.use_callchain || !sample->callchain)
312                 goto exit;
313
314         if (machine__resolve_callchain(al->machine, evsel, al->thread,
315                                            sample, NULL, NULL,
316                                            PERF_MAX_STACK_DEPTH) != 0) {
317                 pr_err("Failed to resolve callchain. Skipping\n");
318                 goto exit;
319         }
320         callchain_cursor_commit(&callchain_cursor);
321
322
323         while (1) {
324                 PyObject *pyelem;
325                 struct callchain_cursor_node *node;
326                 node = callchain_cursor_current(&callchain_cursor);
327                 if (!node)
328                         break;
329
330                 pyelem = PyDict_New();
331                 if (!pyelem)
332                         Py_FatalError("couldn't create Python dictionary");
333
334
335                 pydict_set_item_string_decref(pyelem, "ip",
336                                 PyLong_FromUnsignedLongLong(node->ip));
337
338                 if (node->sym) {
339                         PyObject *pysym  = PyDict_New();
340                         if (!pysym)
341                                 Py_FatalError("couldn't create Python dictionary");
342                         pydict_set_item_string_decref(pysym, "start",
343                                         PyLong_FromUnsignedLongLong(node->sym->start));
344                         pydict_set_item_string_decref(pysym, "end",
345                                         PyLong_FromUnsignedLongLong(node->sym->end));
346                         pydict_set_item_string_decref(pysym, "binding",
347                                         PyInt_FromLong(node->sym->binding));
348                         pydict_set_item_string_decref(pysym, "name",
349                                         PyString_FromStringAndSize(node->sym->name,
350                                                         node->sym->namelen));
351                         pydict_set_item_string_decref(pyelem, "sym", pysym);
352                 }
353
354                 if (node->map) {
355                         struct map *map = node->map;
356                         const char *dsoname = "[unknown]";
357                         if (map && map->dso && (map->dso->name || map->dso->long_name)) {
358                                 if (symbol_conf.show_kernel_path && map->dso->long_name)
359                                         dsoname = map->dso->long_name;
360                                 else if (map->dso->name)
361                                         dsoname = map->dso->name;
362                         }
363                         pydict_set_item_string_decref(pyelem, "dso",
364                                         PyString_FromString(dsoname));
365                 }
366
367                 callchain_cursor_advance(&callchain_cursor);
368                 PyList_Append(pylist, pyelem);
369                 Py_DECREF(pyelem);
370         }
371
372 exit:
373         return pylist;
374 }
375
376
377 static void python_process_tracepoint(struct perf_sample *sample,
378                                       struct perf_evsel *evsel,
379                                       struct thread *thread,
380                                       struct addr_location *al)
381 {
382         PyObject *handler, *context, *t, *obj, *callchain;
383         PyObject *dict = NULL;
384         static char handler_name[256];
385         struct format_field *field;
386         unsigned long s, ns;
387         struct event_format *event;
388         unsigned n = 0;
389         int pid;
390         int cpu = sample->cpu;
391         void *data = sample->raw_data;
392         unsigned long long nsecs = sample->time;
393         const char *comm = thread__comm_str(thread);
394
395         t = PyTuple_New(MAX_FIELDS);
396         if (!t)
397                 Py_FatalError("couldn't create Python tuple");
398
399         event = find_cache_event(evsel);
400         if (!event)
401                 die("ug! no event found for type %d", (int)evsel->attr.config);
402
403         pid = raw_field_value(event, "common_pid", data);
404
405         sprintf(handler_name, "%s__%s", event->system, event->name);
406
407         handler = get_handler(handler_name);
408         if (!handler) {
409                 dict = PyDict_New();
410                 if (!dict)
411                         Py_FatalError("couldn't create Python dict");
412         }
413         s = nsecs / NSECS_PER_SEC;
414         ns = nsecs - s * NSECS_PER_SEC;
415
416         scripting_context->event_data = data;
417         scripting_context->pevent = evsel->tp_format->pevent;
418
419         context = PyCObject_FromVoidPtr(scripting_context, NULL);
420
421         PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
422         PyTuple_SetItem(t, n++, context);
423
424         /* ip unwinding */
425         callchain = python_process_callchain(sample, evsel, al);
426
427         if (handler) {
428                 PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
429                 PyTuple_SetItem(t, n++, PyInt_FromLong(s));
430                 PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
431                 PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
432                 PyTuple_SetItem(t, n++, PyString_FromString(comm));
433                 PyTuple_SetItem(t, n++, callchain);
434         } else {
435                 pydict_set_item_string_decref(dict, "common_cpu", PyInt_FromLong(cpu));
436                 pydict_set_item_string_decref(dict, "common_s", PyInt_FromLong(s));
437                 pydict_set_item_string_decref(dict, "common_ns", PyInt_FromLong(ns));
438                 pydict_set_item_string_decref(dict, "common_pid", PyInt_FromLong(pid));
439                 pydict_set_item_string_decref(dict, "common_comm", PyString_FromString(comm));
440                 pydict_set_item_string_decref(dict, "common_callchain", callchain);
441         }
442         for (field = event->format.fields; field; field = field->next) {
443                 if (field->flags & FIELD_IS_STRING) {
444                         int offset;
445                         if (field->flags & FIELD_IS_DYNAMIC) {
446                                 offset = *(int *)(data + field->offset);
447                                 offset &= 0xffff;
448                         } else
449                                 offset = field->offset;
450                         obj = PyString_FromString((char *)data + offset);
451                 } else { /* FIELD_IS_NUMERIC */
452                         obj = get_field_numeric_entry(event, field, data);
453                 }
454                 if (handler)
455                         PyTuple_SetItem(t, n++, obj);
456                 else
457                         pydict_set_item_string_decref(dict, field->name, obj);
458
459         }
460
461         if (!handler)
462                 PyTuple_SetItem(t, n++, dict);
463
464         if (_PyTuple_Resize(&t, n) == -1)
465                 Py_FatalError("error resizing Python tuple");
466
467         if (handler) {
468                 call_object(handler, t, handler_name);
469         } else {
470                 try_call_object("trace_unhandled", t);
471                 Py_DECREF(dict);
472         }
473
474         Py_DECREF(t);
475 }
476
477 static void python_process_general_event(struct perf_sample *sample,
478                                          struct perf_evsel *evsel,
479                                          struct thread *thread,
480                                          struct addr_location *al)
481 {
482         PyObject *handler, *t, *dict, *callchain, *dict_sample;
483         static char handler_name[64];
484         unsigned n = 0;
485
486         /*
487          * Use the MAX_FIELDS to make the function expandable, though
488          * currently there is only one item for the tuple.
489          */
490         t = PyTuple_New(MAX_FIELDS);
491         if (!t)
492                 Py_FatalError("couldn't create Python tuple");
493
494         dict = PyDict_New();
495         if (!dict)
496                 Py_FatalError("couldn't create Python dictionary");
497
498         dict_sample = PyDict_New();
499         if (!dict_sample)
500                 Py_FatalError("couldn't create Python dictionary");
501
502         snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
503
504         handler = get_handler(handler_name);
505         if (!handler)
506                 goto exit;
507
508         pydict_set_item_string_decref(dict, "ev_name", PyString_FromString(perf_evsel__name(evsel)));
509         pydict_set_item_string_decref(dict, "attr", PyString_FromStringAndSize(
510                         (const char *)&evsel->attr, sizeof(evsel->attr)));
511
512         pydict_set_item_string_decref(dict_sample, "pid",
513                         PyInt_FromLong(sample->pid));
514         pydict_set_item_string_decref(dict_sample, "tid",
515                         PyInt_FromLong(sample->tid));
516         pydict_set_item_string_decref(dict_sample, "cpu",
517                         PyInt_FromLong(sample->cpu));
518         pydict_set_item_string_decref(dict_sample, "ip",
519                         PyLong_FromUnsignedLongLong(sample->ip));
520         pydict_set_item_string_decref(dict_sample, "time",
521                         PyLong_FromUnsignedLongLong(sample->time));
522         pydict_set_item_string_decref(dict_sample, "period",
523                         PyLong_FromUnsignedLongLong(sample->period));
524         pydict_set_item_string_decref(dict, "sample", dict_sample);
525
526         pydict_set_item_string_decref(dict, "raw_buf", PyString_FromStringAndSize(
527                         (const char *)sample->raw_data, sample->raw_size));
528         pydict_set_item_string_decref(dict, "comm",
529                         PyString_FromString(thread__comm_str(thread)));
530         if (al->map) {
531                 pydict_set_item_string_decref(dict, "dso",
532                         PyString_FromString(al->map->dso->name));
533         }
534         if (al->sym) {
535                 pydict_set_item_string_decref(dict, "symbol",
536                         PyString_FromString(al->sym->name));
537         }
538
539         /* ip unwinding */
540         callchain = python_process_callchain(sample, evsel, al);
541         pydict_set_item_string_decref(dict, "callchain", callchain);
542
543         PyTuple_SetItem(t, n++, dict);
544         if (_PyTuple_Resize(&t, n) == -1)
545                 Py_FatalError("error resizing Python tuple");
546
547         call_object(handler, t, handler_name);
548 exit:
549         Py_DECREF(dict);
550         Py_DECREF(t);
551 }
552
553 static void python_process_event(union perf_event *event __maybe_unused,
554                                  struct perf_sample *sample,
555                                  struct perf_evsel *evsel,
556                                  struct thread *thread,
557                                  struct addr_location *al)
558 {
559         switch (evsel->attr.type) {
560         case PERF_TYPE_TRACEPOINT:
561                 python_process_tracepoint(sample, evsel, thread, al);
562                 break;
563         /* Reserve for future process_hw/sw/raw APIs */
564         default:
565                 python_process_general_event(sample, evsel, thread, al);
566         }
567 }
568
569 static int run_start_sub(void)
570 {
571         main_module = PyImport_AddModule("__main__");
572         if (main_module == NULL)
573                 return -1;
574         Py_INCREF(main_module);
575
576         main_dict = PyModule_GetDict(main_module);
577         if (main_dict == NULL)
578                 goto error;
579         Py_INCREF(main_dict);
580
581         try_call_object("trace_begin", NULL);
582
583         return 0;
584
585 error:
586         Py_XDECREF(main_dict);
587         Py_XDECREF(main_module);
588         return -1;
589 }
590
591 /*
592  * Start trace script
593  */
594 static int python_start_script(const char *script, int argc, const char **argv)
595 {
596         const char **command_line;
597         char buf[PATH_MAX];
598         int i, err = 0;
599         FILE *fp;
600
601         command_line = malloc((argc + 1) * sizeof(const char *));
602         command_line[0] = script;
603         for (i = 1; i < argc + 1; i++)
604                 command_line[i] = argv[i - 1];
605
606         Py_Initialize();
607
608         initperf_trace_context();
609
610         PySys_SetArgv(argc + 1, (char **)command_line);
611
612         fp = fopen(script, "r");
613         if (!fp) {
614                 sprintf(buf, "Can't open python script \"%s\"", script);
615                 perror(buf);
616                 err = -1;
617                 goto error;
618         }
619
620         err = PyRun_SimpleFile(fp, script);
621         if (err) {
622                 fprintf(stderr, "Error running python script %s\n", script);
623                 goto error;
624         }
625
626         err = run_start_sub();
627         if (err) {
628                 fprintf(stderr, "Error starting python script %s\n", script);
629                 goto error;
630         }
631
632         free(command_line);
633
634         return err;
635 error:
636         Py_Finalize();
637         free(command_line);
638
639         return err;
640 }
641
642 /*
643  * Stop trace script
644  */
645 static int python_stop_script(void)
646 {
647         try_call_object("trace_end", NULL);
648
649         Py_XDECREF(main_dict);
650         Py_XDECREF(main_module);
651         Py_Finalize();
652
653         return 0;
654 }
655
656 static int python_generate_script(struct pevent *pevent, const char *outfile)
657 {
658         struct event_format *event = NULL;
659         struct format_field *f;
660         char fname[PATH_MAX];
661         int not_first, count;
662         FILE *ofp;
663
664         sprintf(fname, "%s.py", outfile);
665         ofp = fopen(fname, "w");
666         if (ofp == NULL) {
667                 fprintf(stderr, "couldn't open %s\n", fname);
668                 return -1;
669         }
670         fprintf(ofp, "# perf script event handlers, "
671                 "generated by perf script -g python\n");
672
673         fprintf(ofp, "# Licensed under the terms of the GNU GPL"
674                 " License version 2\n\n");
675
676         fprintf(ofp, "# The common_* event handler fields are the most useful "
677                 "fields common to\n");
678
679         fprintf(ofp, "# all events.  They don't necessarily correspond to "
680                 "the 'common_*' fields\n");
681
682         fprintf(ofp, "# in the format files.  Those fields not available as "
683                 "handler params can\n");
684
685         fprintf(ofp, "# be retrieved using Python functions of the form "
686                 "common_*(context).\n");
687
688         fprintf(ofp, "# See the perf-trace-python Documentation for the list "
689                 "of available functions.\n\n");
690
691         fprintf(ofp, "import os\n");
692         fprintf(ofp, "import sys\n\n");
693
694         fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
695         fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
696         fprintf(ofp, "\nfrom perf_trace_context import *\n");
697         fprintf(ofp, "from Core import *\n\n\n");
698
699         fprintf(ofp, "def trace_begin():\n");
700         fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
701
702         fprintf(ofp, "def trace_end():\n");
703         fprintf(ofp, "\tprint \"in trace_end\"\n\n");
704
705         while ((event = trace_find_next_event(pevent, event))) {
706                 fprintf(ofp, "def %s__%s(", event->system, event->name);
707                 fprintf(ofp, "event_name, ");
708                 fprintf(ofp, "context, ");
709                 fprintf(ofp, "common_cpu,\n");
710                 fprintf(ofp, "\tcommon_secs, ");
711                 fprintf(ofp, "common_nsecs, ");
712                 fprintf(ofp, "common_pid, ");
713                 fprintf(ofp, "common_comm,\n\t");
714                 fprintf(ofp, "common_callchain, ");
715
716                 not_first = 0;
717                 count = 0;
718
719                 for (f = event->format.fields; f; f = f->next) {
720                         if (not_first++)
721                                 fprintf(ofp, ", ");
722                         if (++count % 5 == 0)
723                                 fprintf(ofp, "\n\t");
724
725                         fprintf(ofp, "%s", f->name);
726                 }
727                 fprintf(ofp, "):\n");
728
729                 fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
730                         "common_secs, common_nsecs,\n\t\t\t"
731                         "common_pid, common_comm)\n\n");
732
733                 fprintf(ofp, "\t\tprint \"");
734
735                 not_first = 0;
736                 count = 0;
737
738                 for (f = event->format.fields; f; f = f->next) {
739                         if (not_first++)
740                                 fprintf(ofp, ", ");
741                         if (count && count % 3 == 0) {
742                                 fprintf(ofp, "\" \\\n\t\t\"");
743                         }
744                         count++;
745
746                         fprintf(ofp, "%s=", f->name);
747                         if (f->flags & FIELD_IS_STRING ||
748                             f->flags & FIELD_IS_FLAG ||
749                             f->flags & FIELD_IS_ARRAY ||
750                             f->flags & FIELD_IS_SYMBOLIC)
751                                 fprintf(ofp, "%%s");
752                         else if (f->flags & FIELD_IS_SIGNED)
753                                 fprintf(ofp, "%%d");
754                         else
755                                 fprintf(ofp, "%%u");
756                 }
757
758                 fprintf(ofp, "\" %% \\\n\t\t(");
759
760                 not_first = 0;
761                 count = 0;
762
763                 for (f = event->format.fields; f; f = f->next) {
764                         if (not_first++)
765                                 fprintf(ofp, ", ");
766
767                         if (++count % 5 == 0)
768                                 fprintf(ofp, "\n\t\t");
769
770                         if (f->flags & FIELD_IS_FLAG) {
771                                 if ((count - 1) % 5 != 0) {
772                                         fprintf(ofp, "\n\t\t");
773                                         count = 4;
774                                 }
775                                 fprintf(ofp, "flag_str(\"");
776                                 fprintf(ofp, "%s__%s\", ", event->system,
777                                         event->name);
778                                 fprintf(ofp, "\"%s\", %s)", f->name,
779                                         f->name);
780                         } else if (f->flags & FIELD_IS_SYMBOLIC) {
781                                 if ((count - 1) % 5 != 0) {
782                                         fprintf(ofp, "\n\t\t");
783                                         count = 4;
784                                 }
785                                 fprintf(ofp, "symbol_str(\"");
786                                 fprintf(ofp, "%s__%s\", ", event->system,
787                                         event->name);
788                                 fprintf(ofp, "\"%s\", %s)", f->name,
789                                         f->name);
790                         } else
791                                 fprintf(ofp, "%s", f->name);
792                 }
793
794                 fprintf(ofp, ")\n\n");
795
796                 fprintf(ofp, "\t\tfor node in common_callchain:");
797                 fprintf(ofp, "\n\t\t\tif 'sym' in node:");
798                 fprintf(ofp, "\n\t\t\t\tprint \"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name'])");
799                 fprintf(ofp, "\n\t\t\telse:");
800                 fprintf(ofp, "\n\t\t\t\tprint \"\t[%%x]\" %% (node['ip'])\n\n");
801                 fprintf(ofp, "\t\tprint \"\\n\"\n\n");
802
803         }
804
805         fprintf(ofp, "def trace_unhandled(event_name, context, "
806                 "event_fields_dict):\n");
807
808         fprintf(ofp, "\t\tprint ' '.join(['%%s=%%s'%%(k,str(v))"
809                 "for k,v in sorted(event_fields_dict.items())])\n\n");
810
811         fprintf(ofp, "def print_header("
812                 "event_name, cpu, secs, nsecs, pid, comm):\n"
813                 "\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
814                 "(event_name, cpu, secs, nsecs, pid, comm),\n");
815
816         fclose(ofp);
817
818         fprintf(stderr, "generated Python script: %s\n", fname);
819
820         return 0;
821 }
822
823 struct scripting_ops python_scripting_ops = {
824         .name = "Python",
825         .start_script = python_start_script,
826         .stop_script = python_stop_script,
827         .process_event = python_process_event,
828         .generate_script = python_generate_script,
829 };