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