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