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 #ifdef HAVE_LIBTRACEEVENT_TEP_FIELD_IS_RELATIVE
998 				if (field->flags & TEP_FIELD_IS_RELATIVE)
999 					offset += field->offset + field->size;
1000 #endif
1001 			}
1002 			if (field->flags & TEP_FIELD_IS_STRING &&
1003 			    is_printable_array(data + offset, len)) {
1004 				obj = _PyUnicode_FromString((char *) data + offset);
1005 			} else {
1006 				obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
1007 				field->flags &= ~TEP_FIELD_IS_STRING;
1008 			}
1009 		} else { /* FIELD_IS_NUMERIC */
1010 			obj = get_field_numeric_entry(event, field, data);
1011 		}
1012 		if (!dict)
1013 			PyTuple_SetItem(t, n++, obj);
1014 		else
1015 			pydict_set_item_string_decref(dict, field->name, obj);
1016 
1017 	}
1018 
1019 	if (dict)
1020 		PyTuple_SetItem(t, n++, dict);
1021 
1022 	if (get_argument_count(handler) == (int) n + 1) {
1023 		all_entries_dict = get_perf_sample_dict(sample, evsel, al, addr_al,
1024 			callchain);
1025 		PyTuple_SetItem(t, n++,	all_entries_dict);
1026 	} else {
1027 		Py_DECREF(callchain);
1028 	}
1029 
1030 	if (_PyTuple_Resize(&t, n) == -1)
1031 		Py_FatalError("error resizing Python tuple");
1032 
1033 	if (!dict)
1034 		call_object(handler, t, handler_name);
1035 	else
1036 		call_object(handler, t, default_handler_name);
1037 
1038 	Py_DECREF(t);
1039 }
1040 
1041 static PyObject *tuple_new(unsigned int sz)
1042 {
1043 	PyObject *t;
1044 
1045 	t = PyTuple_New(sz);
1046 	if (!t)
1047 		Py_FatalError("couldn't create Python tuple");
1048 	return t;
1049 }
1050 
1051 static int tuple_set_s64(PyObject *t, unsigned int pos, s64 val)
1052 {
1053 #if BITS_PER_LONG == 64
1054 	return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
1055 #endif
1056 #if BITS_PER_LONG == 32
1057 	return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
1058 #endif
1059 }
1060 
1061 /*
1062  * Databases support only signed 64-bit numbers, so even though we are
1063  * exporting a u64, it must be as s64.
1064  */
1065 #define tuple_set_d64 tuple_set_s64
1066 
1067 static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
1068 {
1069 #if BITS_PER_LONG == 64
1070 	return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
1071 #endif
1072 #if BITS_PER_LONG == 32
1073 	return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLongLong(val));
1074 #endif
1075 }
1076 
1077 static int tuple_set_u32(PyObject *t, unsigned int pos, u32 val)
1078 {
1079 	return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
1080 }
1081 
1082 static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
1083 {
1084 	return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
1085 }
1086 
1087 static int tuple_set_bool(PyObject *t, unsigned int pos, bool val)
1088 {
1089 	return PyTuple_SetItem(t, pos, PyBool_FromLong(val));
1090 }
1091 
1092 static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
1093 {
1094 	return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
1095 }
1096 
1097 static int tuple_set_bytes(PyObject *t, unsigned int pos, void *bytes,
1098 			   unsigned int sz)
1099 {
1100 	return PyTuple_SetItem(t, pos, _PyBytes_FromStringAndSize(bytes, sz));
1101 }
1102 
1103 static int python_export_evsel(struct db_export *dbe, struct evsel *evsel)
1104 {
1105 	struct tables *tables = container_of(dbe, struct tables, dbe);
1106 	PyObject *t;
1107 
1108 	t = tuple_new(2);
1109 
1110 	tuple_set_d64(t, 0, evsel->db_id);
1111 	tuple_set_string(t, 1, evsel__name(evsel));
1112 
1113 	call_object(tables->evsel_handler, t, "evsel_table");
1114 
1115 	Py_DECREF(t);
1116 
1117 	return 0;
1118 }
1119 
1120 static int python_export_machine(struct db_export *dbe,
1121 				 struct machine *machine)
1122 {
1123 	struct tables *tables = container_of(dbe, struct tables, dbe);
1124 	PyObject *t;
1125 
1126 	t = tuple_new(3);
1127 
1128 	tuple_set_d64(t, 0, machine->db_id);
1129 	tuple_set_s32(t, 1, machine->pid);
1130 	tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
1131 
1132 	call_object(tables->machine_handler, t, "machine_table");
1133 
1134 	Py_DECREF(t);
1135 
1136 	return 0;
1137 }
1138 
1139 static int python_export_thread(struct db_export *dbe, struct thread *thread,
1140 				u64 main_thread_db_id, struct machine *machine)
1141 {
1142 	struct tables *tables = container_of(dbe, struct tables, dbe);
1143 	PyObject *t;
1144 
1145 	t = tuple_new(5);
1146 
1147 	tuple_set_d64(t, 0, thread->db_id);
1148 	tuple_set_d64(t, 1, machine->db_id);
1149 	tuple_set_d64(t, 2, main_thread_db_id);
1150 	tuple_set_s32(t, 3, thread->pid_);
1151 	tuple_set_s32(t, 4, thread->tid);
1152 
1153 	call_object(tables->thread_handler, t, "thread_table");
1154 
1155 	Py_DECREF(t);
1156 
1157 	return 0;
1158 }
1159 
1160 static int python_export_comm(struct db_export *dbe, struct comm *comm,
1161 			      struct thread *thread)
1162 {
1163 	struct tables *tables = container_of(dbe, struct tables, dbe);
1164 	PyObject *t;
1165 
1166 	t = tuple_new(5);
1167 
1168 	tuple_set_d64(t, 0, comm->db_id);
1169 	tuple_set_string(t, 1, comm__str(comm));
1170 	tuple_set_d64(t, 2, thread->db_id);
1171 	tuple_set_d64(t, 3, comm->start);
1172 	tuple_set_s32(t, 4, comm->exec);
1173 
1174 	call_object(tables->comm_handler, t, "comm_table");
1175 
1176 	Py_DECREF(t);
1177 
1178 	return 0;
1179 }
1180 
1181 static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
1182 				     struct comm *comm, struct thread *thread)
1183 {
1184 	struct tables *tables = container_of(dbe, struct tables, dbe);
1185 	PyObject *t;
1186 
1187 	t = tuple_new(3);
1188 
1189 	tuple_set_d64(t, 0, db_id);
1190 	tuple_set_d64(t, 1, comm->db_id);
1191 	tuple_set_d64(t, 2, thread->db_id);
1192 
1193 	call_object(tables->comm_thread_handler, t, "comm_thread_table");
1194 
1195 	Py_DECREF(t);
1196 
1197 	return 0;
1198 }
1199 
1200 static int python_export_dso(struct db_export *dbe, struct dso *dso,
1201 			     struct machine *machine)
1202 {
1203 	struct tables *tables = container_of(dbe, struct tables, dbe);
1204 	char sbuild_id[SBUILD_ID_SIZE];
1205 	PyObject *t;
1206 
1207 	build_id__sprintf(&dso->bid, sbuild_id);
1208 
1209 	t = tuple_new(5);
1210 
1211 	tuple_set_d64(t, 0, dso->db_id);
1212 	tuple_set_d64(t, 1, machine->db_id);
1213 	tuple_set_string(t, 2, dso->short_name);
1214 	tuple_set_string(t, 3, dso->long_name);
1215 	tuple_set_string(t, 4, sbuild_id);
1216 
1217 	call_object(tables->dso_handler, t, "dso_table");
1218 
1219 	Py_DECREF(t);
1220 
1221 	return 0;
1222 }
1223 
1224 static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
1225 				struct dso *dso)
1226 {
1227 	struct tables *tables = container_of(dbe, struct tables, dbe);
1228 	u64 *sym_db_id = symbol__priv(sym);
1229 	PyObject *t;
1230 
1231 	t = tuple_new(6);
1232 
1233 	tuple_set_d64(t, 0, *sym_db_id);
1234 	tuple_set_d64(t, 1, dso->db_id);
1235 	tuple_set_d64(t, 2, sym->start);
1236 	tuple_set_d64(t, 3, sym->end);
1237 	tuple_set_s32(t, 4, sym->binding);
1238 	tuple_set_string(t, 5, sym->name);
1239 
1240 	call_object(tables->symbol_handler, t, "symbol_table");
1241 
1242 	Py_DECREF(t);
1243 
1244 	return 0;
1245 }
1246 
1247 static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
1248 				     const char *name)
1249 {
1250 	struct tables *tables = container_of(dbe, struct tables, dbe);
1251 	PyObject *t;
1252 
1253 	t = tuple_new(2);
1254 
1255 	tuple_set_s32(t, 0, branch_type);
1256 	tuple_set_string(t, 1, name);
1257 
1258 	call_object(tables->branch_type_handler, t, "branch_type_table");
1259 
1260 	Py_DECREF(t);
1261 
1262 	return 0;
1263 }
1264 
1265 static void python_export_sample_table(struct db_export *dbe,
1266 				       struct export_sample *es)
1267 {
1268 	struct tables *tables = container_of(dbe, struct tables, dbe);
1269 	PyObject *t;
1270 
1271 	t = tuple_new(25);
1272 
1273 	tuple_set_d64(t, 0, es->db_id);
1274 	tuple_set_d64(t, 1, es->evsel->db_id);
1275 	tuple_set_d64(t, 2, es->al->maps->machine->db_id);
1276 	tuple_set_d64(t, 3, es->al->thread->db_id);
1277 	tuple_set_d64(t, 4, es->comm_db_id);
1278 	tuple_set_d64(t, 5, es->dso_db_id);
1279 	tuple_set_d64(t, 6, es->sym_db_id);
1280 	tuple_set_d64(t, 7, es->offset);
1281 	tuple_set_d64(t, 8, es->sample->ip);
1282 	tuple_set_d64(t, 9, es->sample->time);
1283 	tuple_set_s32(t, 10, es->sample->cpu);
1284 	tuple_set_d64(t, 11, es->addr_dso_db_id);
1285 	tuple_set_d64(t, 12, es->addr_sym_db_id);
1286 	tuple_set_d64(t, 13, es->addr_offset);
1287 	tuple_set_d64(t, 14, es->sample->addr);
1288 	tuple_set_d64(t, 15, es->sample->period);
1289 	tuple_set_d64(t, 16, es->sample->weight);
1290 	tuple_set_d64(t, 17, es->sample->transaction);
1291 	tuple_set_d64(t, 18, es->sample->data_src);
1292 	tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
1293 	tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
1294 	tuple_set_d64(t, 21, es->call_path_id);
1295 	tuple_set_d64(t, 22, es->sample->insn_cnt);
1296 	tuple_set_d64(t, 23, es->sample->cyc_cnt);
1297 	tuple_set_s32(t, 24, es->sample->flags);
1298 
1299 	call_object(tables->sample_handler, t, "sample_table");
1300 
1301 	Py_DECREF(t);
1302 }
1303 
1304 static void python_export_synth(struct db_export *dbe, struct export_sample *es)
1305 {
1306 	struct tables *tables = container_of(dbe, struct tables, dbe);
1307 	PyObject *t;
1308 
1309 	t = tuple_new(3);
1310 
1311 	tuple_set_d64(t, 0, es->db_id);
1312 	tuple_set_d64(t, 1, es->evsel->core.attr.config);
1313 	tuple_set_bytes(t, 2, es->sample->raw_data, es->sample->raw_size);
1314 
1315 	call_object(tables->synth_handler, t, "synth_data");
1316 
1317 	Py_DECREF(t);
1318 }
1319 
1320 static int python_export_sample(struct db_export *dbe,
1321 				struct export_sample *es)
1322 {
1323 	struct tables *tables = container_of(dbe, struct tables, dbe);
1324 
1325 	python_export_sample_table(dbe, es);
1326 
1327 	if (es->evsel->core.attr.type == PERF_TYPE_SYNTH && tables->synth_handler)
1328 		python_export_synth(dbe, es);
1329 
1330 	return 0;
1331 }
1332 
1333 static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
1334 {
1335 	struct tables *tables = container_of(dbe, struct tables, dbe);
1336 	PyObject *t;
1337 	u64 parent_db_id, sym_db_id;
1338 
1339 	parent_db_id = cp->parent ? cp->parent->db_id : 0;
1340 	sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
1341 
1342 	t = tuple_new(4);
1343 
1344 	tuple_set_d64(t, 0, cp->db_id);
1345 	tuple_set_d64(t, 1, parent_db_id);
1346 	tuple_set_d64(t, 2, sym_db_id);
1347 	tuple_set_d64(t, 3, cp->ip);
1348 
1349 	call_object(tables->call_path_handler, t, "call_path_table");
1350 
1351 	Py_DECREF(t);
1352 
1353 	return 0;
1354 }
1355 
1356 static int python_export_call_return(struct db_export *dbe,
1357 				     struct call_return *cr)
1358 {
1359 	struct tables *tables = container_of(dbe, struct tables, dbe);
1360 	u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
1361 	PyObject *t;
1362 
1363 	t = tuple_new(14);
1364 
1365 	tuple_set_d64(t, 0, cr->db_id);
1366 	tuple_set_d64(t, 1, cr->thread->db_id);
1367 	tuple_set_d64(t, 2, comm_db_id);
1368 	tuple_set_d64(t, 3, cr->cp->db_id);
1369 	tuple_set_d64(t, 4, cr->call_time);
1370 	tuple_set_d64(t, 5, cr->return_time);
1371 	tuple_set_d64(t, 6, cr->branch_count);
1372 	tuple_set_d64(t, 7, cr->call_ref);
1373 	tuple_set_d64(t, 8, cr->return_ref);
1374 	tuple_set_d64(t, 9, cr->cp->parent->db_id);
1375 	tuple_set_s32(t, 10, cr->flags);
1376 	tuple_set_d64(t, 11, cr->parent_db_id);
1377 	tuple_set_d64(t, 12, cr->insn_count);
1378 	tuple_set_d64(t, 13, cr->cyc_count);
1379 
1380 	call_object(tables->call_return_handler, t, "call_return_table");
1381 
1382 	Py_DECREF(t);
1383 
1384 	return 0;
1385 }
1386 
1387 static int python_export_context_switch(struct db_export *dbe, u64 db_id,
1388 					struct machine *machine,
1389 					struct perf_sample *sample,
1390 					u64 th_out_id, u64 comm_out_id,
1391 					u64 th_in_id, u64 comm_in_id, int flags)
1392 {
1393 	struct tables *tables = container_of(dbe, struct tables, dbe);
1394 	PyObject *t;
1395 
1396 	t = tuple_new(9);
1397 
1398 	tuple_set_d64(t, 0, db_id);
1399 	tuple_set_d64(t, 1, machine->db_id);
1400 	tuple_set_d64(t, 2, sample->time);
1401 	tuple_set_s32(t, 3, sample->cpu);
1402 	tuple_set_d64(t, 4, th_out_id);
1403 	tuple_set_d64(t, 5, comm_out_id);
1404 	tuple_set_d64(t, 6, th_in_id);
1405 	tuple_set_d64(t, 7, comm_in_id);
1406 	tuple_set_s32(t, 8, flags);
1407 
1408 	call_object(tables->context_switch_handler, t, "context_switch");
1409 
1410 	Py_DECREF(t);
1411 
1412 	return 0;
1413 }
1414 
1415 static int python_process_call_return(struct call_return *cr, u64 *parent_db_id,
1416 				      void *data)
1417 {
1418 	struct db_export *dbe = data;
1419 
1420 	return db_export__call_return(dbe, cr, parent_db_id);
1421 }
1422 
1423 static void python_process_general_event(struct perf_sample *sample,
1424 					 struct evsel *evsel,
1425 					 struct addr_location *al,
1426 					 struct addr_location *addr_al)
1427 {
1428 	PyObject *handler, *t, *dict, *callchain;
1429 	static char handler_name[64];
1430 	unsigned n = 0;
1431 
1432 	snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
1433 
1434 	handler = get_handler(handler_name);
1435 	if (!handler)
1436 		return;
1437 
1438 	/*
1439 	 * Use the MAX_FIELDS to make the function expandable, though
1440 	 * currently there is only one item for the tuple.
1441 	 */
1442 	t = PyTuple_New(MAX_FIELDS);
1443 	if (!t)
1444 		Py_FatalError("couldn't create Python tuple");
1445 
1446 	/* ip unwinding */
1447 	callchain = python_process_callchain(sample, evsel, al);
1448 	dict = get_perf_sample_dict(sample, evsel, al, addr_al, callchain);
1449 
1450 	PyTuple_SetItem(t, n++, dict);
1451 	if (_PyTuple_Resize(&t, n) == -1)
1452 		Py_FatalError("error resizing Python tuple");
1453 
1454 	call_object(handler, t, handler_name);
1455 
1456 	Py_DECREF(t);
1457 }
1458 
1459 static void python_process_event(union perf_event *event,
1460 				 struct perf_sample *sample,
1461 				 struct evsel *evsel,
1462 				 struct addr_location *al,
1463 				 struct addr_location *addr_al)
1464 {
1465 	struct tables *tables = &tables_global;
1466 
1467 	scripting_context__update(scripting_context, event, sample, evsel, al, addr_al);
1468 
1469 	switch (evsel->core.attr.type) {
1470 	case PERF_TYPE_TRACEPOINT:
1471 		python_process_tracepoint(sample, evsel, al, addr_al);
1472 		break;
1473 	/* Reserve for future process_hw/sw/raw APIs */
1474 	default:
1475 		if (tables->db_export_mode)
1476 			db_export__sample(&tables->dbe, event, sample, evsel, al, addr_al);
1477 		else
1478 			python_process_general_event(sample, evsel, al, addr_al);
1479 	}
1480 }
1481 
1482 static void python_process_throttle(union perf_event *event,
1483 				    struct perf_sample *sample,
1484 				    struct machine *machine)
1485 {
1486 	const char *handler_name;
1487 	PyObject *handler, *t;
1488 
1489 	if (event->header.type == PERF_RECORD_THROTTLE)
1490 		handler_name = "throttle";
1491 	else
1492 		handler_name = "unthrottle";
1493 	handler = get_handler(handler_name);
1494 	if (!handler)
1495 		return;
1496 
1497 	t = tuple_new(6);
1498 	if (!t)
1499 		return;
1500 
1501 	tuple_set_u64(t, 0, event->throttle.time);
1502 	tuple_set_u64(t, 1, event->throttle.id);
1503 	tuple_set_u64(t, 2, event->throttle.stream_id);
1504 	tuple_set_s32(t, 3, sample->cpu);
1505 	tuple_set_s32(t, 4, sample->pid);
1506 	tuple_set_s32(t, 5, sample->tid);
1507 
1508 	call_object(handler, t, handler_name);
1509 
1510 	Py_DECREF(t);
1511 }
1512 
1513 static void python_do_process_switch(union perf_event *event,
1514 				     struct perf_sample *sample,
1515 				     struct machine *machine)
1516 {
1517 	const char *handler_name = "context_switch";
1518 	bool out = event->header.misc & PERF_RECORD_MISC_SWITCH_OUT;
1519 	bool out_preempt = out && (event->header.misc & PERF_RECORD_MISC_SWITCH_OUT_PREEMPT);
1520 	pid_t np_pid = -1, np_tid = -1;
1521 	PyObject *handler, *t;
1522 
1523 	handler = get_handler(handler_name);
1524 	if (!handler)
1525 		return;
1526 
1527 	if (event->header.type == PERF_RECORD_SWITCH_CPU_WIDE) {
1528 		np_pid = event->context_switch.next_prev_pid;
1529 		np_tid = event->context_switch.next_prev_tid;
1530 	}
1531 
1532 	t = tuple_new(11);
1533 	if (!t)
1534 		return;
1535 
1536 	tuple_set_u64(t, 0, sample->time);
1537 	tuple_set_s32(t, 1, sample->cpu);
1538 	tuple_set_s32(t, 2, sample->pid);
1539 	tuple_set_s32(t, 3, sample->tid);
1540 	tuple_set_s32(t, 4, np_pid);
1541 	tuple_set_s32(t, 5, np_tid);
1542 	tuple_set_s32(t, 6, machine->pid);
1543 	tuple_set_bool(t, 7, out);
1544 	tuple_set_bool(t, 8, out_preempt);
1545 	tuple_set_s32(t, 9, sample->machine_pid);
1546 	tuple_set_s32(t, 10, sample->vcpu);
1547 
1548 	call_object(handler, t, handler_name);
1549 
1550 	Py_DECREF(t);
1551 }
1552 
1553 static void python_process_switch(union perf_event *event,
1554 				  struct perf_sample *sample,
1555 				  struct machine *machine)
1556 {
1557 	struct tables *tables = &tables_global;
1558 
1559 	if (tables->db_export_mode)
1560 		db_export__switch(&tables->dbe, event, sample, machine);
1561 	else
1562 		python_do_process_switch(event, sample, machine);
1563 }
1564 
1565 static void python_process_auxtrace_error(struct perf_session *session __maybe_unused,
1566 					  union perf_event *event)
1567 {
1568 	struct perf_record_auxtrace_error *e = &event->auxtrace_error;
1569 	u8 cpumode = e->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
1570 	const char *handler_name = "auxtrace_error";
1571 	unsigned long long tm = e->time;
1572 	const char *msg = e->msg;
1573 	PyObject *handler, *t;
1574 
1575 	handler = get_handler(handler_name);
1576 	if (!handler)
1577 		return;
1578 
1579 	if (!e->fmt) {
1580 		tm = 0;
1581 		msg = (const char *)&e->time;
1582 	}
1583 
1584 	t = tuple_new(11);
1585 
1586 	tuple_set_u32(t, 0, e->type);
1587 	tuple_set_u32(t, 1, e->code);
1588 	tuple_set_s32(t, 2, e->cpu);
1589 	tuple_set_s32(t, 3, e->pid);
1590 	tuple_set_s32(t, 4, e->tid);
1591 	tuple_set_u64(t, 5, e->ip);
1592 	tuple_set_u64(t, 6, tm);
1593 	tuple_set_string(t, 7, msg);
1594 	tuple_set_u32(t, 8, cpumode);
1595 	tuple_set_s32(t, 9, e->machine_pid);
1596 	tuple_set_s32(t, 10, e->vcpu);
1597 
1598 	call_object(handler, t, handler_name);
1599 
1600 	Py_DECREF(t);
1601 }
1602 
1603 static void get_handler_name(char *str, size_t size,
1604 			     struct evsel *evsel)
1605 {
1606 	char *p = str;
1607 
1608 	scnprintf(str, size, "stat__%s", evsel__name(evsel));
1609 
1610 	while ((p = strchr(p, ':'))) {
1611 		*p = '_';
1612 		p++;
1613 	}
1614 }
1615 
1616 static void
1617 process_stat(struct evsel *counter, struct perf_cpu cpu, int thread, u64 tstamp,
1618 	     struct perf_counts_values *count)
1619 {
1620 	PyObject *handler, *t;
1621 	static char handler_name[256];
1622 	int n = 0;
1623 
1624 	t = PyTuple_New(MAX_FIELDS);
1625 	if (!t)
1626 		Py_FatalError("couldn't create Python tuple");
1627 
1628 	get_handler_name(handler_name, sizeof(handler_name),
1629 			 counter);
1630 
1631 	handler = get_handler(handler_name);
1632 	if (!handler) {
1633 		pr_debug("can't find python handler %s\n", handler_name);
1634 		return;
1635 	}
1636 
1637 	PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu.cpu));
1638 	PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
1639 
1640 	tuple_set_u64(t, n++, tstamp);
1641 	tuple_set_u64(t, n++, count->val);
1642 	tuple_set_u64(t, n++, count->ena);
1643 	tuple_set_u64(t, n++, count->run);
1644 
1645 	if (_PyTuple_Resize(&t, n) == -1)
1646 		Py_FatalError("error resizing Python tuple");
1647 
1648 	call_object(handler, t, handler_name);
1649 
1650 	Py_DECREF(t);
1651 }
1652 
1653 static void python_process_stat(struct perf_stat_config *config,
1654 				struct evsel *counter, u64 tstamp)
1655 {
1656 	struct perf_thread_map *threads = counter->core.threads;
1657 	struct perf_cpu_map *cpus = counter->core.cpus;
1658 	int cpu, thread;
1659 
1660 	for (thread = 0; thread < perf_thread_map__nr(threads); thread++) {
1661 		for (cpu = 0; cpu < perf_cpu_map__nr(cpus); cpu++) {
1662 			process_stat(counter, perf_cpu_map__cpu(cpus, cpu),
1663 				     perf_thread_map__pid(threads, thread), tstamp,
1664 				     perf_counts(counter->counts, cpu, thread));
1665 		}
1666 	}
1667 }
1668 
1669 static void python_process_stat_interval(u64 tstamp)
1670 {
1671 	PyObject *handler, *t;
1672 	static const char handler_name[] = "stat__interval";
1673 	int n = 0;
1674 
1675 	t = PyTuple_New(MAX_FIELDS);
1676 	if (!t)
1677 		Py_FatalError("couldn't create Python tuple");
1678 
1679 	handler = get_handler(handler_name);
1680 	if (!handler) {
1681 		pr_debug("can't find python handler %s\n", handler_name);
1682 		return;
1683 	}
1684 
1685 	tuple_set_u64(t, n++, tstamp);
1686 
1687 	if (_PyTuple_Resize(&t, n) == -1)
1688 		Py_FatalError("error resizing Python tuple");
1689 
1690 	call_object(handler, t, handler_name);
1691 
1692 	Py_DECREF(t);
1693 }
1694 
1695 static int perf_script_context_init(void)
1696 {
1697 	PyObject *perf_script_context;
1698 	PyObject *perf_trace_context;
1699 	PyObject *dict;
1700 	int ret;
1701 
1702 	perf_trace_context = PyImport_AddModule("perf_trace_context");
1703 	if (!perf_trace_context)
1704 		return -1;
1705 	dict = PyModule_GetDict(perf_trace_context);
1706 	if (!dict)
1707 		return -1;
1708 
1709 	perf_script_context = _PyCapsule_New(scripting_context, NULL, NULL);
1710 	if (!perf_script_context)
1711 		return -1;
1712 
1713 	ret = PyDict_SetItemString(dict, "perf_script_context", perf_script_context);
1714 	if (!ret)
1715 		ret = PyDict_SetItemString(main_dict, "perf_script_context", perf_script_context);
1716 	Py_DECREF(perf_script_context);
1717 	return ret;
1718 }
1719 
1720 static int run_start_sub(void)
1721 {
1722 	main_module = PyImport_AddModule("__main__");
1723 	if (main_module == NULL)
1724 		return -1;
1725 	Py_INCREF(main_module);
1726 
1727 	main_dict = PyModule_GetDict(main_module);
1728 	if (main_dict == NULL)
1729 		goto error;
1730 	Py_INCREF(main_dict);
1731 
1732 	if (perf_script_context_init())
1733 		goto error;
1734 
1735 	try_call_object("trace_begin", NULL);
1736 
1737 	return 0;
1738 
1739 error:
1740 	Py_XDECREF(main_dict);
1741 	Py_XDECREF(main_module);
1742 	return -1;
1743 }
1744 
1745 #define SET_TABLE_HANDLER_(name, handler_name, table_name) do {		\
1746 	tables->handler_name = get_handler(#table_name);		\
1747 	if (tables->handler_name)					\
1748 		tables->dbe.export_ ## name = python_export_ ## name;	\
1749 } while (0)
1750 
1751 #define SET_TABLE_HANDLER(name) \
1752 	SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
1753 
1754 static void set_table_handlers(struct tables *tables)
1755 {
1756 	const char *perf_db_export_mode = "perf_db_export_mode";
1757 	const char *perf_db_export_calls = "perf_db_export_calls";
1758 	const char *perf_db_export_callchains = "perf_db_export_callchains";
1759 	PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
1760 	bool export_calls = false;
1761 	bool export_callchains = false;
1762 	int ret;
1763 
1764 	memset(tables, 0, sizeof(struct tables));
1765 	if (db_export__init(&tables->dbe))
1766 		Py_FatalError("failed to initialize export");
1767 
1768 	db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
1769 	if (!db_export_mode)
1770 		return;
1771 
1772 	ret = PyObject_IsTrue(db_export_mode);
1773 	if (ret == -1)
1774 		handler_call_die(perf_db_export_mode);
1775 	if (!ret)
1776 		return;
1777 
1778 	/* handle export calls */
1779 	tables->dbe.crp = NULL;
1780 	db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
1781 	if (db_export_calls) {
1782 		ret = PyObject_IsTrue(db_export_calls);
1783 		if (ret == -1)
1784 			handler_call_die(perf_db_export_calls);
1785 		export_calls = !!ret;
1786 	}
1787 
1788 	if (export_calls) {
1789 		tables->dbe.crp =
1790 			call_return_processor__new(python_process_call_return,
1791 						   &tables->dbe);
1792 		if (!tables->dbe.crp)
1793 			Py_FatalError("failed to create calls processor");
1794 	}
1795 
1796 	/* handle export callchains */
1797 	tables->dbe.cpr = NULL;
1798 	db_export_callchains = PyDict_GetItemString(main_dict,
1799 						    perf_db_export_callchains);
1800 	if (db_export_callchains) {
1801 		ret = PyObject_IsTrue(db_export_callchains);
1802 		if (ret == -1)
1803 			handler_call_die(perf_db_export_callchains);
1804 		export_callchains = !!ret;
1805 	}
1806 
1807 	if (export_callchains) {
1808 		/*
1809 		 * Attempt to use the call path root from the call return
1810 		 * processor, if the call return processor is in use. Otherwise,
1811 		 * we allocate a new call path root. This prevents exporting
1812 		 * duplicate call path ids when both are in use simultaneously.
1813 		 */
1814 		if (tables->dbe.crp)
1815 			tables->dbe.cpr = tables->dbe.crp->cpr;
1816 		else
1817 			tables->dbe.cpr = call_path_root__new();
1818 
1819 		if (!tables->dbe.cpr)
1820 			Py_FatalError("failed to create call path root");
1821 	}
1822 
1823 	tables->db_export_mode = true;
1824 	/*
1825 	 * Reserve per symbol space for symbol->db_id via symbol__priv()
1826 	 */
1827 	symbol_conf.priv_size = sizeof(u64);
1828 
1829 	SET_TABLE_HANDLER(evsel);
1830 	SET_TABLE_HANDLER(machine);
1831 	SET_TABLE_HANDLER(thread);
1832 	SET_TABLE_HANDLER(comm);
1833 	SET_TABLE_HANDLER(comm_thread);
1834 	SET_TABLE_HANDLER(dso);
1835 	SET_TABLE_HANDLER(symbol);
1836 	SET_TABLE_HANDLER(branch_type);
1837 	SET_TABLE_HANDLER(sample);
1838 	SET_TABLE_HANDLER(call_path);
1839 	SET_TABLE_HANDLER(call_return);
1840 	SET_TABLE_HANDLER(context_switch);
1841 
1842 	/*
1843 	 * Synthesized events are samples but with architecture-specific data
1844 	 * stored in sample->raw_data. They are exported via
1845 	 * python_export_sample() and consequently do not need a separate export
1846 	 * callback.
1847 	 */
1848 	tables->synth_handler = get_handler("synth_data");
1849 }
1850 
1851 #if PY_MAJOR_VERSION < 3
1852 static void _free_command_line(const char **command_line, int num)
1853 {
1854 	free(command_line);
1855 }
1856 #else
1857 static void _free_command_line(wchar_t **command_line, int num)
1858 {
1859 	int i;
1860 	for (i = 0; i < num; i++)
1861 		PyMem_RawFree(command_line[i]);
1862 	free(command_line);
1863 }
1864 #endif
1865 
1866 
1867 /*
1868  * Start trace script
1869  */
1870 static int python_start_script(const char *script, int argc, const char **argv,
1871 			       struct perf_session *session)
1872 {
1873 	struct tables *tables = &tables_global;
1874 #if PY_MAJOR_VERSION < 3
1875 	const char **command_line;
1876 #else
1877 	wchar_t **command_line;
1878 #endif
1879 	/*
1880 	 * Use a non-const name variable to cope with python 2.6's
1881 	 * PyImport_AppendInittab prototype
1882 	 */
1883 	char buf[PATH_MAX], name[19] = "perf_trace_context";
1884 	int i, err = 0;
1885 	FILE *fp;
1886 
1887 	scripting_context->session = session;
1888 #if PY_MAJOR_VERSION < 3
1889 	command_line = malloc((argc + 1) * sizeof(const char *));
1890 	command_line[0] = script;
1891 	for (i = 1; i < argc + 1; i++)
1892 		command_line[i] = argv[i - 1];
1893 	PyImport_AppendInittab(name, initperf_trace_context);
1894 #else
1895 	command_line = malloc((argc + 1) * sizeof(wchar_t *));
1896 	command_line[0] = Py_DecodeLocale(script, NULL);
1897 	for (i = 1; i < argc + 1; i++)
1898 		command_line[i] = Py_DecodeLocale(argv[i - 1], NULL);
1899 	PyImport_AppendInittab(name, PyInit_perf_trace_context);
1900 #endif
1901 	Py_Initialize();
1902 
1903 #if PY_MAJOR_VERSION < 3
1904 	PySys_SetArgv(argc + 1, (char **)command_line);
1905 #else
1906 	PySys_SetArgv(argc + 1, command_line);
1907 #endif
1908 
1909 	fp = fopen(script, "r");
1910 	if (!fp) {
1911 		sprintf(buf, "Can't open python script \"%s\"", script);
1912 		perror(buf);
1913 		err = -1;
1914 		goto error;
1915 	}
1916 
1917 	err = PyRun_SimpleFile(fp, script);
1918 	if (err) {
1919 		fprintf(stderr, "Error running python script %s\n", script);
1920 		goto error;
1921 	}
1922 
1923 	err = run_start_sub();
1924 	if (err) {
1925 		fprintf(stderr, "Error starting python script %s\n", script);
1926 		goto error;
1927 	}
1928 
1929 	set_table_handlers(tables);
1930 
1931 	if (tables->db_export_mode) {
1932 		err = db_export__branch_types(&tables->dbe);
1933 		if (err)
1934 			goto error;
1935 	}
1936 
1937 	_free_command_line(command_line, argc + 1);
1938 
1939 	return err;
1940 error:
1941 	Py_Finalize();
1942 	_free_command_line(command_line, argc + 1);
1943 
1944 	return err;
1945 }
1946 
1947 static int python_flush_script(void)
1948 {
1949 	return 0;
1950 }
1951 
1952 /*
1953  * Stop trace script
1954  */
1955 static int python_stop_script(void)
1956 {
1957 	struct tables *tables = &tables_global;
1958 
1959 	try_call_object("trace_end", NULL);
1960 
1961 	db_export__exit(&tables->dbe);
1962 
1963 	Py_XDECREF(main_dict);
1964 	Py_XDECREF(main_module);
1965 	Py_Finalize();
1966 
1967 	return 0;
1968 }
1969 
1970 static int python_generate_script(struct tep_handle *pevent, const char *outfile)
1971 {
1972 	int i, not_first, count, nr_events;
1973 	struct tep_event **all_events;
1974 	struct tep_event *event = NULL;
1975 	struct tep_format_field *f;
1976 	char fname[PATH_MAX];
1977 	FILE *ofp;
1978 
1979 	sprintf(fname, "%s.py", outfile);
1980 	ofp = fopen(fname, "w");
1981 	if (ofp == NULL) {
1982 		fprintf(stderr, "couldn't open %s\n", fname);
1983 		return -1;
1984 	}
1985 	fprintf(ofp, "# perf script event handlers, "
1986 		"generated by perf script -g python\n");
1987 
1988 	fprintf(ofp, "# Licensed under the terms of the GNU GPL"
1989 		" License version 2\n\n");
1990 
1991 	fprintf(ofp, "# The common_* event handler fields are the most useful "
1992 		"fields common to\n");
1993 
1994 	fprintf(ofp, "# all events.  They don't necessarily correspond to "
1995 		"the 'common_*' fields\n");
1996 
1997 	fprintf(ofp, "# in the format files.  Those fields not available as "
1998 		"handler params can\n");
1999 
2000 	fprintf(ofp, "# be retrieved using Python functions of the form "
2001 		"common_*(context).\n");
2002 
2003 	fprintf(ofp, "# See the perf-script-python Documentation for the list "
2004 		"of available functions.\n\n");
2005 
2006 	fprintf(ofp, "from __future__ import print_function\n\n");
2007 	fprintf(ofp, "import os\n");
2008 	fprintf(ofp, "import sys\n\n");
2009 
2010 	fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
2011 	fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
2012 	fprintf(ofp, "\nfrom perf_trace_context import *\n");
2013 	fprintf(ofp, "from Core import *\n\n\n");
2014 
2015 	fprintf(ofp, "def trace_begin():\n");
2016 	fprintf(ofp, "\tprint(\"in trace_begin\")\n\n");
2017 
2018 	fprintf(ofp, "def trace_end():\n");
2019 	fprintf(ofp, "\tprint(\"in trace_end\")\n\n");
2020 
2021 	nr_events = tep_get_events_count(pevent);
2022 	all_events = tep_list_events(pevent, TEP_EVENT_SORT_ID);
2023 
2024 	for (i = 0; all_events && i < nr_events; i++) {
2025 		event = all_events[i];
2026 		fprintf(ofp, "def %s__%s(", event->system, event->name);
2027 		fprintf(ofp, "event_name, ");
2028 		fprintf(ofp, "context, ");
2029 		fprintf(ofp, "common_cpu,\n");
2030 		fprintf(ofp, "\tcommon_secs, ");
2031 		fprintf(ofp, "common_nsecs, ");
2032 		fprintf(ofp, "common_pid, ");
2033 		fprintf(ofp, "common_comm,\n\t");
2034 		fprintf(ofp, "common_callchain, ");
2035 
2036 		not_first = 0;
2037 		count = 0;
2038 
2039 		for (f = event->format.fields; f; f = f->next) {
2040 			if (not_first++)
2041 				fprintf(ofp, ", ");
2042 			if (++count % 5 == 0)
2043 				fprintf(ofp, "\n\t");
2044 
2045 			fprintf(ofp, "%s", f->name);
2046 		}
2047 		if (not_first++)
2048 			fprintf(ofp, ", ");
2049 		if (++count % 5 == 0)
2050 			fprintf(ofp, "\n\t\t");
2051 		fprintf(ofp, "perf_sample_dict");
2052 
2053 		fprintf(ofp, "):\n");
2054 
2055 		fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
2056 			"common_secs, common_nsecs,\n\t\t\t"
2057 			"common_pid, common_comm)\n\n");
2058 
2059 		fprintf(ofp, "\t\tprint(\"");
2060 
2061 		not_first = 0;
2062 		count = 0;
2063 
2064 		for (f = event->format.fields; f; f = f->next) {
2065 			if (not_first++)
2066 				fprintf(ofp, ", ");
2067 			if (count && count % 3 == 0) {
2068 				fprintf(ofp, "\" \\\n\t\t\"");
2069 			}
2070 			count++;
2071 
2072 			fprintf(ofp, "%s=", f->name);
2073 			if (f->flags & TEP_FIELD_IS_STRING ||
2074 			    f->flags & TEP_FIELD_IS_FLAG ||
2075 			    f->flags & TEP_FIELD_IS_ARRAY ||
2076 			    f->flags & TEP_FIELD_IS_SYMBOLIC)
2077 				fprintf(ofp, "%%s");
2078 			else if (f->flags & TEP_FIELD_IS_SIGNED)
2079 				fprintf(ofp, "%%d");
2080 			else
2081 				fprintf(ofp, "%%u");
2082 		}
2083 
2084 		fprintf(ofp, "\" %% \\\n\t\t(");
2085 
2086 		not_first = 0;
2087 		count = 0;
2088 
2089 		for (f = event->format.fields; f; f = f->next) {
2090 			if (not_first++)
2091 				fprintf(ofp, ", ");
2092 
2093 			if (++count % 5 == 0)
2094 				fprintf(ofp, "\n\t\t");
2095 
2096 			if (f->flags & TEP_FIELD_IS_FLAG) {
2097 				if ((count - 1) % 5 != 0) {
2098 					fprintf(ofp, "\n\t\t");
2099 					count = 4;
2100 				}
2101 				fprintf(ofp, "flag_str(\"");
2102 				fprintf(ofp, "%s__%s\", ", event->system,
2103 					event->name);
2104 				fprintf(ofp, "\"%s\", %s)", f->name,
2105 					f->name);
2106 			} else if (f->flags & TEP_FIELD_IS_SYMBOLIC) {
2107 				if ((count - 1) % 5 != 0) {
2108 					fprintf(ofp, "\n\t\t");
2109 					count = 4;
2110 				}
2111 				fprintf(ofp, "symbol_str(\"");
2112 				fprintf(ofp, "%s__%s\", ", event->system,
2113 					event->name);
2114 				fprintf(ofp, "\"%s\", %s)", f->name,
2115 					f->name);
2116 			} else
2117 				fprintf(ofp, "%s", f->name);
2118 		}
2119 
2120 		fprintf(ofp, "))\n\n");
2121 
2122 		fprintf(ofp, "\t\tprint('Sample: {'+"
2123 			"get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
2124 
2125 		fprintf(ofp, "\t\tfor node in common_callchain:");
2126 		fprintf(ofp, "\n\t\t\tif 'sym' in node:");
2127 		fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x] %%s%%s%%s%%s\" %% (");
2128 		fprintf(ofp, "\n\t\t\t\t\tnode['ip'], node['sym']['name'],");
2129 		fprintf(ofp, "\n\t\t\t\t\t\"+0x{:x}\".format(node['sym_off']) if 'sym_off' in node else \"\",");
2130 		fprintf(ofp, "\n\t\t\t\t\t\" ({})\".format(node['dso'])  if 'dso' in node else \"\",");
2131 		fprintf(ofp, "\n\t\t\t\t\t\" \" + node['sym_srcline'] if 'sym_srcline' in node else \"\"))");
2132 		fprintf(ofp, "\n\t\t\telse:");
2133 		fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x]\" %% (node['ip']))\n\n");
2134 		fprintf(ofp, "\t\tprint()\n\n");
2135 
2136 	}
2137 
2138 	fprintf(ofp, "def trace_unhandled(event_name, context, "
2139 		"event_fields_dict, perf_sample_dict):\n");
2140 
2141 	fprintf(ofp, "\t\tprint(get_dict_as_string(event_fields_dict))\n");
2142 	fprintf(ofp, "\t\tprint('Sample: {'+"
2143 		"get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
2144 
2145 	fprintf(ofp, "def print_header("
2146 		"event_name, cpu, secs, nsecs, pid, comm):\n"
2147 		"\tprint(\"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
2148 		"(event_name, cpu, secs, nsecs, pid, comm), end=\"\")\n\n");
2149 
2150 	fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
2151 		"\treturn delimiter.join"
2152 		"(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
2153 
2154 	fclose(ofp);
2155 
2156 	fprintf(stderr, "generated Python script: %s\n", fname);
2157 
2158 	return 0;
2159 }
2160 
2161 struct scripting_ops python_scripting_ops = {
2162 	.name			= "Python",
2163 	.dirname		= "python",
2164 	.start_script		= python_start_script,
2165 	.flush_script		= python_flush_script,
2166 	.stop_script		= python_stop_script,
2167 	.process_event		= python_process_event,
2168 	.process_switch		= python_process_switch,
2169 	.process_auxtrace_error	= python_process_auxtrace_error,
2170 	.process_stat		= python_process_stat,
2171 	.process_stat_interval	= python_process_stat_interval,
2172 	.process_throttle	= python_process_throttle,
2173 	.generate_script	= python_generate_script,
2174 };
2175