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