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