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