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