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