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