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