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