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