xref: /linux/tools/perf/util/scripting-engines/trace-event-python.c (revision ceea279f93760767c0e654341829334a1c881a08)
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, uint32_t e_flags,
718 		     char *bf, int size)
719 {
720 	unsigned int i = 0, r;
721 	int printed = 0;
722 
723 	bf[0] = 0;
724 
725 	if (size <= 0)
726 		return;
727 
728 	if (!regs || !regs->regs)
729 		return;
730 
731 	for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
732 		u64 val = regs->regs[i++];
733 
734 		printed += scnprintf(bf + printed, size - printed,
735 				     "%5s:0x%" PRIx64 " ",
736 				     perf_reg_name(r, e_machine, e_flags), val);
737 	}
738 }
739 
740 #define MAX_REG_SIZE 128
741 
742 static int set_regs_in_dict(PyObject *dict,
743 			     struct perf_sample *sample,
744 			     struct evsel *evsel,
745 			     uint16_t e_machine,
746 			     uint32_t e_flags)
747 {
748 	struct perf_event_attr *attr = &evsel->core.attr;
749 
750 	int size = (__sw_hweight64(attr->sample_regs_intr) * MAX_REG_SIZE) + 1;
751 	char *bf = NULL;
752 
753 	if (sample->intr_regs) {
754 		bf = malloc(size);
755 		if (!bf)
756 			return -1;
757 
758 		regs_map(sample->intr_regs, attr->sample_regs_intr, e_machine, e_flags, bf, size);
759 
760 		pydict_set_item_string_decref(dict, "iregs",
761 					_PyUnicode_FromString(bf));
762 	}
763 
764 	if (sample->user_regs) {
765 		if (!bf) {
766 			bf = malloc(size);
767 			if (!bf)
768 				return -1;
769 		}
770 		regs_map(sample->user_regs, attr->sample_regs_user, e_machine, e_flags, bf, size);
771 
772 		pydict_set_item_string_decref(dict, "uregs",
773 					_PyUnicode_FromString(bf));
774 	}
775 	free(bf);
776 
777 	return 0;
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 			    const char *map_pgoff)
785 {
786 	if (al->map) {
787 		char sbuild_id[SBUILD_ID_SIZE];
788 		struct dso *dso = map__dso(al->map);
789 
790 		pydict_set_item_string_decref(dict, dso_field,
791 					      _PyUnicode_FromString(dso__name(dso)));
792 		build_id__snprintf(dso__bid(dso), sbuild_id, sizeof(sbuild_id));
793 		pydict_set_item_string_decref(dict, dso_bid_field,
794 			_PyUnicode_FromString(sbuild_id));
795 		pydict_set_item_string_decref(dict, dso_map_start,
796 			PyLong_FromUnsignedLong(map__start(al->map)));
797 		pydict_set_item_string_decref(dict, dso_map_end,
798 			PyLong_FromUnsignedLong(map__end(al->map)));
799 		pydict_set_item_string_decref(dict, map_pgoff,
800 			PyLong_FromUnsignedLongLong(map__pgoff(al->map)));
801 	}
802 	if (al->sym) {
803 		pydict_set_item_string_decref(dict, sym_field,
804 			_PyUnicode_FromString(al->sym->name));
805 		pydict_set_item_string_decref(dict, symoff_field,
806 			PyLong_FromUnsignedLong(get_offset(al->sym, al)));
807 	}
808 }
809 
810 static void set_sample_flags(PyObject *dict, u32 flags)
811 {
812 	const char *ch = PERF_IP_FLAG_CHARS;
813 	char *p, str[33];
814 
815 	for (p = str; *ch; ch++, flags >>= 1) {
816 		if (flags & 1)
817 			*p++ = *ch;
818 	}
819 	*p = 0;
820 	pydict_set_item_string_decref(dict, "flags", _PyUnicode_FromString(str));
821 }
822 
823 static void python_process_sample_flags(struct perf_sample *sample, PyObject *dict_sample)
824 {
825 	char flags_disp[SAMPLE_FLAGS_BUF_SIZE];
826 
827 	set_sample_flags(dict_sample, sample->flags);
828 	perf_sample__sprintf_flags(sample->flags, flags_disp, sizeof(flags_disp));
829 	pydict_set_item_string_decref(dict_sample, "flags_disp",
830 		_PyUnicode_FromString(flags_disp));
831 }
832 
833 static PyObject *get_perf_sample_dict(struct perf_sample *sample,
834 					 struct evsel *evsel,
835 					 struct addr_location *al,
836 					 struct addr_location *addr_al,
837 					 PyObject *callchain)
838 {
839 	PyObject *dict, *dict_sample, *brstack, *brstacksym;
840 	struct machine *machine;
841 	uint16_t e_machine = EM_HOST;
842 	uint32_t e_flags = EF_HOST;
843 
844 	dict = PyDict_New();
845 	if (!dict)
846 		Py_FatalError("couldn't create Python dictionary");
847 
848 	dict_sample = PyDict_New();
849 	if (!dict_sample)
850 		Py_FatalError("couldn't create Python dictionary");
851 
852 	pydict_set_item_string_decref(dict, "ev_name", _PyUnicode_FromString(evsel__name(evsel)));
853 	pydict_set_item_string_decref(dict, "attr", _PyBytes_FromStringAndSize((const char *)&evsel->core.attr, sizeof(evsel->core.attr)));
854 
855 	pydict_set_item_string_decref(dict_sample, "id",
856 			PyLong_FromUnsignedLongLong(sample->id));
857 	pydict_set_item_string_decref(dict_sample, "stream_id",
858 			PyLong_FromUnsignedLongLong(sample->stream_id));
859 	pydict_set_item_string_decref(dict_sample, "pid",
860 			_PyLong_FromLong(sample->pid));
861 	pydict_set_item_string_decref(dict_sample, "tid",
862 			_PyLong_FromLong(sample->tid));
863 	pydict_set_item_string_decref(dict_sample, "cpu",
864 			_PyLong_FromLong(sample->cpu));
865 	pydict_set_item_string_decref(dict_sample, "ip",
866 			PyLong_FromUnsignedLongLong(sample->ip));
867 	pydict_set_item_string_decref(dict_sample, "time",
868 			PyLong_FromUnsignedLongLong(sample->time));
869 	pydict_set_item_string_decref(dict_sample, "period",
870 			PyLong_FromUnsignedLongLong(sample->period));
871 	pydict_set_item_string_decref(dict_sample, "phys_addr",
872 			PyLong_FromUnsignedLongLong(sample->phys_addr));
873 	pydict_set_item_string_decref(dict_sample, "addr",
874 			PyLong_FromUnsignedLongLong(sample->addr));
875 	set_sample_read_in_dict(dict_sample, sample, evsel);
876 	pydict_set_item_string_decref(dict_sample, "weight",
877 			PyLong_FromUnsignedLongLong(sample->weight));
878 	pydict_set_item_string_decref(dict_sample, "ins_lat",
879 			PyLong_FromUnsignedLong(sample->ins_lat));
880 	pydict_set_item_string_decref(dict_sample, "transaction",
881 			PyLong_FromUnsignedLongLong(sample->transaction));
882 	set_sample_datasrc_in_dict(dict_sample, sample);
883 	pydict_set_item_string_decref(dict, "sample", dict_sample);
884 
885 	pydict_set_item_string_decref(dict, "raw_buf", _PyBytes_FromStringAndSize(
886 			(const char *)sample->raw_data, sample->raw_size));
887 	pydict_set_item_string_decref(dict, "comm",
888 			_PyUnicode_FromString(thread__comm_str(al->thread)));
889 	set_sym_in_dict(dict, al, "dso", "dso_bid", "dso_map_start", "dso_map_end",
890 			"symbol", "symoff", "map_pgoff");
891 
892 	pydict_set_item_string_decref(dict, "callchain", callchain);
893 
894 	brstack = python_process_brstack(sample, al->thread);
895 	pydict_set_item_string_decref(dict, "brstack", brstack);
896 
897 	brstacksym = python_process_brstacksym(sample, al->thread);
898 	pydict_set_item_string_decref(dict, "brstacksym", brstacksym);
899 
900 	if (sample->machine_pid) {
901 		pydict_set_item_string_decref(dict_sample, "machine_pid",
902 				_PyLong_FromLong(sample->machine_pid));
903 		pydict_set_item_string_decref(dict_sample, "vcpu",
904 				_PyLong_FromLong(sample->vcpu));
905 	}
906 
907 	pydict_set_item_string_decref(dict_sample, "cpumode",
908 			_PyLong_FromLong((unsigned long)sample->cpumode));
909 
910 	if (addr_al) {
911 		pydict_set_item_string_decref(dict_sample, "addr_correlates_sym",
912 			PyBool_FromLong(1));
913 		set_sym_in_dict(dict_sample, addr_al, "addr_dso", "addr_dso_bid",
914 				"addr_dso_map_start", "addr_dso_map_end",
915 				"addr_symbol", "addr_symoff", "addr_map_pgoff");
916 	}
917 
918 	if (sample->flags)
919 		python_process_sample_flags(sample, dict_sample);
920 
921 	/* Instructions per cycle (IPC) */
922 	if (sample->insn_cnt && sample->cyc_cnt) {
923 		pydict_set_item_string_decref(dict_sample, "insn_cnt",
924 			PyLong_FromUnsignedLongLong(sample->insn_cnt));
925 		pydict_set_item_string_decref(dict_sample, "cyc_cnt",
926 			PyLong_FromUnsignedLongLong(sample->cyc_cnt));
927 	}
928 
929 	if (al->thread) {
930 		machine = maps__machine(thread__maps(al->thread));
931 		e_machine = thread__e_machine(al->thread, machine, &e_flags);
932 	}
933 	if (set_regs_in_dict(dict, sample, evsel, e_machine, e_flags))
934 		Py_FatalError("Failed to setting regs in dict");
935 
936 	return dict;
937 }
938 
939 #ifdef HAVE_LIBTRACEEVENT
940 static void python_process_tracepoint(struct perf_sample *sample,
941 				      struct evsel *evsel,
942 				      struct addr_location *al,
943 				      struct addr_location *addr_al)
944 {
945 	struct tep_event *event;
946 	PyObject *handler, *context, *t, *obj = NULL, *callchain;
947 	PyObject *dict = NULL, *all_entries_dict = NULL;
948 	static char handler_name[256];
949 	struct tep_format_field *field;
950 	unsigned long s, ns;
951 	unsigned n = 0;
952 	int pid;
953 	int cpu = sample->cpu;
954 	void *data = sample->raw_data;
955 	unsigned long long nsecs = sample->time;
956 	const char *comm = thread__comm_str(al->thread);
957 	const char *default_handler_name = "trace_unhandled";
958 	DECLARE_BITMAP(events_defined, TRACE_EVENT_TYPE_MAX);
959 
960 	bitmap_zero(events_defined, TRACE_EVENT_TYPE_MAX);
961 
962 	event = evsel__tp_format(evsel);
963 	if (!event) {
964 		snprintf(handler_name, sizeof(handler_name),
965 			 "ug! no event found for type %" PRIu64, (u64)evsel->core.attr.config);
966 		Py_FatalError(handler_name);
967 	}
968 
969 	pid = raw_field_value(event, "common_pid", data);
970 
971 	sprintf(handler_name, "%s__%s", event->system, event->name);
972 
973 	if (!__test_and_set_bit(event->id, events_defined))
974 		define_event_symbols(event, handler_name, event->print_fmt.args);
975 
976 	handler = get_handler(handler_name);
977 	if (!handler) {
978 		handler = get_handler(default_handler_name);
979 		if (!handler)
980 			return;
981 		dict = PyDict_New();
982 		if (!dict)
983 			Py_FatalError("couldn't create Python dict");
984 	}
985 
986 	t = PyTuple_New(MAX_FIELDS);
987 	if (!t)
988 		Py_FatalError("couldn't create Python tuple");
989 
990 
991 	s = nsecs / NSEC_PER_SEC;
992 	ns = nsecs - s * NSEC_PER_SEC;
993 
994 	context = _PyCapsule_New(scripting_context, NULL, NULL);
995 
996 	PyTuple_SetItem(t, n++, _PyUnicode_FromString(handler_name));
997 	PyTuple_SetItem(t, n++, context);
998 
999 	/* ip unwinding */
1000 	callchain = python_process_callchain(sample, evsel, al);
1001 	/* Need an additional reference for the perf_sample dict */
1002 	Py_INCREF(callchain);
1003 
1004 	if (!dict) {
1005 		PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
1006 		PyTuple_SetItem(t, n++, _PyLong_FromLong(s));
1007 		PyTuple_SetItem(t, n++, _PyLong_FromLong(ns));
1008 		PyTuple_SetItem(t, n++, _PyLong_FromLong(pid));
1009 		PyTuple_SetItem(t, n++, _PyUnicode_FromString(comm));
1010 		PyTuple_SetItem(t, n++, callchain);
1011 	} else {
1012 		pydict_set_item_string_decref(dict, "common_cpu", _PyLong_FromLong(cpu));
1013 		pydict_set_item_string_decref(dict, "common_s", _PyLong_FromLong(s));
1014 		pydict_set_item_string_decref(dict, "common_ns", _PyLong_FromLong(ns));
1015 		pydict_set_item_string_decref(dict, "common_pid", _PyLong_FromLong(pid));
1016 		pydict_set_item_string_decref(dict, "common_comm", _PyUnicode_FromString(comm));
1017 		pydict_set_item_string_decref(dict, "common_callchain", callchain);
1018 	}
1019 	for (field = event->format.fields; field; field = field->next) {
1020 		unsigned int offset, len;
1021 		unsigned long long val;
1022 
1023 		if (field->flags & TEP_FIELD_IS_ARRAY) {
1024 			offset = field->offset;
1025 			len    = field->size;
1026 			if (field->flags & TEP_FIELD_IS_DYNAMIC) {
1027 				val     = tep_read_number(scripting_context->pevent,
1028 							  data + offset, len);
1029 				offset  = val;
1030 				len     = offset >> 16;
1031 				offset &= 0xffff;
1032 				if (tep_field_is_relative(field->flags))
1033 					offset += field->offset + field->size;
1034 			}
1035 			if (field->flags & TEP_FIELD_IS_STRING &&
1036 			    is_printable_array(data + offset, len)) {
1037 				obj = _PyUnicode_FromString((char *) data + offset);
1038 			} else {
1039 				obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
1040 				field->flags &= ~TEP_FIELD_IS_STRING;
1041 			}
1042 		} else { /* FIELD_IS_NUMERIC */
1043 			obj = get_field_numeric_entry(event, field, data);
1044 		}
1045 		if (!dict)
1046 			PyTuple_SetItem(t, n++, obj);
1047 		else
1048 			pydict_set_item_string_decref(dict, field->name, obj);
1049 
1050 	}
1051 
1052 	if (dict)
1053 		PyTuple_SetItem(t, n++, dict);
1054 
1055 	if (get_argument_count(handler) == (int) n + 1) {
1056 		all_entries_dict = get_perf_sample_dict(sample, evsel, al, addr_al,
1057 			callchain);
1058 		PyTuple_SetItem(t, n++,	all_entries_dict);
1059 	} else {
1060 		Py_DECREF(callchain);
1061 	}
1062 
1063 	if (_PyTuple_Resize(&t, n) == -1)
1064 		Py_FatalError("error resizing Python tuple");
1065 
1066 	if (!dict)
1067 		call_object(handler, t, handler_name);
1068 	else
1069 		call_object(handler, t, default_handler_name);
1070 
1071 	Py_DECREF(t);
1072 }
1073 #else
1074 static void python_process_tracepoint(struct perf_sample *sample __maybe_unused,
1075 				      struct evsel *evsel __maybe_unused,
1076 				      struct addr_location *al __maybe_unused,
1077 				      struct addr_location *addr_al __maybe_unused)
1078 {
1079 	fprintf(stderr, "Tracepoint events are not supported because "
1080 			"perf is not linked with libtraceevent.\n");
1081 }
1082 #endif
1083 
1084 static PyObject *tuple_new(unsigned int sz)
1085 {
1086 	PyObject *t;
1087 
1088 	t = PyTuple_New(sz);
1089 	if (!t)
1090 		Py_FatalError("couldn't create Python tuple");
1091 	return t;
1092 }
1093 
1094 static int tuple_set_s64(PyObject *t, unsigned int pos, s64 val)
1095 {
1096 #if BITS_PER_LONG == 64
1097 	return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
1098 #endif
1099 #if BITS_PER_LONG == 32
1100 	return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
1101 #endif
1102 }
1103 
1104 /*
1105  * Databases support only signed 64-bit numbers, so even though we are
1106  * exporting a u64, it must be as s64.
1107  */
1108 #define tuple_set_d64 tuple_set_s64
1109 
1110 static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
1111 {
1112 #if BITS_PER_LONG == 64
1113 	return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
1114 #endif
1115 #if BITS_PER_LONG == 32
1116 	return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLongLong(val));
1117 #endif
1118 }
1119 
1120 static int tuple_set_u32(PyObject *t, unsigned int pos, u32 val)
1121 {
1122 	return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
1123 }
1124 
1125 static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
1126 {
1127 	return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
1128 }
1129 
1130 static int tuple_set_bool(PyObject *t, unsigned int pos, bool val)
1131 {
1132 	return PyTuple_SetItem(t, pos, PyBool_FromLong(val));
1133 }
1134 
1135 static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
1136 {
1137 	return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
1138 }
1139 
1140 static int tuple_set_bytes(PyObject *t, unsigned int pos, void *bytes,
1141 			   unsigned int sz)
1142 {
1143 	return PyTuple_SetItem(t, pos, _PyBytes_FromStringAndSize(bytes, sz));
1144 }
1145 
1146 static int python_export_evsel(struct db_export *dbe, struct evsel *evsel)
1147 {
1148 	struct tables *tables = container_of(dbe, struct tables, dbe);
1149 	PyObject *t;
1150 
1151 	t = tuple_new(2);
1152 
1153 	tuple_set_d64(t, 0, evsel->db_id);
1154 	tuple_set_string(t, 1, evsel__name(evsel));
1155 
1156 	call_object(tables->evsel_handler, t, "evsel_table");
1157 
1158 	Py_DECREF(t);
1159 
1160 	return 0;
1161 }
1162 
1163 static int python_export_machine(struct db_export *dbe,
1164 				 struct machine *machine)
1165 {
1166 	struct tables *tables = container_of(dbe, struct tables, dbe);
1167 	PyObject *t;
1168 
1169 	t = tuple_new(3);
1170 
1171 	tuple_set_d64(t, 0, machine->db_id);
1172 	tuple_set_s32(t, 1, machine->pid);
1173 	tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
1174 
1175 	call_object(tables->machine_handler, t, "machine_table");
1176 
1177 	Py_DECREF(t);
1178 
1179 	return 0;
1180 }
1181 
1182 static int python_export_thread(struct db_export *dbe, struct thread *thread,
1183 				u64 main_thread_db_id, struct machine *machine)
1184 {
1185 	struct tables *tables = container_of(dbe, struct tables, dbe);
1186 	PyObject *t;
1187 
1188 	t = tuple_new(5);
1189 
1190 	tuple_set_d64(t, 0, thread__db_id(thread));
1191 	tuple_set_d64(t, 1, machine->db_id);
1192 	tuple_set_d64(t, 2, main_thread_db_id);
1193 	tuple_set_s32(t, 3, thread__pid(thread));
1194 	tuple_set_s32(t, 4, thread__tid(thread));
1195 
1196 	call_object(tables->thread_handler, t, "thread_table");
1197 
1198 	Py_DECREF(t);
1199 
1200 	return 0;
1201 }
1202 
1203 static int python_export_comm(struct db_export *dbe, struct comm *comm,
1204 			      struct thread *thread)
1205 {
1206 	struct tables *tables = container_of(dbe, struct tables, dbe);
1207 	PyObject *t;
1208 
1209 	t = tuple_new(5);
1210 
1211 	tuple_set_d64(t, 0, comm->db_id);
1212 	tuple_set_string(t, 1, comm__str(comm));
1213 	tuple_set_d64(t, 2, thread__db_id(thread));
1214 	tuple_set_d64(t, 3, comm->start);
1215 	tuple_set_s32(t, 4, comm->exec);
1216 
1217 	call_object(tables->comm_handler, t, "comm_table");
1218 
1219 	Py_DECREF(t);
1220 
1221 	return 0;
1222 }
1223 
1224 static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
1225 				     struct comm *comm, struct thread *thread)
1226 {
1227 	struct tables *tables = container_of(dbe, struct tables, dbe);
1228 	PyObject *t;
1229 
1230 	t = tuple_new(3);
1231 
1232 	tuple_set_d64(t, 0, db_id);
1233 	tuple_set_d64(t, 1, comm->db_id);
1234 	tuple_set_d64(t, 2, thread__db_id(thread));
1235 
1236 	call_object(tables->comm_thread_handler, t, "comm_thread_table");
1237 
1238 	Py_DECREF(t);
1239 
1240 	return 0;
1241 }
1242 
1243 static int python_export_dso(struct db_export *dbe, struct dso *dso,
1244 			     struct machine *machine)
1245 {
1246 	struct tables *tables = container_of(dbe, struct tables, dbe);
1247 	char sbuild_id[SBUILD_ID_SIZE];
1248 	PyObject *t;
1249 
1250 	build_id__snprintf(dso__bid(dso), sbuild_id, sizeof(sbuild_id));
1251 
1252 	t = tuple_new(5);
1253 
1254 	tuple_set_d64(t, 0, dso__db_id(dso));
1255 	tuple_set_d64(t, 1, machine->db_id);
1256 	tuple_set_string(t, 2, dso__short_name(dso));
1257 	tuple_set_string(t, 3, dso__long_name(dso));
1258 	tuple_set_string(t, 4, sbuild_id);
1259 
1260 	call_object(tables->dso_handler, t, "dso_table");
1261 
1262 	Py_DECREF(t);
1263 
1264 	return 0;
1265 }
1266 
1267 static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
1268 				struct dso *dso)
1269 {
1270 	struct tables *tables = container_of(dbe, struct tables, dbe);
1271 	u64 *sym_db_id = symbol__priv(sym);
1272 	PyObject *t;
1273 
1274 	t = tuple_new(6);
1275 
1276 	tuple_set_d64(t, 0, *sym_db_id);
1277 	tuple_set_d64(t, 1, dso__db_id(dso));
1278 	tuple_set_d64(t, 2, sym->start);
1279 	tuple_set_d64(t, 3, sym->end);
1280 	tuple_set_s32(t, 4, sym->binding);
1281 	tuple_set_string(t, 5, sym->name);
1282 
1283 	call_object(tables->symbol_handler, t, "symbol_table");
1284 
1285 	Py_DECREF(t);
1286 
1287 	return 0;
1288 }
1289 
1290 static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
1291 				     const char *name)
1292 {
1293 	struct tables *tables = container_of(dbe, struct tables, dbe);
1294 	PyObject *t;
1295 
1296 	t = tuple_new(2);
1297 
1298 	tuple_set_s32(t, 0, branch_type);
1299 	tuple_set_string(t, 1, name);
1300 
1301 	call_object(tables->branch_type_handler, t, "branch_type_table");
1302 
1303 	Py_DECREF(t);
1304 
1305 	return 0;
1306 }
1307 
1308 static void python_export_sample_table(struct db_export *dbe,
1309 				       struct export_sample *es)
1310 {
1311 	struct tables *tables = container_of(dbe, struct tables, dbe);
1312 	PyObject *t;
1313 
1314 	t = tuple_new(28);
1315 
1316 	tuple_set_d64(t, 0, es->db_id);
1317 	tuple_set_d64(t, 1, es->evsel->db_id);
1318 	tuple_set_d64(t, 2, maps__machine(thread__maps(es->al->thread))->db_id);
1319 	tuple_set_d64(t, 3, thread__db_id(es->al->thread));
1320 	tuple_set_d64(t, 4, es->comm_db_id);
1321 	tuple_set_d64(t, 5, es->dso_db_id);
1322 	tuple_set_d64(t, 6, es->sym_db_id);
1323 	tuple_set_d64(t, 7, es->offset);
1324 	tuple_set_d64(t, 8, es->sample->ip);
1325 	tuple_set_d64(t, 9, es->sample->time);
1326 	tuple_set_s32(t, 10, es->sample->cpu);
1327 	tuple_set_d64(t, 11, es->addr_dso_db_id);
1328 	tuple_set_d64(t, 12, es->addr_sym_db_id);
1329 	tuple_set_d64(t, 13, es->addr_offset);
1330 	tuple_set_d64(t, 14, es->sample->addr);
1331 	tuple_set_d64(t, 15, es->sample->period);
1332 	tuple_set_d64(t, 16, es->sample->weight);
1333 	tuple_set_d64(t, 17, es->sample->transaction);
1334 	tuple_set_d64(t, 18, es->sample->data_src);
1335 	tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
1336 	tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
1337 	tuple_set_d64(t, 21, es->call_path_id);
1338 	tuple_set_d64(t, 22, es->sample->insn_cnt);
1339 	tuple_set_d64(t, 23, es->sample->cyc_cnt);
1340 	tuple_set_s32(t, 24, es->sample->flags);
1341 	tuple_set_d64(t, 25, es->sample->id);
1342 	tuple_set_d64(t, 26, es->sample->stream_id);
1343 	tuple_set_u32(t, 27, es->sample->ins_lat);
1344 
1345 	call_object(tables->sample_handler, t, "sample_table");
1346 
1347 	Py_DECREF(t);
1348 }
1349 
1350 static void python_export_synth(struct db_export *dbe, struct export_sample *es)
1351 {
1352 	struct tables *tables = container_of(dbe, struct tables, dbe);
1353 	PyObject *t;
1354 
1355 	t = tuple_new(3);
1356 
1357 	tuple_set_d64(t, 0, es->db_id);
1358 	tuple_set_d64(t, 1, es->evsel->core.attr.config);
1359 	tuple_set_bytes(t, 2, es->sample->raw_data, es->sample->raw_size);
1360 
1361 	call_object(tables->synth_handler, t, "synth_data");
1362 
1363 	Py_DECREF(t);
1364 }
1365 
1366 static int python_export_sample(struct db_export *dbe,
1367 				struct export_sample *es)
1368 {
1369 	struct tables *tables = container_of(dbe, struct tables, dbe);
1370 
1371 	python_export_sample_table(dbe, es);
1372 
1373 	if (es->evsel->core.attr.type == PERF_TYPE_SYNTH && tables->synth_handler)
1374 		python_export_synth(dbe, es);
1375 
1376 	return 0;
1377 }
1378 
1379 static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
1380 {
1381 	struct tables *tables = container_of(dbe, struct tables, dbe);
1382 	PyObject *t;
1383 	u64 parent_db_id, sym_db_id;
1384 
1385 	parent_db_id = cp->parent ? cp->parent->db_id : 0;
1386 	sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
1387 
1388 	t = tuple_new(4);
1389 
1390 	tuple_set_d64(t, 0, cp->db_id);
1391 	tuple_set_d64(t, 1, parent_db_id);
1392 	tuple_set_d64(t, 2, sym_db_id);
1393 	tuple_set_d64(t, 3, cp->ip);
1394 
1395 	call_object(tables->call_path_handler, t, "call_path_table");
1396 
1397 	Py_DECREF(t);
1398 
1399 	return 0;
1400 }
1401 
1402 static int python_export_call_return(struct db_export *dbe,
1403 				     struct call_return *cr)
1404 {
1405 	struct tables *tables = container_of(dbe, struct tables, dbe);
1406 	u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
1407 	PyObject *t;
1408 
1409 	t = tuple_new(14);
1410 
1411 	tuple_set_d64(t, 0, cr->db_id);
1412 	tuple_set_d64(t, 1, thread__db_id(cr->thread));
1413 	tuple_set_d64(t, 2, comm_db_id);
1414 	tuple_set_d64(t, 3, cr->cp->db_id);
1415 	tuple_set_d64(t, 4, cr->call_time);
1416 	tuple_set_d64(t, 5, cr->return_time);
1417 	tuple_set_d64(t, 6, cr->branch_count);
1418 	tuple_set_d64(t, 7, cr->call_ref);
1419 	tuple_set_d64(t, 8, cr->return_ref);
1420 	tuple_set_d64(t, 9, cr->cp->parent->db_id);
1421 	tuple_set_s32(t, 10, cr->flags);
1422 	tuple_set_d64(t, 11, cr->parent_db_id);
1423 	tuple_set_d64(t, 12, cr->insn_count);
1424 	tuple_set_d64(t, 13, cr->cyc_count);
1425 
1426 	call_object(tables->call_return_handler, t, "call_return_table");
1427 
1428 	Py_DECREF(t);
1429 
1430 	return 0;
1431 }
1432 
1433 static int python_export_context_switch(struct db_export *dbe, u64 db_id,
1434 					struct machine *machine,
1435 					struct perf_sample *sample,
1436 					u64 th_out_id, u64 comm_out_id,
1437 					u64 th_in_id, u64 comm_in_id, int flags)
1438 {
1439 	struct tables *tables = container_of(dbe, struct tables, dbe);
1440 	PyObject *t;
1441 
1442 	t = tuple_new(9);
1443 
1444 	tuple_set_d64(t, 0, db_id);
1445 	tuple_set_d64(t, 1, machine->db_id);
1446 	tuple_set_d64(t, 2, sample->time);
1447 	tuple_set_s32(t, 3, sample->cpu);
1448 	tuple_set_d64(t, 4, th_out_id);
1449 	tuple_set_d64(t, 5, comm_out_id);
1450 	tuple_set_d64(t, 6, th_in_id);
1451 	tuple_set_d64(t, 7, comm_in_id);
1452 	tuple_set_s32(t, 8, flags);
1453 
1454 	call_object(tables->context_switch_handler, t, "context_switch");
1455 
1456 	Py_DECREF(t);
1457 
1458 	return 0;
1459 }
1460 
1461 static int python_process_call_return(struct call_return *cr, u64 *parent_db_id,
1462 				      void *data)
1463 {
1464 	struct db_export *dbe = data;
1465 
1466 	return db_export__call_return(dbe, cr, parent_db_id);
1467 }
1468 
1469 static void python_process_general_event(struct perf_sample *sample,
1470 					 struct evsel *evsel,
1471 					 struct addr_location *al,
1472 					 struct addr_location *addr_al)
1473 {
1474 	PyObject *handler, *t, *dict, *callchain;
1475 	static char handler_name[64];
1476 	unsigned n = 0;
1477 
1478 	snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
1479 
1480 	handler = get_handler(handler_name);
1481 	if (!handler)
1482 		return;
1483 
1484 	/*
1485 	 * Use the MAX_FIELDS to make the function expandable, though
1486 	 * currently there is only one item for the tuple.
1487 	 */
1488 	t = PyTuple_New(MAX_FIELDS);
1489 	if (!t)
1490 		Py_FatalError("couldn't create Python tuple");
1491 
1492 	/* ip unwinding */
1493 	callchain = python_process_callchain(sample, evsel, al);
1494 	dict = get_perf_sample_dict(sample, evsel, al, addr_al, callchain);
1495 
1496 	PyTuple_SetItem(t, n++, dict);
1497 	if (_PyTuple_Resize(&t, n) == -1)
1498 		Py_FatalError("error resizing Python tuple");
1499 
1500 	call_object(handler, t, handler_name);
1501 
1502 	Py_DECREF(t);
1503 }
1504 
1505 static void python_process_event(union perf_event *event,
1506 				 struct perf_sample *sample,
1507 				 struct evsel *evsel,
1508 				 struct addr_location *al,
1509 				 struct addr_location *addr_al)
1510 {
1511 	struct tables *tables = &tables_global;
1512 
1513 	scripting_context__update(scripting_context, event, sample, evsel, al, addr_al);
1514 
1515 	switch (evsel->core.attr.type) {
1516 	case PERF_TYPE_TRACEPOINT:
1517 		python_process_tracepoint(sample, evsel, al, addr_al);
1518 		break;
1519 	/* Reserve for future process_hw/sw/raw APIs */
1520 	default:
1521 		if (tables->db_export_mode)
1522 			db_export__sample(&tables->dbe, event, sample, evsel, al, addr_al);
1523 		else
1524 			python_process_general_event(sample, evsel, al, addr_al);
1525 	}
1526 }
1527 
1528 static void python_process_throttle(union perf_event *event,
1529 				    struct perf_sample *sample,
1530 				    struct machine *machine)
1531 {
1532 	const char *handler_name;
1533 	PyObject *handler, *t;
1534 
1535 	if (event->header.type == PERF_RECORD_THROTTLE)
1536 		handler_name = "throttle";
1537 	else
1538 		handler_name = "unthrottle";
1539 	handler = get_handler(handler_name);
1540 	if (!handler)
1541 		return;
1542 
1543 	t = tuple_new(6);
1544 	if (!t)
1545 		return;
1546 
1547 	tuple_set_u64(t, 0, event->throttle.time);
1548 	tuple_set_u64(t, 1, event->throttle.id);
1549 	tuple_set_u64(t, 2, event->throttle.stream_id);
1550 	tuple_set_s32(t, 3, sample->cpu);
1551 	tuple_set_s32(t, 4, sample->pid);
1552 	tuple_set_s32(t, 5, sample->tid);
1553 
1554 	call_object(handler, t, handler_name);
1555 
1556 	Py_DECREF(t);
1557 }
1558 
1559 static void python_do_process_switch(union perf_event *event,
1560 				     struct perf_sample *sample,
1561 				     struct machine *machine)
1562 {
1563 	const char *handler_name = "context_switch";
1564 	bool out = event->header.misc & PERF_RECORD_MISC_SWITCH_OUT;
1565 	bool out_preempt = out && (event->header.misc & PERF_RECORD_MISC_SWITCH_OUT_PREEMPT);
1566 	pid_t np_pid = -1, np_tid = -1;
1567 	PyObject *handler, *t;
1568 
1569 	handler = get_handler(handler_name);
1570 	if (!handler)
1571 		return;
1572 
1573 	if (event->header.type == PERF_RECORD_SWITCH_CPU_WIDE) {
1574 		np_pid = event->context_switch.next_prev_pid;
1575 		np_tid = event->context_switch.next_prev_tid;
1576 	}
1577 
1578 	t = tuple_new(11);
1579 	if (!t)
1580 		return;
1581 
1582 	tuple_set_u64(t, 0, sample->time);
1583 	tuple_set_s32(t, 1, sample->cpu);
1584 	tuple_set_s32(t, 2, sample->pid);
1585 	tuple_set_s32(t, 3, sample->tid);
1586 	tuple_set_s32(t, 4, np_pid);
1587 	tuple_set_s32(t, 5, np_tid);
1588 	tuple_set_s32(t, 6, machine->pid);
1589 	tuple_set_bool(t, 7, out);
1590 	tuple_set_bool(t, 8, out_preempt);
1591 	tuple_set_s32(t, 9, sample->machine_pid);
1592 	tuple_set_s32(t, 10, sample->vcpu);
1593 
1594 	call_object(handler, t, handler_name);
1595 
1596 	Py_DECREF(t);
1597 }
1598 
1599 static void python_process_switch(union perf_event *event,
1600 				  struct perf_sample *sample,
1601 				  struct machine *machine)
1602 {
1603 	struct tables *tables = &tables_global;
1604 
1605 	if (tables->db_export_mode)
1606 		db_export__switch(&tables->dbe, event, sample, machine);
1607 	else
1608 		python_do_process_switch(event, sample, machine);
1609 }
1610 
1611 static void python_process_auxtrace_error(struct perf_session *session __maybe_unused,
1612 					  union perf_event *event)
1613 {
1614 	struct perf_record_auxtrace_error *e = &event->auxtrace_error;
1615 	u8 cpumode = e->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
1616 	const char *handler_name = "auxtrace_error";
1617 	unsigned long long tm = e->time;
1618 	const char *msg = e->msg;
1619 	PyObject *handler, *t;
1620 
1621 	handler = get_handler(handler_name);
1622 	if (!handler)
1623 		return;
1624 
1625 	if (!e->fmt) {
1626 		tm = 0;
1627 		msg = (const char *)&e->time;
1628 	}
1629 
1630 	t = tuple_new(11);
1631 
1632 	tuple_set_u32(t, 0, e->type);
1633 	tuple_set_u32(t, 1, e->code);
1634 	tuple_set_s32(t, 2, e->cpu);
1635 	tuple_set_s32(t, 3, e->pid);
1636 	tuple_set_s32(t, 4, e->tid);
1637 	tuple_set_u64(t, 5, e->ip);
1638 	tuple_set_u64(t, 6, tm);
1639 	tuple_set_string(t, 7, msg);
1640 	tuple_set_u32(t, 8, cpumode);
1641 	tuple_set_s32(t, 9, e->machine_pid);
1642 	tuple_set_s32(t, 10, e->vcpu);
1643 
1644 	call_object(handler, t, handler_name);
1645 
1646 	Py_DECREF(t);
1647 }
1648 
1649 static void get_handler_name(char *str, size_t size,
1650 			     struct evsel *evsel)
1651 {
1652 	char *p = str;
1653 
1654 	scnprintf(str, size, "stat__%s", evsel__name(evsel));
1655 
1656 	while ((p = strchr(p, ':'))) {
1657 		*p = '_';
1658 		p++;
1659 	}
1660 }
1661 
1662 static void
1663 process_stat(struct evsel *counter, struct perf_cpu cpu, int thread, u64 tstamp,
1664 	     struct perf_counts_values *count)
1665 {
1666 	PyObject *handler, *t;
1667 	static char handler_name[256];
1668 	int n = 0;
1669 
1670 	t = PyTuple_New(MAX_FIELDS);
1671 	if (!t)
1672 		Py_FatalError("couldn't create Python tuple");
1673 
1674 	get_handler_name(handler_name, sizeof(handler_name),
1675 			 counter);
1676 
1677 	handler = get_handler(handler_name);
1678 	if (!handler) {
1679 		pr_debug("can't find python handler %s\n", handler_name);
1680 		return;
1681 	}
1682 
1683 	PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu.cpu));
1684 	PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
1685 
1686 	tuple_set_u64(t, n++, tstamp);
1687 	tuple_set_u64(t, n++, count->val);
1688 	tuple_set_u64(t, n++, count->ena);
1689 	tuple_set_u64(t, n++, count->run);
1690 
1691 	if (_PyTuple_Resize(&t, n) == -1)
1692 		Py_FatalError("error resizing Python tuple");
1693 
1694 	call_object(handler, t, handler_name);
1695 
1696 	Py_DECREF(t);
1697 }
1698 
1699 static void python_process_stat(struct perf_stat_config *config,
1700 				struct evsel *counter, u64 tstamp)
1701 {
1702 	struct perf_thread_map *threads = counter->core.threads;
1703 	struct perf_cpu_map *cpus = counter->core.cpus;
1704 
1705 	for (int thread = 0; thread < perf_thread_map__nr(threads); thread++) {
1706 		int idx;
1707 		struct perf_cpu cpu;
1708 
1709 		perf_cpu_map__for_each_cpu(cpu, idx, cpus) {
1710 			process_stat(counter, cpu,
1711 				     perf_thread_map__pid(threads, thread), tstamp,
1712 				     perf_counts(counter->counts, idx, thread));
1713 		}
1714 	}
1715 }
1716 
1717 static void python_process_stat_interval(u64 tstamp)
1718 {
1719 	PyObject *handler, *t;
1720 	static const char handler_name[] = "stat__interval";
1721 	int n = 0;
1722 
1723 	t = PyTuple_New(MAX_FIELDS);
1724 	if (!t)
1725 		Py_FatalError("couldn't create Python tuple");
1726 
1727 	handler = get_handler(handler_name);
1728 	if (!handler) {
1729 		pr_debug("can't find python handler %s\n", handler_name);
1730 		return;
1731 	}
1732 
1733 	tuple_set_u64(t, n++, tstamp);
1734 
1735 	if (_PyTuple_Resize(&t, n) == -1)
1736 		Py_FatalError("error resizing Python tuple");
1737 
1738 	call_object(handler, t, handler_name);
1739 
1740 	Py_DECREF(t);
1741 }
1742 
1743 static int perf_script_context_init(void)
1744 {
1745 	PyObject *perf_script_context;
1746 	PyObject *perf_trace_context;
1747 	PyObject *dict;
1748 	int ret;
1749 
1750 	perf_trace_context = PyImport_AddModule("perf_trace_context");
1751 	if (!perf_trace_context)
1752 		return -1;
1753 	dict = PyModule_GetDict(perf_trace_context);
1754 	if (!dict)
1755 		return -1;
1756 
1757 	perf_script_context = _PyCapsule_New(scripting_context, NULL, NULL);
1758 	if (!perf_script_context)
1759 		return -1;
1760 
1761 	ret = PyDict_SetItemString(dict, "perf_script_context", perf_script_context);
1762 	if (!ret)
1763 		ret = PyDict_SetItemString(main_dict, "perf_script_context", perf_script_context);
1764 	Py_DECREF(perf_script_context);
1765 	return ret;
1766 }
1767 
1768 static int run_start_sub(void)
1769 {
1770 	main_module = PyImport_AddModule("__main__");
1771 	if (main_module == NULL)
1772 		return -1;
1773 	Py_INCREF(main_module);
1774 
1775 	main_dict = PyModule_GetDict(main_module);
1776 	if (main_dict == NULL)
1777 		goto error;
1778 	Py_INCREF(main_dict);
1779 
1780 	if (perf_script_context_init())
1781 		goto error;
1782 
1783 	try_call_object("trace_begin", NULL);
1784 
1785 	return 0;
1786 
1787 error:
1788 	Py_XDECREF(main_dict);
1789 	Py_XDECREF(main_module);
1790 	return -1;
1791 }
1792 
1793 #define SET_TABLE_HANDLER_(name, handler_name, table_name) do {		\
1794 	tables->handler_name = get_handler(#table_name);		\
1795 	if (tables->handler_name)					\
1796 		tables->dbe.export_ ## name = python_export_ ## name;	\
1797 } while (0)
1798 
1799 #define SET_TABLE_HANDLER(name) \
1800 	SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
1801 
1802 static void set_table_handlers(struct tables *tables)
1803 {
1804 	const char *perf_db_export_mode = "perf_db_export_mode";
1805 	const char *perf_db_export_calls = "perf_db_export_calls";
1806 	const char *perf_db_export_callchains = "perf_db_export_callchains";
1807 	PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
1808 	bool export_calls = false;
1809 	bool export_callchains = false;
1810 	int ret;
1811 
1812 	memset(tables, 0, sizeof(struct tables));
1813 	if (db_export__init(&tables->dbe))
1814 		Py_FatalError("failed to initialize export");
1815 
1816 	db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
1817 	if (!db_export_mode)
1818 		return;
1819 
1820 	ret = PyObject_IsTrue(db_export_mode);
1821 	if (ret == -1)
1822 		handler_call_die(perf_db_export_mode);
1823 	if (!ret)
1824 		return;
1825 
1826 	/* handle export calls */
1827 	tables->dbe.crp = NULL;
1828 	db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
1829 	if (db_export_calls) {
1830 		ret = PyObject_IsTrue(db_export_calls);
1831 		if (ret == -1)
1832 			handler_call_die(perf_db_export_calls);
1833 		export_calls = !!ret;
1834 	}
1835 
1836 	if (export_calls) {
1837 		tables->dbe.crp =
1838 			call_return_processor__new(python_process_call_return,
1839 						   &tables->dbe);
1840 		if (!tables->dbe.crp)
1841 			Py_FatalError("failed to create calls processor");
1842 	}
1843 
1844 	/* handle export callchains */
1845 	tables->dbe.cpr = NULL;
1846 	db_export_callchains = PyDict_GetItemString(main_dict,
1847 						    perf_db_export_callchains);
1848 	if (db_export_callchains) {
1849 		ret = PyObject_IsTrue(db_export_callchains);
1850 		if (ret == -1)
1851 			handler_call_die(perf_db_export_callchains);
1852 		export_callchains = !!ret;
1853 	}
1854 
1855 	if (export_callchains) {
1856 		/*
1857 		 * Attempt to use the call path root from the call return
1858 		 * processor, if the call return processor is in use. Otherwise,
1859 		 * we allocate a new call path root. This prevents exporting
1860 		 * duplicate call path ids when both are in use simultaneously.
1861 		 */
1862 		if (tables->dbe.crp)
1863 			tables->dbe.cpr = tables->dbe.crp->cpr;
1864 		else
1865 			tables->dbe.cpr = call_path_root__new();
1866 
1867 		if (!tables->dbe.cpr)
1868 			Py_FatalError("failed to create call path root");
1869 	}
1870 
1871 	tables->db_export_mode = true;
1872 	/*
1873 	 * Reserve per symbol space for symbol->db_id via symbol__priv()
1874 	 */
1875 	symbol_conf.priv_size = sizeof(u64);
1876 
1877 	SET_TABLE_HANDLER(evsel);
1878 	SET_TABLE_HANDLER(machine);
1879 	SET_TABLE_HANDLER(thread);
1880 	SET_TABLE_HANDLER(comm);
1881 	SET_TABLE_HANDLER(comm_thread);
1882 	SET_TABLE_HANDLER(dso);
1883 	SET_TABLE_HANDLER(symbol);
1884 	SET_TABLE_HANDLER(branch_type);
1885 	SET_TABLE_HANDLER(sample);
1886 	SET_TABLE_HANDLER(call_path);
1887 	SET_TABLE_HANDLER(call_return);
1888 	SET_TABLE_HANDLER(context_switch);
1889 
1890 	/*
1891 	 * Synthesized events are samples but with architecture-specific data
1892 	 * stored in sample->raw_data. They are exported via
1893 	 * python_export_sample() and consequently do not need a separate export
1894 	 * callback.
1895 	 */
1896 	tables->synth_handler = get_handler("synth_data");
1897 }
1898 
1899 static void _free_command_line(wchar_t **command_line, int num)
1900 {
1901 	int i;
1902 	for (i = 0; i < num; i++)
1903 		PyMem_RawFree(command_line[i]);
1904 	free(command_line);
1905 }
1906 
1907 
1908 /*
1909  * Start trace script
1910  */
1911 static int python_start_script(const char *script, int argc, const char **argv,
1912 			       struct perf_session *session)
1913 {
1914 	struct tables *tables = &tables_global;
1915 	wchar_t **command_line;
1916 	char buf[PATH_MAX];
1917 	int i, err = 0;
1918 	FILE *fp;
1919 
1920 	scripting_context->session = session;
1921 	command_line = malloc((argc + 1) * sizeof(wchar_t *));
1922 	if (!command_line)
1923 		return -1;
1924 
1925 	command_line[0] = Py_DecodeLocale(script, NULL);
1926 	for (i = 1; i < argc + 1; i++)
1927 		command_line[i] = Py_DecodeLocale(argv[i - 1], NULL);
1928 	PyImport_AppendInittab("perf_trace_context", PyInit_perf_trace_context);
1929 	Py_Initialize();
1930 
1931 	PySys_SetArgv(argc + 1, command_line);
1932 
1933 	fp = fopen(script, "r");
1934 	if (!fp) {
1935 		sprintf(buf, "Can't open python script \"%s\"", script);
1936 		perror(buf);
1937 		err = -1;
1938 		goto error;
1939 	}
1940 
1941 	err = PyRun_SimpleFile(fp, script);
1942 	if (err) {
1943 		fprintf(stderr, "Error running python script %s\n", script);
1944 		goto error;
1945 	}
1946 
1947 	err = run_start_sub();
1948 	if (err) {
1949 		fprintf(stderr, "Error starting python script %s\n", script);
1950 		goto error;
1951 	}
1952 
1953 	set_table_handlers(tables);
1954 
1955 	if (tables->db_export_mode) {
1956 		err = db_export__branch_types(&tables->dbe);
1957 		if (err)
1958 			goto error;
1959 	}
1960 
1961 	_free_command_line(command_line, argc + 1);
1962 
1963 	return err;
1964 error:
1965 	Py_Finalize();
1966 	_free_command_line(command_line, argc + 1);
1967 
1968 	return err;
1969 }
1970 
1971 static int python_flush_script(void)
1972 {
1973 	return 0;
1974 }
1975 
1976 /*
1977  * Stop trace script
1978  */
1979 static int python_stop_script(void)
1980 {
1981 	struct tables *tables = &tables_global;
1982 
1983 	try_call_object("trace_end", NULL);
1984 
1985 	db_export__exit(&tables->dbe);
1986 
1987 	Py_XDECREF(main_dict);
1988 	Py_XDECREF(main_module);
1989 	Py_Finalize();
1990 
1991 	return 0;
1992 }
1993 
1994 #ifdef HAVE_LIBTRACEEVENT
1995 static int python_generate_script(struct tep_handle *pevent, const char *outfile)
1996 {
1997 	int i, not_first, count, nr_events;
1998 	struct tep_event **all_events;
1999 	struct tep_event *event = NULL;
2000 	struct tep_format_field *f;
2001 	char fname[PATH_MAX];
2002 	FILE *ofp;
2003 
2004 	sprintf(fname, "%s.py", outfile);
2005 	ofp = fopen(fname, "w");
2006 	if (ofp == NULL) {
2007 		fprintf(stderr, "couldn't open %s\n", fname);
2008 		return -1;
2009 	}
2010 	fprintf(ofp, "# perf script event handlers, "
2011 		"generated by perf script -g python\n");
2012 
2013 	fprintf(ofp, "# Licensed under the terms of the GNU GPL"
2014 		" License version 2\n\n");
2015 
2016 	fprintf(ofp, "# The common_* event handler fields are the most useful "
2017 		"fields common to\n");
2018 
2019 	fprintf(ofp, "# all events.  They don't necessarily correspond to "
2020 		"the 'common_*' fields\n");
2021 
2022 	fprintf(ofp, "# in the format files.  Those fields not available as "
2023 		"handler params can\n");
2024 
2025 	fprintf(ofp, "# be retrieved using Python functions of the form "
2026 		"common_*(context).\n");
2027 
2028 	fprintf(ofp, "# See the perf-script-python Documentation for the list "
2029 		"of available functions.\n\n");
2030 
2031 	fprintf(ofp, "from __future__ import print_function\n\n");
2032 	fprintf(ofp, "import os\n");
2033 	fprintf(ofp, "import sys\n\n");
2034 
2035 	fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
2036 	fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
2037 	fprintf(ofp, "\nfrom perf_trace_context import *\n");
2038 	fprintf(ofp, "from Core import *\n\n\n");
2039 
2040 	fprintf(ofp, "def trace_begin():\n");
2041 	fprintf(ofp, "\tprint(\"in trace_begin\")\n\n");
2042 
2043 	fprintf(ofp, "def trace_end():\n");
2044 	fprintf(ofp, "\tprint(\"in trace_end\")\n\n");
2045 
2046 	nr_events = tep_get_events_count(pevent);
2047 	all_events = tep_list_events(pevent, TEP_EVENT_SORT_ID);
2048 
2049 	for (i = 0; all_events && i < nr_events; i++) {
2050 		event = all_events[i];
2051 		fprintf(ofp, "def %s__%s(", event->system, event->name);
2052 		fprintf(ofp, "event_name, ");
2053 		fprintf(ofp, "context, ");
2054 		fprintf(ofp, "common_cpu,\n");
2055 		fprintf(ofp, "\tcommon_secs, ");
2056 		fprintf(ofp, "common_nsecs, ");
2057 		fprintf(ofp, "common_pid, ");
2058 		fprintf(ofp, "common_comm,\n\t");
2059 		fprintf(ofp, "common_callchain, ");
2060 
2061 		not_first = 0;
2062 		count = 0;
2063 
2064 		for (f = event->format.fields; f; f = f->next) {
2065 			if (not_first++)
2066 				fprintf(ofp, ", ");
2067 			if (++count % 5 == 0)
2068 				fprintf(ofp, "\n\t");
2069 
2070 			fprintf(ofp, "%s", f->name);
2071 		}
2072 		if (not_first++)
2073 			fprintf(ofp, ", ");
2074 		if (++count % 5 == 0)
2075 			fprintf(ofp, "\n\t\t");
2076 		fprintf(ofp, "perf_sample_dict");
2077 
2078 		fprintf(ofp, "):\n");
2079 
2080 		fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
2081 			"common_secs, common_nsecs,\n\t\t\t"
2082 			"common_pid, common_comm)\n\n");
2083 
2084 		fprintf(ofp, "\t\tprint(\"");
2085 
2086 		not_first = 0;
2087 		count = 0;
2088 
2089 		for (f = event->format.fields; f; f = f->next) {
2090 			if (not_first++)
2091 				fprintf(ofp, ", ");
2092 			if (count && count % 3 == 0) {
2093 				fprintf(ofp, "\" \\\n\t\t\"");
2094 			}
2095 			count++;
2096 
2097 			fprintf(ofp, "%s=", f->name);
2098 			if (f->flags & TEP_FIELD_IS_STRING ||
2099 			    f->flags & TEP_FIELD_IS_FLAG ||
2100 			    f->flags & TEP_FIELD_IS_ARRAY ||
2101 			    f->flags & TEP_FIELD_IS_SYMBOLIC)
2102 				fprintf(ofp, "%%s");
2103 			else if (f->flags & TEP_FIELD_IS_SIGNED)
2104 				fprintf(ofp, "%%d");
2105 			else
2106 				fprintf(ofp, "%%u");
2107 		}
2108 
2109 		fprintf(ofp, "\" %% \\\n\t\t(");
2110 
2111 		not_first = 0;
2112 		count = 0;
2113 
2114 		for (f = event->format.fields; f; f = f->next) {
2115 			if (not_first++)
2116 				fprintf(ofp, ", ");
2117 
2118 			if (++count % 5 == 0)
2119 				fprintf(ofp, "\n\t\t");
2120 
2121 			if (f->flags & TEP_FIELD_IS_FLAG) {
2122 				if ((count - 1) % 5 != 0) {
2123 					fprintf(ofp, "\n\t\t");
2124 					count = 4;
2125 				}
2126 				fprintf(ofp, "flag_str(\"");
2127 				fprintf(ofp, "%s__%s\", ", event->system,
2128 					event->name);
2129 				fprintf(ofp, "\"%s\", %s)", f->name,
2130 					f->name);
2131 			} else if (f->flags & TEP_FIELD_IS_SYMBOLIC) {
2132 				if ((count - 1) % 5 != 0) {
2133 					fprintf(ofp, "\n\t\t");
2134 					count = 4;
2135 				}
2136 				fprintf(ofp, "symbol_str(\"");
2137 				fprintf(ofp, "%s__%s\", ", event->system,
2138 					event->name);
2139 				fprintf(ofp, "\"%s\", %s)", f->name,
2140 					f->name);
2141 			} else
2142 				fprintf(ofp, "%s", f->name);
2143 		}
2144 
2145 		fprintf(ofp, "))\n\n");
2146 
2147 		fprintf(ofp, "\t\tprint('Sample: {'+"
2148 			"get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
2149 
2150 		fprintf(ofp, "\t\tfor node in common_callchain:");
2151 		fprintf(ofp, "\n\t\t\tif 'sym' in node:");
2152 		fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x] %%s%%s%%s%%s\" %% (");
2153 		fprintf(ofp, "\n\t\t\t\t\tnode['ip'], node['sym']['name'],");
2154 		fprintf(ofp, "\n\t\t\t\t\t\"+0x{:x}\".format(node['sym_off']) if 'sym_off' in node else \"\",");
2155 		fprintf(ofp, "\n\t\t\t\t\t\" ({})\".format(node['dso'])  if 'dso' in node else \"\",");
2156 		fprintf(ofp, "\n\t\t\t\t\t\" \" + node['sym_srcline'] if 'sym_srcline' in node else \"\"))");
2157 		fprintf(ofp, "\n\t\t\telse:");
2158 		fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x]\" %% (node['ip']))\n\n");
2159 		fprintf(ofp, "\t\tprint()\n\n");
2160 
2161 	}
2162 
2163 	fprintf(ofp, "def trace_unhandled(event_name, context, "
2164 		"event_fields_dict, perf_sample_dict):\n");
2165 
2166 	fprintf(ofp, "\t\tprint(get_dict_as_string(event_fields_dict))\n");
2167 	fprintf(ofp, "\t\tprint('Sample: {'+"
2168 		"get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
2169 
2170 	fprintf(ofp, "def print_header("
2171 		"event_name, cpu, secs, nsecs, pid, comm):\n"
2172 		"\tprint(\"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
2173 		"(event_name, cpu, secs, nsecs, pid, comm), end=\"\")\n\n");
2174 
2175 	fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
2176 		"\treturn delimiter.join"
2177 		"(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
2178 
2179 	fclose(ofp);
2180 
2181 	fprintf(stderr, "generated Python script: %s\n", fname);
2182 
2183 	return 0;
2184 }
2185 #else
2186 static int python_generate_script(struct tep_handle *pevent __maybe_unused,
2187 				  const char *outfile __maybe_unused)
2188 {
2189 	fprintf(stderr, "Generating Python perf-script is not supported."
2190 		"  Install libtraceevent and rebuild perf to enable it.\n"
2191 		"For example:\n  # apt install libtraceevent-dev (ubuntu)"
2192 		"\n  # yum install libtraceevent-devel (Fedora)"
2193 		"\n  etc.\n");
2194 	return -1;
2195 }
2196 #endif
2197 
2198 struct scripting_ops python_scripting_ops = {
2199 	.name			= "Python",
2200 	.dirname		= "python",
2201 	.start_script		= python_start_script,
2202 	.flush_script		= python_flush_script,
2203 	.stop_script		= python_stop_script,
2204 	.process_event		= python_process_event,
2205 	.process_switch		= python_process_switch,
2206 	.process_auxtrace_error	= python_process_auxtrace_error,
2207 	.process_stat		= python_process_stat,
2208 	.process_stat_interval	= python_process_stat_interval,
2209 	.process_throttle	= python_process_throttle,
2210 	.generate_script	= python_generate_script,
2211 };
2212