1 /*
2  * trace-event-python.  Feed trace events to an embedded Python interpreter.
3  *
4  * Copyright (C) 2010 Tom Zanussi <[email protected]>
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 
34 #include "../../perf.h"
35 #include "../debug.h"
36 #include "../callchain.h"
37 #include "../evsel.h"
38 #include "../util.h"
39 #include "../event.h"
40 #include "../thread.h"
41 #include "../comm.h"
42 #include "../machine.h"
43 #include "../db-export.h"
44 #include "../thread-stack.h"
45 #include "../trace-event.h"
46 #include "../call-path.h"
47 #include "thread_map.h"
48 #include "cpumap.h"
49 #include "print_binary.h"
50 #include "stat.h"
51 #include "mem-events.h"
52 
53 #if PY_MAJOR_VERSION < 3
54 #define _PyUnicode_FromString(arg) \
55   PyString_FromString(arg)
56 #define _PyUnicode_FromStringAndSize(arg1, arg2) \
57   PyString_FromStringAndSize((arg1), (arg2))
58 #define _PyBytes_FromStringAndSize(arg1, arg2) \
59   PyString_FromStringAndSize((arg1), (arg2))
60 #define _PyLong_FromLong(arg) \
61   PyInt_FromLong(arg)
62 #define _PyLong_AsLong(arg) \
63   PyInt_AsLong(arg)
64 #define _PyCapsule_New(arg1, arg2, arg3) \
65   PyCObject_FromVoidPtr((arg1), (arg2))
66 
67 PyMODINIT_FUNC initperf_trace_context(void);
68 #else
69 #define _PyUnicode_FromString(arg) \
70   PyUnicode_FromString(arg)
71 #define _PyUnicode_FromStringAndSize(arg1, arg2) \
72   PyUnicode_FromStringAndSize((arg1), (arg2))
73 #define _PyBytes_FromStringAndSize(arg1, arg2) \
74   PyBytes_FromStringAndSize((arg1), (arg2))
75 #define _PyLong_FromLong(arg) \
76   PyLong_FromLong(arg)
77 #define _PyLong_AsLong(arg) \
78   PyLong_AsLong(arg)
79 #define _PyCapsule_New(arg1, arg2, arg3) \
80   PyCapsule_New((arg1), (arg2), (arg3))
81 
82 PyMODINIT_FUNC PyInit_perf_trace_context(void);
83 #endif
84 
85 #define TRACE_EVENT_TYPE_MAX				\
86 	((1 << (sizeof(unsigned short) * 8)) - 1)
87 
88 static DECLARE_BITMAP(events_defined, TRACE_EVENT_TYPE_MAX);
89 
90 #define MAX_FIELDS	64
91 #define N_COMMON_FIELDS	7
92 
93 extern struct scripting_context *scripting_context;
94 
95 static char *cur_field_name;
96 static int zero_flag_atom;
97 
98 static PyObject *main_module, *main_dict;
99 
100 struct tables {
101 	struct db_export	dbe;
102 	PyObject		*evsel_handler;
103 	PyObject		*machine_handler;
104 	PyObject		*thread_handler;
105 	PyObject		*comm_handler;
106 	PyObject		*comm_thread_handler;
107 	PyObject		*dso_handler;
108 	PyObject		*symbol_handler;
109 	PyObject		*branch_type_handler;
110 	PyObject		*sample_handler;
111 	PyObject		*call_path_handler;
112 	PyObject		*call_return_handler;
113 	bool			db_export_mode;
114 };
115 
116 static struct tables tables_global;
117 
118 static void handler_call_die(const char *handler_name) __noreturn;
119 static void handler_call_die(const char *handler_name)
120 {
121 	PyErr_Print();
122 	Py_FatalError("problem in Python trace event handler");
123 	// Py_FatalError does not return
124 	// but we have to make the compiler happy
125 	abort();
126 }
127 
128 /*
129  * Insert val into into the dictionary and decrement the reference counter.
130  * This is necessary for dictionaries since PyDict_SetItemString() does not
131  * steal a reference, as opposed to PyTuple_SetItem().
132  */
133 static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
134 {
135 	PyDict_SetItemString(dict, key, val);
136 	Py_DECREF(val);
137 }
138 
139 static PyObject *get_handler(const char *handler_name)
140 {
141 	PyObject *handler;
142 
143 	handler = PyDict_GetItemString(main_dict, handler_name);
144 	if (handler && !PyCallable_Check(handler))
145 		return NULL;
146 	return handler;
147 }
148 
149 static int get_argument_count(PyObject *handler)
150 {
151 	int arg_count = 0;
152 
153 	/*
154 	 * The attribute for the code object is func_code in Python 2,
155 	 * whereas it is __code__ in Python 3.0+.
156 	 */
157 	PyObject *code_obj = PyObject_GetAttrString(handler,
158 		"func_code");
159 	if (PyErr_Occurred()) {
160 		PyErr_Clear();
161 		code_obj = PyObject_GetAttrString(handler,
162 			"__code__");
163 	}
164 	PyErr_Clear();
165 	if (code_obj) {
166 		PyObject *arg_count_obj = PyObject_GetAttrString(code_obj,
167 			"co_argcount");
168 		if (arg_count_obj) {
169 			arg_count = (int) _PyLong_AsLong(arg_count_obj);
170 			Py_DECREF(arg_count_obj);
171 		}
172 		Py_DECREF(code_obj);
173 	}
174 	return arg_count;
175 }
176 
177 static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
178 {
179 	PyObject *retval;
180 
181 	retval = PyObject_CallObject(handler, args);
182 	if (retval == NULL)
183 		handler_call_die(die_msg);
184 	Py_DECREF(retval);
185 }
186 
187 static void try_call_object(const char *handler_name, PyObject *args)
188 {
189 	PyObject *handler;
190 
191 	handler = get_handler(handler_name);
192 	if (handler)
193 		call_object(handler, args, handler_name);
194 }
195 
196 static void define_value(enum tep_print_arg_type field_type,
197 			 const char *ev_name,
198 			 const char *field_name,
199 			 const char *field_value,
200 			 const char *field_str)
201 {
202 	const char *handler_name = "define_flag_value";
203 	PyObject *t;
204 	unsigned long long value;
205 	unsigned n = 0;
206 
207 	if (field_type == TEP_PRINT_SYMBOL)
208 		handler_name = "define_symbolic_value";
209 
210 	t = PyTuple_New(4);
211 	if (!t)
212 		Py_FatalError("couldn't create Python tuple");
213 
214 	value = eval_flag(field_value);
215 
216 	PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
217 	PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
218 	PyTuple_SetItem(t, n++, _PyLong_FromLong(value));
219 	PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_str));
220 
221 	try_call_object(handler_name, t);
222 
223 	Py_DECREF(t);
224 }
225 
226 static void define_values(enum tep_print_arg_type field_type,
227 			  struct tep_print_flag_sym *field,
228 			  const char *ev_name,
229 			  const char *field_name)
230 {
231 	define_value(field_type, ev_name, field_name, field->value,
232 		     field->str);
233 
234 	if (field->next)
235 		define_values(field_type, field->next, ev_name, field_name);
236 }
237 
238 static void define_field(enum tep_print_arg_type field_type,
239 			 const char *ev_name,
240 			 const char *field_name,
241 			 const char *delim)
242 {
243 	const char *handler_name = "define_flag_field";
244 	PyObject *t;
245 	unsigned n = 0;
246 
247 	if (field_type == TEP_PRINT_SYMBOL)
248 		handler_name = "define_symbolic_field";
249 
250 	if (field_type == TEP_PRINT_FLAGS)
251 		t = PyTuple_New(3);
252 	else
253 		t = PyTuple_New(2);
254 	if (!t)
255 		Py_FatalError("couldn't create Python tuple");
256 
257 	PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
258 	PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
259 	if (field_type == TEP_PRINT_FLAGS)
260 		PyTuple_SetItem(t, n++, _PyUnicode_FromString(delim));
261 
262 	try_call_object(handler_name, t);
263 
264 	Py_DECREF(t);
265 }
266 
267 static void define_event_symbols(struct tep_event *event,
268 				 const char *ev_name,
269 				 struct tep_print_arg *args)
270 {
271 	if (args == NULL)
272 		return;
273 
274 	switch (args->type) {
275 	case TEP_PRINT_NULL:
276 		break;
277 	case TEP_PRINT_ATOM:
278 		define_value(TEP_PRINT_FLAGS, ev_name, cur_field_name, "0",
279 			     args->atom.atom);
280 		zero_flag_atom = 0;
281 		break;
282 	case TEP_PRINT_FIELD:
283 		free(cur_field_name);
284 		cur_field_name = strdup(args->field.name);
285 		break;
286 	case TEP_PRINT_FLAGS:
287 		define_event_symbols(event, ev_name, args->flags.field);
288 		define_field(TEP_PRINT_FLAGS, ev_name, cur_field_name,
289 			     args->flags.delim);
290 		define_values(TEP_PRINT_FLAGS, args->flags.flags, ev_name,
291 			      cur_field_name);
292 		break;
293 	case TEP_PRINT_SYMBOL:
294 		define_event_symbols(event, ev_name, args->symbol.field);
295 		define_field(TEP_PRINT_SYMBOL, ev_name, cur_field_name, NULL);
296 		define_values(TEP_PRINT_SYMBOL, args->symbol.symbols, ev_name,
297 			      cur_field_name);
298 		break;
299 	case TEP_PRINT_HEX:
300 	case TEP_PRINT_HEX_STR:
301 		define_event_symbols(event, ev_name, args->hex.field);
302 		define_event_symbols(event, ev_name, args->hex.size);
303 		break;
304 	case TEP_PRINT_INT_ARRAY:
305 		define_event_symbols(event, ev_name, args->int_array.field);
306 		define_event_symbols(event, ev_name, args->int_array.count);
307 		define_event_symbols(event, ev_name, args->int_array.el_size);
308 		break;
309 	case TEP_PRINT_STRING:
310 		break;
311 	case TEP_PRINT_TYPE:
312 		define_event_symbols(event, ev_name, args->typecast.item);
313 		break;
314 	case TEP_PRINT_OP:
315 		if (strcmp(args->op.op, ":") == 0)
316 			zero_flag_atom = 1;
317 		define_event_symbols(event, ev_name, args->op.left);
318 		define_event_symbols(event, ev_name, args->op.right);
319 		break;
320 	default:
321 		/* gcc warns for these? */
322 	case TEP_PRINT_BSTRING:
323 	case TEP_PRINT_DYNAMIC_ARRAY:
324 	case TEP_PRINT_DYNAMIC_ARRAY_LEN:
325 	case TEP_PRINT_FUNC:
326 	case TEP_PRINT_BITMASK:
327 		/* we should warn... */
328 		return;
329 	}
330 
331 	if (args->next)
332 		define_event_symbols(event, ev_name, args->next);
333 }
334 
335 static PyObject *get_field_numeric_entry(struct tep_event *event,
336 		struct tep_format_field *field, void *data)
337 {
338 	bool is_array = field->flags & TEP_FIELD_IS_ARRAY;
339 	PyObject *obj = NULL, *list = NULL;
340 	unsigned long long val;
341 	unsigned int item_size, n_items, i;
342 
343 	if (is_array) {
344 		list = PyList_New(field->arraylen);
345 		item_size = field->size / field->arraylen;
346 		n_items = field->arraylen;
347 	} else {
348 		item_size = field->size;
349 		n_items = 1;
350 	}
351 
352 	for (i = 0; i < n_items; i++) {
353 
354 		val = read_size(event, data + field->offset + i * item_size,
355 				item_size);
356 		if (field->flags & TEP_FIELD_IS_SIGNED) {
357 			if ((long long)val >= LONG_MIN &&
358 					(long long)val <= LONG_MAX)
359 				obj = _PyLong_FromLong(val);
360 			else
361 				obj = PyLong_FromLongLong(val);
362 		} else {
363 			if (val <= LONG_MAX)
364 				obj = _PyLong_FromLong(val);
365 			else
366 				obj = PyLong_FromUnsignedLongLong(val);
367 		}
368 		if (is_array)
369 			PyList_SET_ITEM(list, i, obj);
370 	}
371 	if (is_array)
372 		obj = list;
373 	return obj;
374 }
375 
376 static const char *get_dsoname(struct map *map)
377 {
378 	const char *dsoname = "[unknown]";
379 
380 	if (map && map->dso) {
381 		if (symbol_conf.show_kernel_path && map->dso->long_name)
382 			dsoname = map->dso->long_name;
383 		else
384 			dsoname = map->dso->name;
385 	}
386 
387 	return dsoname;
388 }
389 
390 static PyObject *python_process_callchain(struct perf_sample *sample,
391 					 struct perf_evsel *evsel,
392 					 struct addr_location *al)
393 {
394 	PyObject *pylist;
395 
396 	pylist = PyList_New(0);
397 	if (!pylist)
398 		Py_FatalError("couldn't create Python list");
399 
400 	if (!symbol_conf.use_callchain || !sample->callchain)
401 		goto exit;
402 
403 	if (thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
404 				      sample, NULL, NULL,
405 				      scripting_max_stack) != 0) {
406 		pr_err("Failed to resolve callchain. Skipping\n");
407 		goto exit;
408 	}
409 	callchain_cursor_commit(&callchain_cursor);
410 
411 
412 	while (1) {
413 		PyObject *pyelem;
414 		struct callchain_cursor_node *node;
415 		node = callchain_cursor_current(&callchain_cursor);
416 		if (!node)
417 			break;
418 
419 		pyelem = PyDict_New();
420 		if (!pyelem)
421 			Py_FatalError("couldn't create Python dictionary");
422 
423 
424 		pydict_set_item_string_decref(pyelem, "ip",
425 				PyLong_FromUnsignedLongLong(node->ip));
426 
427 		if (node->sym) {
428 			PyObject *pysym  = PyDict_New();
429 			if (!pysym)
430 				Py_FatalError("couldn't create Python dictionary");
431 			pydict_set_item_string_decref(pysym, "start",
432 					PyLong_FromUnsignedLongLong(node->sym->start));
433 			pydict_set_item_string_decref(pysym, "end",
434 					PyLong_FromUnsignedLongLong(node->sym->end));
435 			pydict_set_item_string_decref(pysym, "binding",
436 					_PyLong_FromLong(node->sym->binding));
437 			pydict_set_item_string_decref(pysym, "name",
438 					_PyUnicode_FromStringAndSize(node->sym->name,
439 							node->sym->namelen));
440 			pydict_set_item_string_decref(pyelem, "sym", pysym);
441 		}
442 
443 		if (node->map) {
444 			const char *dsoname = get_dsoname(node->map);
445 
446 			pydict_set_item_string_decref(pyelem, "dso",
447 					_PyUnicode_FromString(dsoname));
448 		}
449 
450 		callchain_cursor_advance(&callchain_cursor);
451 		PyList_Append(pylist, pyelem);
452 		Py_DECREF(pyelem);
453 	}
454 
455 exit:
456 	return pylist;
457 }
458 
459 static PyObject *python_process_brstack(struct perf_sample *sample,
460 					struct thread *thread)
461 {
462 	struct branch_stack *br = sample->branch_stack;
463 	PyObject *pylist;
464 	u64 i;
465 
466 	pylist = PyList_New(0);
467 	if (!pylist)
468 		Py_FatalError("couldn't create Python list");
469 
470 	if (!(br && br->nr))
471 		goto exit;
472 
473 	for (i = 0; i < br->nr; i++) {
474 		PyObject *pyelem;
475 		struct addr_location al;
476 		const char *dsoname;
477 
478 		pyelem = PyDict_New();
479 		if (!pyelem)
480 			Py_FatalError("couldn't create Python dictionary");
481 
482 		pydict_set_item_string_decref(pyelem, "from",
483 		    PyLong_FromUnsignedLongLong(br->entries[i].from));
484 		pydict_set_item_string_decref(pyelem, "to",
485 		    PyLong_FromUnsignedLongLong(br->entries[i].to));
486 		pydict_set_item_string_decref(pyelem, "mispred",
487 		    PyBool_FromLong(br->entries[i].flags.mispred));
488 		pydict_set_item_string_decref(pyelem, "predicted",
489 		    PyBool_FromLong(br->entries[i].flags.predicted));
490 		pydict_set_item_string_decref(pyelem, "in_tx",
491 		    PyBool_FromLong(br->entries[i].flags.in_tx));
492 		pydict_set_item_string_decref(pyelem, "abort",
493 		    PyBool_FromLong(br->entries[i].flags.abort));
494 		pydict_set_item_string_decref(pyelem, "cycles",
495 		    PyLong_FromUnsignedLongLong(br->entries[i].flags.cycles));
496 
497 		thread__find_map_fb(thread, sample->cpumode,
498 				    br->entries[i].from, &al);
499 		dsoname = get_dsoname(al.map);
500 		pydict_set_item_string_decref(pyelem, "from_dsoname",
501 					      _PyUnicode_FromString(dsoname));
502 
503 		thread__find_map_fb(thread, sample->cpumode,
504 				    br->entries[i].to, &al);
505 		dsoname = get_dsoname(al.map);
506 		pydict_set_item_string_decref(pyelem, "to_dsoname",
507 					      _PyUnicode_FromString(dsoname));
508 
509 		PyList_Append(pylist, pyelem);
510 		Py_DECREF(pyelem);
511 	}
512 
513 exit:
514 	return pylist;
515 }
516 
517 static unsigned long get_offset(struct symbol *sym, struct addr_location *al)
518 {
519 	unsigned long offset;
520 
521 	if (al->addr < sym->end)
522 		offset = al->addr - sym->start;
523 	else
524 		offset = al->addr - al->map->start - sym->start;
525 
526 	return offset;
527 }
528 
529 static int get_symoff(struct symbol *sym, struct addr_location *al,
530 		      bool print_off, char *bf, int size)
531 {
532 	unsigned long offset;
533 
534 	if (!sym || !sym->name[0])
535 		return scnprintf(bf, size, "%s", "[unknown]");
536 
537 	if (!print_off)
538 		return scnprintf(bf, size, "%s", sym->name);
539 
540 	offset = get_offset(sym, al);
541 
542 	return scnprintf(bf, size, "%s+0x%x", sym->name, offset);
543 }
544 
545 static int get_br_mspred(struct branch_flags *flags, char *bf, int size)
546 {
547 	if (!flags->mispred  && !flags->predicted)
548 		return scnprintf(bf, size, "%s", "-");
549 
550 	if (flags->mispred)
551 		return scnprintf(bf, size, "%s", "M");
552 
553 	return scnprintf(bf, size, "%s", "P");
554 }
555 
556 static PyObject *python_process_brstacksym(struct perf_sample *sample,
557 					   struct thread *thread)
558 {
559 	struct branch_stack *br = sample->branch_stack;
560 	PyObject *pylist;
561 	u64 i;
562 	char bf[512];
563 	struct addr_location al;
564 
565 	pylist = PyList_New(0);
566 	if (!pylist)
567 		Py_FatalError("couldn't create Python list");
568 
569 	if (!(br && br->nr))
570 		goto exit;
571 
572 	for (i = 0; i < br->nr; i++) {
573 		PyObject *pyelem;
574 
575 		pyelem = PyDict_New();
576 		if (!pyelem)
577 			Py_FatalError("couldn't create Python dictionary");
578 
579 		thread__find_symbol_fb(thread, sample->cpumode,
580 				       br->entries[i].from, &al);
581 		get_symoff(al.sym, &al, true, bf, sizeof(bf));
582 		pydict_set_item_string_decref(pyelem, "from",
583 					      _PyUnicode_FromString(bf));
584 
585 		thread__find_symbol_fb(thread, sample->cpumode,
586 				       br->entries[i].to, &al);
587 		get_symoff(al.sym, &al, true, bf, sizeof(bf));
588 		pydict_set_item_string_decref(pyelem, "to",
589 					      _PyUnicode_FromString(bf));
590 
591 		get_br_mspred(&br->entries[i].flags, bf, sizeof(bf));
592 		pydict_set_item_string_decref(pyelem, "pred",
593 					      _PyUnicode_FromString(bf));
594 
595 		if (br->entries[i].flags.in_tx) {
596 			pydict_set_item_string_decref(pyelem, "in_tx",
597 					      _PyUnicode_FromString("X"));
598 		} else {
599 			pydict_set_item_string_decref(pyelem, "in_tx",
600 					      _PyUnicode_FromString("-"));
601 		}
602 
603 		if (br->entries[i].flags.abort) {
604 			pydict_set_item_string_decref(pyelem, "abort",
605 					      _PyUnicode_FromString("A"));
606 		} else {
607 			pydict_set_item_string_decref(pyelem, "abort",
608 					      _PyUnicode_FromString("-"));
609 		}
610 
611 		PyList_Append(pylist, pyelem);
612 		Py_DECREF(pyelem);
613 	}
614 
615 exit:
616 	return pylist;
617 }
618 
619 static PyObject *get_sample_value_as_tuple(struct sample_read_value *value)
620 {
621 	PyObject *t;
622 
623 	t = PyTuple_New(2);
624 	if (!t)
625 		Py_FatalError("couldn't create Python tuple");
626 	PyTuple_SetItem(t, 0, PyLong_FromUnsignedLongLong(value->id));
627 	PyTuple_SetItem(t, 1, PyLong_FromUnsignedLongLong(value->value));
628 	return t;
629 }
630 
631 static void set_sample_read_in_dict(PyObject *dict_sample,
632 					 struct perf_sample *sample,
633 					 struct perf_evsel *evsel)
634 {
635 	u64 read_format = evsel->attr.read_format;
636 	PyObject *values;
637 	unsigned int i;
638 
639 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
640 		pydict_set_item_string_decref(dict_sample, "time_enabled",
641 			PyLong_FromUnsignedLongLong(sample->read.time_enabled));
642 	}
643 
644 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
645 		pydict_set_item_string_decref(dict_sample, "time_running",
646 			PyLong_FromUnsignedLongLong(sample->read.time_running));
647 	}
648 
649 	if (read_format & PERF_FORMAT_GROUP)
650 		values = PyList_New(sample->read.group.nr);
651 	else
652 		values = PyList_New(1);
653 
654 	if (!values)
655 		Py_FatalError("couldn't create Python list");
656 
657 	if (read_format & PERF_FORMAT_GROUP) {
658 		for (i = 0; i < sample->read.group.nr; i++) {
659 			PyObject *t = get_sample_value_as_tuple(&sample->read.group.values[i]);
660 			PyList_SET_ITEM(values, i, t);
661 		}
662 	} else {
663 		PyObject *t = get_sample_value_as_tuple(&sample->read.one);
664 		PyList_SET_ITEM(values, 0, t);
665 	}
666 	pydict_set_item_string_decref(dict_sample, "values", values);
667 }
668 
669 static void set_sample_datasrc_in_dict(PyObject *dict,
670 				       struct perf_sample *sample)
671 {
672 	struct mem_info mi = { .data_src.val = sample->data_src };
673 	char decode[100];
674 
675 	pydict_set_item_string_decref(dict, "datasrc",
676 			PyLong_FromUnsignedLongLong(sample->data_src));
677 
678 	perf_script__meminfo_scnprintf(decode, 100, &mi);
679 
680 	pydict_set_item_string_decref(dict, "datasrc_decode",
681 			_PyUnicode_FromString(decode));
682 }
683 
684 static int regs_map(struct regs_dump *regs, uint64_t mask, char *bf, int size)
685 {
686 	unsigned int i = 0, r;
687 	int printed = 0;
688 
689 	bf[0] = 0;
690 
691 	for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
692 		u64 val = regs->regs[i++];
693 
694 		printed += scnprintf(bf + printed, size - printed,
695 				     "%5s:0x%" PRIx64 " ",
696 				     perf_reg_name(r), val);
697 	}
698 
699 	return printed;
700 }
701 
702 static void set_regs_in_dict(PyObject *dict,
703 			     struct perf_sample *sample,
704 			     struct perf_evsel *evsel)
705 {
706 	struct perf_event_attr *attr = &evsel->attr;
707 	char bf[512];
708 
709 	regs_map(&sample->intr_regs, attr->sample_regs_intr, bf, sizeof(bf));
710 
711 	pydict_set_item_string_decref(dict, "iregs",
712 			_PyUnicode_FromString(bf));
713 
714 	regs_map(&sample->user_regs, attr->sample_regs_user, bf, sizeof(bf));
715 
716 	pydict_set_item_string_decref(dict, "uregs",
717 			_PyUnicode_FromString(bf));
718 }
719 
720 static PyObject *get_perf_sample_dict(struct perf_sample *sample,
721 					 struct perf_evsel *evsel,
722 					 struct addr_location *al,
723 					 PyObject *callchain)
724 {
725 	PyObject *dict, *dict_sample, *brstack, *brstacksym;
726 
727 	dict = PyDict_New();
728 	if (!dict)
729 		Py_FatalError("couldn't create Python dictionary");
730 
731 	dict_sample = PyDict_New();
732 	if (!dict_sample)
733 		Py_FatalError("couldn't create Python dictionary");
734 
735 	pydict_set_item_string_decref(dict, "ev_name", _PyUnicode_FromString(perf_evsel__name(evsel)));
736 	pydict_set_item_string_decref(dict, "attr", _PyBytes_FromStringAndSize((const char *)&evsel->attr, sizeof(evsel->attr)));
737 
738 	pydict_set_item_string_decref(dict_sample, "pid",
739 			_PyLong_FromLong(sample->pid));
740 	pydict_set_item_string_decref(dict_sample, "tid",
741 			_PyLong_FromLong(sample->tid));
742 	pydict_set_item_string_decref(dict_sample, "cpu",
743 			_PyLong_FromLong(sample->cpu));
744 	pydict_set_item_string_decref(dict_sample, "ip",
745 			PyLong_FromUnsignedLongLong(sample->ip));
746 	pydict_set_item_string_decref(dict_sample, "time",
747 			PyLong_FromUnsignedLongLong(sample->time));
748 	pydict_set_item_string_decref(dict_sample, "period",
749 			PyLong_FromUnsignedLongLong(sample->period));
750 	pydict_set_item_string_decref(dict_sample, "phys_addr",
751 			PyLong_FromUnsignedLongLong(sample->phys_addr));
752 	pydict_set_item_string_decref(dict_sample, "addr",
753 			PyLong_FromUnsignedLongLong(sample->addr));
754 	set_sample_read_in_dict(dict_sample, sample, evsel);
755 	pydict_set_item_string_decref(dict_sample, "weight",
756 			PyLong_FromUnsignedLongLong(sample->weight));
757 	pydict_set_item_string_decref(dict_sample, "transaction",
758 			PyLong_FromUnsignedLongLong(sample->transaction));
759 	set_sample_datasrc_in_dict(dict_sample, sample);
760 	pydict_set_item_string_decref(dict, "sample", dict_sample);
761 
762 	pydict_set_item_string_decref(dict, "raw_buf", _PyBytes_FromStringAndSize(
763 			(const char *)sample->raw_data, sample->raw_size));
764 	pydict_set_item_string_decref(dict, "comm",
765 			_PyUnicode_FromString(thread__comm_str(al->thread)));
766 	if (al->map) {
767 		pydict_set_item_string_decref(dict, "dso",
768 			_PyUnicode_FromString(al->map->dso->name));
769 	}
770 	if (al->sym) {
771 		pydict_set_item_string_decref(dict, "symbol",
772 			_PyUnicode_FromString(al->sym->name));
773 	}
774 
775 	pydict_set_item_string_decref(dict, "callchain", callchain);
776 
777 	brstack = python_process_brstack(sample, al->thread);
778 	pydict_set_item_string_decref(dict, "brstack", brstack);
779 
780 	brstacksym = python_process_brstacksym(sample, al->thread);
781 	pydict_set_item_string_decref(dict, "brstacksym", brstacksym);
782 
783 	set_regs_in_dict(dict, sample, evsel);
784 
785 	return dict;
786 }
787 
788 static void python_process_tracepoint(struct perf_sample *sample,
789 				      struct perf_evsel *evsel,
790 				      struct addr_location *al)
791 {
792 	struct tep_event *event = evsel->tp_format;
793 	PyObject *handler, *context, *t, *obj = NULL, *callchain;
794 	PyObject *dict = NULL, *all_entries_dict = NULL;
795 	static char handler_name[256];
796 	struct tep_format_field *field;
797 	unsigned long s, ns;
798 	unsigned n = 0;
799 	int pid;
800 	int cpu = sample->cpu;
801 	void *data = sample->raw_data;
802 	unsigned long long nsecs = sample->time;
803 	const char *comm = thread__comm_str(al->thread);
804 	const char *default_handler_name = "trace_unhandled";
805 
806 	if (!event) {
807 		snprintf(handler_name, sizeof(handler_name),
808 			 "ug! no event found for type %" PRIu64, (u64)evsel->attr.config);
809 		Py_FatalError(handler_name);
810 	}
811 
812 	pid = raw_field_value(event, "common_pid", data);
813 
814 	sprintf(handler_name, "%s__%s", event->system, event->name);
815 
816 	if (!test_and_set_bit(event->id, events_defined))
817 		define_event_symbols(event, handler_name, event->print_fmt.args);
818 
819 	handler = get_handler(handler_name);
820 	if (!handler) {
821 		handler = get_handler(default_handler_name);
822 		if (!handler)
823 			return;
824 		dict = PyDict_New();
825 		if (!dict)
826 			Py_FatalError("couldn't create Python dict");
827 	}
828 
829 	t = PyTuple_New(MAX_FIELDS);
830 	if (!t)
831 		Py_FatalError("couldn't create Python tuple");
832 
833 
834 	s = nsecs / NSEC_PER_SEC;
835 	ns = nsecs - s * NSEC_PER_SEC;
836 
837 	scripting_context->event_data = data;
838 	scripting_context->pevent = evsel->tp_format->pevent;
839 
840 	context = _PyCapsule_New(scripting_context, NULL, NULL);
841 
842 	PyTuple_SetItem(t, n++, _PyUnicode_FromString(handler_name));
843 	PyTuple_SetItem(t, n++, context);
844 
845 	/* ip unwinding */
846 	callchain = python_process_callchain(sample, evsel, al);
847 	/* Need an additional reference for the perf_sample dict */
848 	Py_INCREF(callchain);
849 
850 	if (!dict) {
851 		PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
852 		PyTuple_SetItem(t, n++, _PyLong_FromLong(s));
853 		PyTuple_SetItem(t, n++, _PyLong_FromLong(ns));
854 		PyTuple_SetItem(t, n++, _PyLong_FromLong(pid));
855 		PyTuple_SetItem(t, n++, _PyUnicode_FromString(comm));
856 		PyTuple_SetItem(t, n++, callchain);
857 	} else {
858 		pydict_set_item_string_decref(dict, "common_cpu", _PyLong_FromLong(cpu));
859 		pydict_set_item_string_decref(dict, "common_s", _PyLong_FromLong(s));
860 		pydict_set_item_string_decref(dict, "common_ns", _PyLong_FromLong(ns));
861 		pydict_set_item_string_decref(dict, "common_pid", _PyLong_FromLong(pid));
862 		pydict_set_item_string_decref(dict, "common_comm", _PyUnicode_FromString(comm));
863 		pydict_set_item_string_decref(dict, "common_callchain", callchain);
864 	}
865 	for (field = event->format.fields; field; field = field->next) {
866 		unsigned int offset, len;
867 		unsigned long long val;
868 
869 		if (field->flags & TEP_FIELD_IS_ARRAY) {
870 			offset = field->offset;
871 			len    = field->size;
872 			if (field->flags & TEP_FIELD_IS_DYNAMIC) {
873 				val     = tep_read_number(scripting_context->pevent,
874 							  data + offset, len);
875 				offset  = val;
876 				len     = offset >> 16;
877 				offset &= 0xffff;
878 			}
879 			if (field->flags & TEP_FIELD_IS_STRING &&
880 			    is_printable_array(data + offset, len)) {
881 				obj = _PyUnicode_FromString((char *) data + offset);
882 			} else {
883 				obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
884 				field->flags &= ~TEP_FIELD_IS_STRING;
885 			}
886 		} else { /* FIELD_IS_NUMERIC */
887 			obj = get_field_numeric_entry(event, field, data);
888 		}
889 		if (!dict)
890 			PyTuple_SetItem(t, n++, obj);
891 		else
892 			pydict_set_item_string_decref(dict, field->name, obj);
893 
894 	}
895 
896 	if (dict)
897 		PyTuple_SetItem(t, n++, dict);
898 
899 	if (get_argument_count(handler) == (int) n + 1) {
900 		all_entries_dict = get_perf_sample_dict(sample, evsel, al,
901 			callchain);
902 		PyTuple_SetItem(t, n++,	all_entries_dict);
903 	} else {
904 		Py_DECREF(callchain);
905 	}
906 
907 	if (_PyTuple_Resize(&t, n) == -1)
908 		Py_FatalError("error resizing Python tuple");
909 
910 	if (!dict)
911 		call_object(handler, t, handler_name);
912 	else
913 		call_object(handler, t, default_handler_name);
914 
915 	Py_DECREF(t);
916 }
917 
918 static PyObject *tuple_new(unsigned int sz)
919 {
920 	PyObject *t;
921 
922 	t = PyTuple_New(sz);
923 	if (!t)
924 		Py_FatalError("couldn't create Python tuple");
925 	return t;
926 }
927 
928 static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
929 {
930 #if BITS_PER_LONG == 64
931 	return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
932 #endif
933 #if BITS_PER_LONG == 32
934 	return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
935 #endif
936 }
937 
938 static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
939 {
940 	return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
941 }
942 
943 static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
944 {
945 	return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
946 }
947 
948 static int python_export_evsel(struct db_export *dbe, struct perf_evsel *evsel)
949 {
950 	struct tables *tables = container_of(dbe, struct tables, dbe);
951 	PyObject *t;
952 
953 	t = tuple_new(2);
954 
955 	tuple_set_u64(t, 0, evsel->db_id);
956 	tuple_set_string(t, 1, perf_evsel__name(evsel));
957 
958 	call_object(tables->evsel_handler, t, "evsel_table");
959 
960 	Py_DECREF(t);
961 
962 	return 0;
963 }
964 
965 static int python_export_machine(struct db_export *dbe,
966 				 struct machine *machine)
967 {
968 	struct tables *tables = container_of(dbe, struct tables, dbe);
969 	PyObject *t;
970 
971 	t = tuple_new(3);
972 
973 	tuple_set_u64(t, 0, machine->db_id);
974 	tuple_set_s32(t, 1, machine->pid);
975 	tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
976 
977 	call_object(tables->machine_handler, t, "machine_table");
978 
979 	Py_DECREF(t);
980 
981 	return 0;
982 }
983 
984 static int python_export_thread(struct db_export *dbe, struct thread *thread,
985 				u64 main_thread_db_id, struct machine *machine)
986 {
987 	struct tables *tables = container_of(dbe, struct tables, dbe);
988 	PyObject *t;
989 
990 	t = tuple_new(5);
991 
992 	tuple_set_u64(t, 0, thread->db_id);
993 	tuple_set_u64(t, 1, machine->db_id);
994 	tuple_set_u64(t, 2, main_thread_db_id);
995 	tuple_set_s32(t, 3, thread->pid_);
996 	tuple_set_s32(t, 4, thread->tid);
997 
998 	call_object(tables->thread_handler, t, "thread_table");
999 
1000 	Py_DECREF(t);
1001 
1002 	return 0;
1003 }
1004 
1005 static int python_export_comm(struct db_export *dbe, struct comm *comm)
1006 {
1007 	struct tables *tables = container_of(dbe, struct tables, dbe);
1008 	PyObject *t;
1009 
1010 	t = tuple_new(2);
1011 
1012 	tuple_set_u64(t, 0, comm->db_id);
1013 	tuple_set_string(t, 1, comm__str(comm));
1014 
1015 	call_object(tables->comm_handler, t, "comm_table");
1016 
1017 	Py_DECREF(t);
1018 
1019 	return 0;
1020 }
1021 
1022 static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
1023 				     struct comm *comm, struct thread *thread)
1024 {
1025 	struct tables *tables = container_of(dbe, struct tables, dbe);
1026 	PyObject *t;
1027 
1028 	t = tuple_new(3);
1029 
1030 	tuple_set_u64(t, 0, db_id);
1031 	tuple_set_u64(t, 1, comm->db_id);
1032 	tuple_set_u64(t, 2, thread->db_id);
1033 
1034 	call_object(tables->comm_thread_handler, t, "comm_thread_table");
1035 
1036 	Py_DECREF(t);
1037 
1038 	return 0;
1039 }
1040 
1041 static int python_export_dso(struct db_export *dbe, struct dso *dso,
1042 			     struct machine *machine)
1043 {
1044 	struct tables *tables = container_of(dbe, struct tables, dbe);
1045 	char sbuild_id[SBUILD_ID_SIZE];
1046 	PyObject *t;
1047 
1048 	build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);
1049 
1050 	t = tuple_new(5);
1051 
1052 	tuple_set_u64(t, 0, dso->db_id);
1053 	tuple_set_u64(t, 1, machine->db_id);
1054 	tuple_set_string(t, 2, dso->short_name);
1055 	tuple_set_string(t, 3, dso->long_name);
1056 	tuple_set_string(t, 4, sbuild_id);
1057 
1058 	call_object(tables->dso_handler, t, "dso_table");
1059 
1060 	Py_DECREF(t);
1061 
1062 	return 0;
1063 }
1064 
1065 static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
1066 				struct dso *dso)
1067 {
1068 	struct tables *tables = container_of(dbe, struct tables, dbe);
1069 	u64 *sym_db_id = symbol__priv(sym);
1070 	PyObject *t;
1071 
1072 	t = tuple_new(6);
1073 
1074 	tuple_set_u64(t, 0, *sym_db_id);
1075 	tuple_set_u64(t, 1, dso->db_id);
1076 	tuple_set_u64(t, 2, sym->start);
1077 	tuple_set_u64(t, 3, sym->end);
1078 	tuple_set_s32(t, 4, sym->binding);
1079 	tuple_set_string(t, 5, sym->name);
1080 
1081 	call_object(tables->symbol_handler, t, "symbol_table");
1082 
1083 	Py_DECREF(t);
1084 
1085 	return 0;
1086 }
1087 
1088 static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
1089 				     const char *name)
1090 {
1091 	struct tables *tables = container_of(dbe, struct tables, dbe);
1092 	PyObject *t;
1093 
1094 	t = tuple_new(2);
1095 
1096 	tuple_set_s32(t, 0, branch_type);
1097 	tuple_set_string(t, 1, name);
1098 
1099 	call_object(tables->branch_type_handler, t, "branch_type_table");
1100 
1101 	Py_DECREF(t);
1102 
1103 	return 0;
1104 }
1105 
1106 static int python_export_sample(struct db_export *dbe,
1107 				struct export_sample *es)
1108 {
1109 	struct tables *tables = container_of(dbe, struct tables, dbe);
1110 	PyObject *t;
1111 
1112 	t = tuple_new(22);
1113 
1114 	tuple_set_u64(t, 0, es->db_id);
1115 	tuple_set_u64(t, 1, es->evsel->db_id);
1116 	tuple_set_u64(t, 2, es->al->machine->db_id);
1117 	tuple_set_u64(t, 3, es->al->thread->db_id);
1118 	tuple_set_u64(t, 4, es->comm_db_id);
1119 	tuple_set_u64(t, 5, es->dso_db_id);
1120 	tuple_set_u64(t, 6, es->sym_db_id);
1121 	tuple_set_u64(t, 7, es->offset);
1122 	tuple_set_u64(t, 8, es->sample->ip);
1123 	tuple_set_u64(t, 9, es->sample->time);
1124 	tuple_set_s32(t, 10, es->sample->cpu);
1125 	tuple_set_u64(t, 11, es->addr_dso_db_id);
1126 	tuple_set_u64(t, 12, es->addr_sym_db_id);
1127 	tuple_set_u64(t, 13, es->addr_offset);
1128 	tuple_set_u64(t, 14, es->sample->addr);
1129 	tuple_set_u64(t, 15, es->sample->period);
1130 	tuple_set_u64(t, 16, es->sample->weight);
1131 	tuple_set_u64(t, 17, es->sample->transaction);
1132 	tuple_set_u64(t, 18, es->sample->data_src);
1133 	tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
1134 	tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
1135 	tuple_set_u64(t, 21, es->call_path_id);
1136 
1137 	call_object(tables->sample_handler, t, "sample_table");
1138 
1139 	Py_DECREF(t);
1140 
1141 	return 0;
1142 }
1143 
1144 static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
1145 {
1146 	struct tables *tables = container_of(dbe, struct tables, dbe);
1147 	PyObject *t;
1148 	u64 parent_db_id, sym_db_id;
1149 
1150 	parent_db_id = cp->parent ? cp->parent->db_id : 0;
1151 	sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
1152 
1153 	t = tuple_new(4);
1154 
1155 	tuple_set_u64(t, 0, cp->db_id);
1156 	tuple_set_u64(t, 1, parent_db_id);
1157 	tuple_set_u64(t, 2, sym_db_id);
1158 	tuple_set_u64(t, 3, cp->ip);
1159 
1160 	call_object(tables->call_path_handler, t, "call_path_table");
1161 
1162 	Py_DECREF(t);
1163 
1164 	return 0;
1165 }
1166 
1167 static int python_export_call_return(struct db_export *dbe,
1168 				     struct call_return *cr)
1169 {
1170 	struct tables *tables = container_of(dbe, struct tables, dbe);
1171 	u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
1172 	PyObject *t;
1173 
1174 	t = tuple_new(11);
1175 
1176 	tuple_set_u64(t, 0, cr->db_id);
1177 	tuple_set_u64(t, 1, cr->thread->db_id);
1178 	tuple_set_u64(t, 2, comm_db_id);
1179 	tuple_set_u64(t, 3, cr->cp->db_id);
1180 	tuple_set_u64(t, 4, cr->call_time);
1181 	tuple_set_u64(t, 5, cr->return_time);
1182 	tuple_set_u64(t, 6, cr->branch_count);
1183 	tuple_set_u64(t, 7, cr->call_ref);
1184 	tuple_set_u64(t, 8, cr->return_ref);
1185 	tuple_set_u64(t, 9, cr->cp->parent->db_id);
1186 	tuple_set_s32(t, 10, cr->flags);
1187 
1188 	call_object(tables->call_return_handler, t, "call_return_table");
1189 
1190 	Py_DECREF(t);
1191 
1192 	return 0;
1193 }
1194 
1195 static int python_process_call_return(struct call_return *cr, void *data)
1196 {
1197 	struct db_export *dbe = data;
1198 
1199 	return db_export__call_return(dbe, cr);
1200 }
1201 
1202 static void python_process_general_event(struct perf_sample *sample,
1203 					 struct perf_evsel *evsel,
1204 					 struct addr_location *al)
1205 {
1206 	PyObject *handler, *t, *dict, *callchain;
1207 	static char handler_name[64];
1208 	unsigned n = 0;
1209 
1210 	snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
1211 
1212 	handler = get_handler(handler_name);
1213 	if (!handler)
1214 		return;
1215 
1216 	/*
1217 	 * Use the MAX_FIELDS to make the function expandable, though
1218 	 * currently there is only one item for the tuple.
1219 	 */
1220 	t = PyTuple_New(MAX_FIELDS);
1221 	if (!t)
1222 		Py_FatalError("couldn't create Python tuple");
1223 
1224 	/* ip unwinding */
1225 	callchain = python_process_callchain(sample, evsel, al);
1226 	dict = get_perf_sample_dict(sample, evsel, al, callchain);
1227 
1228 	PyTuple_SetItem(t, n++, dict);
1229 	if (_PyTuple_Resize(&t, n) == -1)
1230 		Py_FatalError("error resizing Python tuple");
1231 
1232 	call_object(handler, t, handler_name);
1233 
1234 	Py_DECREF(t);
1235 }
1236 
1237 static void python_process_event(union perf_event *event,
1238 				 struct perf_sample *sample,
1239 				 struct perf_evsel *evsel,
1240 				 struct addr_location *al)
1241 {
1242 	struct tables *tables = &tables_global;
1243 
1244 	switch (evsel->attr.type) {
1245 	case PERF_TYPE_TRACEPOINT:
1246 		python_process_tracepoint(sample, evsel, al);
1247 		break;
1248 	/* Reserve for future process_hw/sw/raw APIs */
1249 	default:
1250 		if (tables->db_export_mode)
1251 			db_export__sample(&tables->dbe, event, sample, evsel, al);
1252 		else
1253 			python_process_general_event(sample, evsel, al);
1254 	}
1255 }
1256 
1257 static void get_handler_name(char *str, size_t size,
1258 			     struct perf_evsel *evsel)
1259 {
1260 	char *p = str;
1261 
1262 	scnprintf(str, size, "stat__%s", perf_evsel__name(evsel));
1263 
1264 	while ((p = strchr(p, ':'))) {
1265 		*p = '_';
1266 		p++;
1267 	}
1268 }
1269 
1270 static void
1271 process_stat(struct perf_evsel *counter, int cpu, int thread, u64 tstamp,
1272 	     struct perf_counts_values *count)
1273 {
1274 	PyObject *handler, *t;
1275 	static char handler_name[256];
1276 	int n = 0;
1277 
1278 	t = PyTuple_New(MAX_FIELDS);
1279 	if (!t)
1280 		Py_FatalError("couldn't create Python tuple");
1281 
1282 	get_handler_name(handler_name, sizeof(handler_name),
1283 			 counter);
1284 
1285 	handler = get_handler(handler_name);
1286 	if (!handler) {
1287 		pr_debug("can't find python handler %s\n", handler_name);
1288 		return;
1289 	}
1290 
1291 	PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
1292 	PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
1293 
1294 	tuple_set_u64(t, n++, tstamp);
1295 	tuple_set_u64(t, n++, count->val);
1296 	tuple_set_u64(t, n++, count->ena);
1297 	tuple_set_u64(t, n++, count->run);
1298 
1299 	if (_PyTuple_Resize(&t, n) == -1)
1300 		Py_FatalError("error resizing Python tuple");
1301 
1302 	call_object(handler, t, handler_name);
1303 
1304 	Py_DECREF(t);
1305 }
1306 
1307 static void python_process_stat(struct perf_stat_config *config,
1308 				struct perf_evsel *counter, u64 tstamp)
1309 {
1310 	struct thread_map *threads = counter->threads;
1311 	struct cpu_map *cpus = counter->cpus;
1312 	int cpu, thread;
1313 
1314 	if (config->aggr_mode == AGGR_GLOBAL) {
1315 		process_stat(counter, -1, -1, tstamp,
1316 			     &counter->counts->aggr);
1317 		return;
1318 	}
1319 
1320 	for (thread = 0; thread < threads->nr; thread++) {
1321 		for (cpu = 0; cpu < cpus->nr; cpu++) {
1322 			process_stat(counter, cpus->map[cpu],
1323 				     thread_map__pid(threads, thread), tstamp,
1324 				     perf_counts(counter->counts, cpu, thread));
1325 		}
1326 	}
1327 }
1328 
1329 static void python_process_stat_interval(u64 tstamp)
1330 {
1331 	PyObject *handler, *t;
1332 	static const char handler_name[] = "stat__interval";
1333 	int n = 0;
1334 
1335 	t = PyTuple_New(MAX_FIELDS);
1336 	if (!t)
1337 		Py_FatalError("couldn't create Python tuple");
1338 
1339 	handler = get_handler(handler_name);
1340 	if (!handler) {
1341 		pr_debug("can't find python handler %s\n", handler_name);
1342 		return;
1343 	}
1344 
1345 	tuple_set_u64(t, n++, tstamp);
1346 
1347 	if (_PyTuple_Resize(&t, n) == -1)
1348 		Py_FatalError("error resizing Python tuple");
1349 
1350 	call_object(handler, t, handler_name);
1351 
1352 	Py_DECREF(t);
1353 }
1354 
1355 static int run_start_sub(void)
1356 {
1357 	main_module = PyImport_AddModule("__main__");
1358 	if (main_module == NULL)
1359 		return -1;
1360 	Py_INCREF(main_module);
1361 
1362 	main_dict = PyModule_GetDict(main_module);
1363 	if (main_dict == NULL)
1364 		goto error;
1365 	Py_INCREF(main_dict);
1366 
1367 	try_call_object("trace_begin", NULL);
1368 
1369 	return 0;
1370 
1371 error:
1372 	Py_XDECREF(main_dict);
1373 	Py_XDECREF(main_module);
1374 	return -1;
1375 }
1376 
1377 #define SET_TABLE_HANDLER_(name, handler_name, table_name) do {		\
1378 	tables->handler_name = get_handler(#table_name);		\
1379 	if (tables->handler_name)					\
1380 		tables->dbe.export_ ## name = python_export_ ## name;	\
1381 } while (0)
1382 
1383 #define SET_TABLE_HANDLER(name) \
1384 	SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
1385 
1386 static void set_table_handlers(struct tables *tables)
1387 {
1388 	const char *perf_db_export_mode = "perf_db_export_mode";
1389 	const char *perf_db_export_calls = "perf_db_export_calls";
1390 	const char *perf_db_export_callchains = "perf_db_export_callchains";
1391 	PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
1392 	bool export_calls = false;
1393 	bool export_callchains = false;
1394 	int ret;
1395 
1396 	memset(tables, 0, sizeof(struct tables));
1397 	if (db_export__init(&tables->dbe))
1398 		Py_FatalError("failed to initialize export");
1399 
1400 	db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
1401 	if (!db_export_mode)
1402 		return;
1403 
1404 	ret = PyObject_IsTrue(db_export_mode);
1405 	if (ret == -1)
1406 		handler_call_die(perf_db_export_mode);
1407 	if (!ret)
1408 		return;
1409 
1410 	/* handle export calls */
1411 	tables->dbe.crp = NULL;
1412 	db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
1413 	if (db_export_calls) {
1414 		ret = PyObject_IsTrue(db_export_calls);
1415 		if (ret == -1)
1416 			handler_call_die(perf_db_export_calls);
1417 		export_calls = !!ret;
1418 	}
1419 
1420 	if (export_calls) {
1421 		tables->dbe.crp =
1422 			call_return_processor__new(python_process_call_return,
1423 						   &tables->dbe);
1424 		if (!tables->dbe.crp)
1425 			Py_FatalError("failed to create calls processor");
1426 	}
1427 
1428 	/* handle export callchains */
1429 	tables->dbe.cpr = NULL;
1430 	db_export_callchains = PyDict_GetItemString(main_dict,
1431 						    perf_db_export_callchains);
1432 	if (db_export_callchains) {
1433 		ret = PyObject_IsTrue(db_export_callchains);
1434 		if (ret == -1)
1435 			handler_call_die(perf_db_export_callchains);
1436 		export_callchains = !!ret;
1437 	}
1438 
1439 	if (export_callchains) {
1440 		/*
1441 		 * Attempt to use the call path root from the call return
1442 		 * processor, if the call return processor is in use. Otherwise,
1443 		 * we allocate a new call path root. This prevents exporting
1444 		 * duplicate call path ids when both are in use simultaniously.
1445 		 */
1446 		if (tables->dbe.crp)
1447 			tables->dbe.cpr = tables->dbe.crp->cpr;
1448 		else
1449 			tables->dbe.cpr = call_path_root__new();
1450 
1451 		if (!tables->dbe.cpr)
1452 			Py_FatalError("failed to create call path root");
1453 	}
1454 
1455 	tables->db_export_mode = true;
1456 	/*
1457 	 * Reserve per symbol space for symbol->db_id via symbol__priv()
1458 	 */
1459 	symbol_conf.priv_size = sizeof(u64);
1460 
1461 	SET_TABLE_HANDLER(evsel);
1462 	SET_TABLE_HANDLER(machine);
1463 	SET_TABLE_HANDLER(thread);
1464 	SET_TABLE_HANDLER(comm);
1465 	SET_TABLE_HANDLER(comm_thread);
1466 	SET_TABLE_HANDLER(dso);
1467 	SET_TABLE_HANDLER(symbol);
1468 	SET_TABLE_HANDLER(branch_type);
1469 	SET_TABLE_HANDLER(sample);
1470 	SET_TABLE_HANDLER(call_path);
1471 	SET_TABLE_HANDLER(call_return);
1472 }
1473 
1474 #if PY_MAJOR_VERSION < 3
1475 static void _free_command_line(const char **command_line, int num)
1476 {
1477 	free(command_line);
1478 }
1479 #else
1480 static void _free_command_line(wchar_t **command_line, int num)
1481 {
1482 	int i;
1483 	for (i = 0; i < num; i++)
1484 		PyMem_RawFree(command_line[i]);
1485 	free(command_line);
1486 }
1487 #endif
1488 
1489 
1490 /*
1491  * Start trace script
1492  */
1493 static int python_start_script(const char *script, int argc, const char **argv)
1494 {
1495 	struct tables *tables = &tables_global;
1496 	PyMODINIT_FUNC (*initfunc)(void);
1497 #if PY_MAJOR_VERSION < 3
1498 	const char **command_line;
1499 #else
1500 	wchar_t **command_line;
1501 #endif
1502 	/*
1503 	 * Use a non-const name variable to cope with python 2.6's
1504 	 * PyImport_AppendInittab prototype
1505 	 */
1506 	char buf[PATH_MAX], name[19] = "perf_trace_context";
1507 	int i, err = 0;
1508 	FILE *fp;
1509 
1510 #if PY_MAJOR_VERSION < 3
1511 	initfunc = initperf_trace_context;
1512 	command_line = malloc((argc + 1) * sizeof(const char *));
1513 	command_line[0] = script;
1514 	for (i = 1; i < argc + 1; i++)
1515 		command_line[i] = argv[i - 1];
1516 #else
1517 	initfunc = PyInit_perf_trace_context;
1518 	command_line = malloc((argc + 1) * sizeof(wchar_t *));
1519 	command_line[0] = Py_DecodeLocale(script, NULL);
1520 	for (i = 1; i < argc + 1; i++)
1521 		command_line[i] = Py_DecodeLocale(argv[i - 1], NULL);
1522 #endif
1523 
1524 	PyImport_AppendInittab(name, initfunc);
1525 	Py_Initialize();
1526 
1527 #if PY_MAJOR_VERSION < 3
1528 	PySys_SetArgv(argc + 1, (char **)command_line);
1529 #else
1530 	PySys_SetArgv(argc + 1, command_line);
1531 #endif
1532 
1533 	fp = fopen(script, "r");
1534 	if (!fp) {
1535 		sprintf(buf, "Can't open python script \"%s\"", script);
1536 		perror(buf);
1537 		err = -1;
1538 		goto error;
1539 	}
1540 
1541 	err = PyRun_SimpleFile(fp, script);
1542 	if (err) {
1543 		fprintf(stderr, "Error running python script %s\n", script);
1544 		goto error;
1545 	}
1546 
1547 	err = run_start_sub();
1548 	if (err) {
1549 		fprintf(stderr, "Error starting python script %s\n", script);
1550 		goto error;
1551 	}
1552 
1553 	set_table_handlers(tables);
1554 
1555 	if (tables->db_export_mode) {
1556 		err = db_export__branch_types(&tables->dbe);
1557 		if (err)
1558 			goto error;
1559 	}
1560 
1561 	_free_command_line(command_line, argc + 1);
1562 
1563 	return err;
1564 error:
1565 	Py_Finalize();
1566 	_free_command_line(command_line, argc + 1);
1567 
1568 	return err;
1569 }
1570 
1571 static int python_flush_script(void)
1572 {
1573 	struct tables *tables = &tables_global;
1574 
1575 	return db_export__flush(&tables->dbe);
1576 }
1577 
1578 /*
1579  * Stop trace script
1580  */
1581 static int python_stop_script(void)
1582 {
1583 	struct tables *tables = &tables_global;
1584 
1585 	try_call_object("trace_end", NULL);
1586 
1587 	db_export__exit(&tables->dbe);
1588 
1589 	Py_XDECREF(main_dict);
1590 	Py_XDECREF(main_module);
1591 	Py_Finalize();
1592 
1593 	return 0;
1594 }
1595 
1596 static int python_generate_script(struct tep_handle *pevent, const char *outfile)
1597 {
1598 	struct tep_event *event = NULL;
1599 	struct tep_format_field *f;
1600 	char fname[PATH_MAX];
1601 	int not_first, count;
1602 	FILE *ofp;
1603 
1604 	sprintf(fname, "%s.py", outfile);
1605 	ofp = fopen(fname, "w");
1606 	if (ofp == NULL) {
1607 		fprintf(stderr, "couldn't open %s\n", fname);
1608 		return -1;
1609 	}
1610 	fprintf(ofp, "# perf script event handlers, "
1611 		"generated by perf script -g python\n");
1612 
1613 	fprintf(ofp, "# Licensed under the terms of the GNU GPL"
1614 		" License version 2\n\n");
1615 
1616 	fprintf(ofp, "# The common_* event handler fields are the most useful "
1617 		"fields common to\n");
1618 
1619 	fprintf(ofp, "# all events.  They don't necessarily correspond to "
1620 		"the 'common_*' fields\n");
1621 
1622 	fprintf(ofp, "# in the format files.  Those fields not available as "
1623 		"handler params can\n");
1624 
1625 	fprintf(ofp, "# be retrieved using Python functions of the form "
1626 		"common_*(context).\n");
1627 
1628 	fprintf(ofp, "# See the perf-script-python Documentation for the list "
1629 		"of available functions.\n\n");
1630 
1631 	fprintf(ofp, "from __future__ import print_function\n\n");
1632 	fprintf(ofp, "import os\n");
1633 	fprintf(ofp, "import sys\n\n");
1634 
1635 	fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
1636 	fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
1637 	fprintf(ofp, "\nfrom perf_trace_context import *\n");
1638 	fprintf(ofp, "from Core import *\n\n\n");
1639 
1640 	fprintf(ofp, "def trace_begin():\n");
1641 	fprintf(ofp, "\tprint(\"in trace_begin\")\n\n");
1642 
1643 	fprintf(ofp, "def trace_end():\n");
1644 	fprintf(ofp, "\tprint(\"in trace_end\")\n\n");
1645 
1646 	while ((event = trace_find_next_event(pevent, event))) {
1647 		fprintf(ofp, "def %s__%s(", event->system, event->name);
1648 		fprintf(ofp, "event_name, ");
1649 		fprintf(ofp, "context, ");
1650 		fprintf(ofp, "common_cpu,\n");
1651 		fprintf(ofp, "\tcommon_secs, ");
1652 		fprintf(ofp, "common_nsecs, ");
1653 		fprintf(ofp, "common_pid, ");
1654 		fprintf(ofp, "common_comm,\n\t");
1655 		fprintf(ofp, "common_callchain, ");
1656 
1657 		not_first = 0;
1658 		count = 0;
1659 
1660 		for (f = event->format.fields; f; f = f->next) {
1661 			if (not_first++)
1662 				fprintf(ofp, ", ");
1663 			if (++count % 5 == 0)
1664 				fprintf(ofp, "\n\t");
1665 
1666 			fprintf(ofp, "%s", f->name);
1667 		}
1668 		if (not_first++)
1669 			fprintf(ofp, ", ");
1670 		if (++count % 5 == 0)
1671 			fprintf(ofp, "\n\t\t");
1672 		fprintf(ofp, "perf_sample_dict");
1673 
1674 		fprintf(ofp, "):\n");
1675 
1676 		fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
1677 			"common_secs, common_nsecs,\n\t\t\t"
1678 			"common_pid, common_comm)\n\n");
1679 
1680 		fprintf(ofp, "\t\tprint(\"");
1681 
1682 		not_first = 0;
1683 		count = 0;
1684 
1685 		for (f = event->format.fields; f; f = f->next) {
1686 			if (not_first++)
1687 				fprintf(ofp, ", ");
1688 			if (count && count % 3 == 0) {
1689 				fprintf(ofp, "\" \\\n\t\t\"");
1690 			}
1691 			count++;
1692 
1693 			fprintf(ofp, "%s=", f->name);
1694 			if (f->flags & TEP_FIELD_IS_STRING ||
1695 			    f->flags & TEP_FIELD_IS_FLAG ||
1696 			    f->flags & TEP_FIELD_IS_ARRAY ||
1697 			    f->flags & TEP_FIELD_IS_SYMBOLIC)
1698 				fprintf(ofp, "%%s");
1699 			else if (f->flags & TEP_FIELD_IS_SIGNED)
1700 				fprintf(ofp, "%%d");
1701 			else
1702 				fprintf(ofp, "%%u");
1703 		}
1704 
1705 		fprintf(ofp, "\" %% \\\n\t\t(");
1706 
1707 		not_first = 0;
1708 		count = 0;
1709 
1710 		for (f = event->format.fields; f; f = f->next) {
1711 			if (not_first++)
1712 				fprintf(ofp, ", ");
1713 
1714 			if (++count % 5 == 0)
1715 				fprintf(ofp, "\n\t\t");
1716 
1717 			if (f->flags & TEP_FIELD_IS_FLAG) {
1718 				if ((count - 1) % 5 != 0) {
1719 					fprintf(ofp, "\n\t\t");
1720 					count = 4;
1721 				}
1722 				fprintf(ofp, "flag_str(\"");
1723 				fprintf(ofp, "%s__%s\", ", event->system,
1724 					event->name);
1725 				fprintf(ofp, "\"%s\", %s)", f->name,
1726 					f->name);
1727 			} else if (f->flags & TEP_FIELD_IS_SYMBOLIC) {
1728 				if ((count - 1) % 5 != 0) {
1729 					fprintf(ofp, "\n\t\t");
1730 					count = 4;
1731 				}
1732 				fprintf(ofp, "symbol_str(\"");
1733 				fprintf(ofp, "%s__%s\", ", event->system,
1734 					event->name);
1735 				fprintf(ofp, "\"%s\", %s)", f->name,
1736 					f->name);
1737 			} else
1738 				fprintf(ofp, "%s", f->name);
1739 		}
1740 
1741 		fprintf(ofp, "))\n\n");
1742 
1743 		fprintf(ofp, "\t\tprint('Sample: {'+"
1744 			"get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
1745 
1746 		fprintf(ofp, "\t\tfor node in common_callchain:");
1747 		fprintf(ofp, "\n\t\t\tif 'sym' in node:");
1748 		fprintf(ofp, "\n\t\t\t\tprint(\"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name']))");
1749 		fprintf(ofp, "\n\t\t\telse:");
1750 		fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x]\" %% (node['ip']))\n\n");
1751 		fprintf(ofp, "\t\tprint()\n\n");
1752 
1753 	}
1754 
1755 	fprintf(ofp, "def trace_unhandled(event_name, context, "
1756 		"event_fields_dict, perf_sample_dict):\n");
1757 
1758 	fprintf(ofp, "\t\tprint(get_dict_as_string(event_fields_dict))\n");
1759 	fprintf(ofp, "\t\tprint('Sample: {'+"
1760 		"get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
1761 
1762 	fprintf(ofp, "def print_header("
1763 		"event_name, cpu, secs, nsecs, pid, comm):\n"
1764 		"\tprint(\"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
1765 		"(event_name, cpu, secs, nsecs, pid, comm), end=\"\")\n\n");
1766 
1767 	fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
1768 		"\treturn delimiter.join"
1769 		"(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
1770 
1771 	fclose(ofp);
1772 
1773 	fprintf(stderr, "generated Python script: %s\n", fname);
1774 
1775 	return 0;
1776 }
1777 
1778 struct scripting_ops python_scripting_ops = {
1779 	.name			= "Python",
1780 	.start_script		= python_start_script,
1781 	.flush_script		= python_flush_script,
1782 	.stop_script		= python_stop_script,
1783 	.process_event		= python_process_event,
1784 	.process_stat		= python_process_stat,
1785 	.process_stat_interval	= python_process_stat_interval,
1786 	.generate_script	= python_generate_script,
1787 };
1788