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