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