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