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