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