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 	set_sample_read_in_dict(dict_sample, sample, evsel);
535 	pydict_set_item_string_decref(dict, "sample", dict_sample);
536 
537 	pydict_set_item_string_decref(dict, "raw_buf", _PyBytes_FromStringAndSize(
538 			(const char *)sample->raw_data, sample->raw_size));
539 	pydict_set_item_string_decref(dict, "comm",
540 			_PyUnicode_FromString(thread__comm_str(al->thread)));
541 	if (al->map) {
542 		pydict_set_item_string_decref(dict, "dso",
543 			_PyUnicode_FromString(al->map->dso->name));
544 	}
545 	if (al->sym) {
546 		pydict_set_item_string_decref(dict, "symbol",
547 			_PyUnicode_FromString(al->sym->name));
548 	}
549 
550 	pydict_set_item_string_decref(dict, "callchain", callchain);
551 
552 	return dict;
553 }
554 
555 static void python_process_tracepoint(struct perf_sample *sample,
556 				      struct perf_evsel *evsel,
557 				      struct addr_location *al)
558 {
559 	struct event_format *event = evsel->tp_format;
560 	PyObject *handler, *context, *t, *obj = NULL, *callchain;
561 	PyObject *dict = NULL, *all_entries_dict = NULL;
562 	static char handler_name[256];
563 	struct format_field *field;
564 	unsigned long s, ns;
565 	unsigned n = 0;
566 	int pid;
567 	int cpu = sample->cpu;
568 	void *data = sample->raw_data;
569 	unsigned long long nsecs = sample->time;
570 	const char *comm = thread__comm_str(al->thread);
571 	const char *default_handler_name = "trace_unhandled";
572 
573 	if (!event) {
574 		snprintf(handler_name, sizeof(handler_name),
575 			 "ug! no event found for type %" PRIu64, (u64)evsel->attr.config);
576 		Py_FatalError(handler_name);
577 	}
578 
579 	pid = raw_field_value(event, "common_pid", data);
580 
581 	sprintf(handler_name, "%s__%s", event->system, event->name);
582 
583 	if (!test_and_set_bit(event->id, events_defined))
584 		define_event_symbols(event, handler_name, event->print_fmt.args);
585 
586 	handler = get_handler(handler_name);
587 	if (!handler) {
588 		handler = get_handler(default_handler_name);
589 		if (!handler)
590 			return;
591 		dict = PyDict_New();
592 		if (!dict)
593 			Py_FatalError("couldn't create Python dict");
594 	}
595 
596 	t = PyTuple_New(MAX_FIELDS);
597 	if (!t)
598 		Py_FatalError("couldn't create Python tuple");
599 
600 
601 	s = nsecs / NSEC_PER_SEC;
602 	ns = nsecs - s * NSEC_PER_SEC;
603 
604 	scripting_context->event_data = data;
605 	scripting_context->pevent = evsel->tp_format->pevent;
606 
607 	context = _PyCapsule_New(scripting_context, NULL, NULL);
608 
609 	PyTuple_SetItem(t, n++, _PyUnicode_FromString(handler_name));
610 	PyTuple_SetItem(t, n++, context);
611 
612 	/* ip unwinding */
613 	callchain = python_process_callchain(sample, evsel, al);
614 	/* Need an additional reference for the perf_sample dict */
615 	Py_INCREF(callchain);
616 
617 	if (!dict) {
618 		PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
619 		PyTuple_SetItem(t, n++, _PyLong_FromLong(s));
620 		PyTuple_SetItem(t, n++, _PyLong_FromLong(ns));
621 		PyTuple_SetItem(t, n++, _PyLong_FromLong(pid));
622 		PyTuple_SetItem(t, n++, _PyUnicode_FromString(comm));
623 		PyTuple_SetItem(t, n++, callchain);
624 	} else {
625 		pydict_set_item_string_decref(dict, "common_cpu", _PyLong_FromLong(cpu));
626 		pydict_set_item_string_decref(dict, "common_s", _PyLong_FromLong(s));
627 		pydict_set_item_string_decref(dict, "common_ns", _PyLong_FromLong(ns));
628 		pydict_set_item_string_decref(dict, "common_pid", _PyLong_FromLong(pid));
629 		pydict_set_item_string_decref(dict, "common_comm", _PyUnicode_FromString(comm));
630 		pydict_set_item_string_decref(dict, "common_callchain", callchain);
631 	}
632 	for (field = event->format.fields; field; field = field->next) {
633 		unsigned int offset, len;
634 		unsigned long long val;
635 
636 		if (field->flags & FIELD_IS_ARRAY) {
637 			offset = field->offset;
638 			len    = field->size;
639 			if (field->flags & FIELD_IS_DYNAMIC) {
640 				val     = pevent_read_number(scripting_context->pevent,
641 							     data + offset, len);
642 				offset  = val;
643 				len     = offset >> 16;
644 				offset &= 0xffff;
645 			}
646 			if (field->flags & FIELD_IS_STRING &&
647 			    is_printable_array(data + offset, len)) {
648 				obj = _PyUnicode_FromString((char *) data + offset);
649 			} else {
650 				obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
651 				field->flags &= ~FIELD_IS_STRING;
652 			}
653 		} else { /* FIELD_IS_NUMERIC */
654 			obj = get_field_numeric_entry(event, field, data);
655 		}
656 		if (!dict)
657 			PyTuple_SetItem(t, n++, obj);
658 		else
659 			pydict_set_item_string_decref(dict, field->name, obj);
660 
661 	}
662 
663 	if (dict)
664 		PyTuple_SetItem(t, n++, dict);
665 
666 	if (get_argument_count(handler) == (int) n + 1) {
667 		all_entries_dict = get_perf_sample_dict(sample, evsel, al,
668 			callchain);
669 		PyTuple_SetItem(t, n++,	all_entries_dict);
670 	} else {
671 		Py_DECREF(callchain);
672 	}
673 
674 	if (_PyTuple_Resize(&t, n) == -1)
675 		Py_FatalError("error resizing Python tuple");
676 
677 	if (!dict) {
678 		call_object(handler, t, handler_name);
679 	} else {
680 		call_object(handler, t, default_handler_name);
681 		Py_DECREF(dict);
682 	}
683 
684 	Py_XDECREF(all_entries_dict);
685 	Py_DECREF(t);
686 }
687 
688 static PyObject *tuple_new(unsigned int sz)
689 {
690 	PyObject *t;
691 
692 	t = PyTuple_New(sz);
693 	if (!t)
694 		Py_FatalError("couldn't create Python tuple");
695 	return t;
696 }
697 
698 static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
699 {
700 #if BITS_PER_LONG == 64
701 	return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
702 #endif
703 #if BITS_PER_LONG == 32
704 	return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
705 #endif
706 }
707 
708 static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
709 {
710 	return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
711 }
712 
713 static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
714 {
715 	return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
716 }
717 
718 static int python_export_evsel(struct db_export *dbe, struct perf_evsel *evsel)
719 {
720 	struct tables *tables = container_of(dbe, struct tables, dbe);
721 	PyObject *t;
722 
723 	t = tuple_new(2);
724 
725 	tuple_set_u64(t, 0, evsel->db_id);
726 	tuple_set_string(t, 1, perf_evsel__name(evsel));
727 
728 	call_object(tables->evsel_handler, t, "evsel_table");
729 
730 	Py_DECREF(t);
731 
732 	return 0;
733 }
734 
735 static int python_export_machine(struct db_export *dbe,
736 				 struct machine *machine)
737 {
738 	struct tables *tables = container_of(dbe, struct tables, dbe);
739 	PyObject *t;
740 
741 	t = tuple_new(3);
742 
743 	tuple_set_u64(t, 0, machine->db_id);
744 	tuple_set_s32(t, 1, machine->pid);
745 	tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
746 
747 	call_object(tables->machine_handler, t, "machine_table");
748 
749 	Py_DECREF(t);
750 
751 	return 0;
752 }
753 
754 static int python_export_thread(struct db_export *dbe, struct thread *thread,
755 				u64 main_thread_db_id, struct machine *machine)
756 {
757 	struct tables *tables = container_of(dbe, struct tables, dbe);
758 	PyObject *t;
759 
760 	t = tuple_new(5);
761 
762 	tuple_set_u64(t, 0, thread->db_id);
763 	tuple_set_u64(t, 1, machine->db_id);
764 	tuple_set_u64(t, 2, main_thread_db_id);
765 	tuple_set_s32(t, 3, thread->pid_);
766 	tuple_set_s32(t, 4, thread->tid);
767 
768 	call_object(tables->thread_handler, t, "thread_table");
769 
770 	Py_DECREF(t);
771 
772 	return 0;
773 }
774 
775 static int python_export_comm(struct db_export *dbe, struct comm *comm)
776 {
777 	struct tables *tables = container_of(dbe, struct tables, dbe);
778 	PyObject *t;
779 
780 	t = tuple_new(2);
781 
782 	tuple_set_u64(t, 0, comm->db_id);
783 	tuple_set_string(t, 1, comm__str(comm));
784 
785 	call_object(tables->comm_handler, t, "comm_table");
786 
787 	Py_DECREF(t);
788 
789 	return 0;
790 }
791 
792 static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
793 				     struct comm *comm, struct thread *thread)
794 {
795 	struct tables *tables = container_of(dbe, struct tables, dbe);
796 	PyObject *t;
797 
798 	t = tuple_new(3);
799 
800 	tuple_set_u64(t, 0, db_id);
801 	tuple_set_u64(t, 1, comm->db_id);
802 	tuple_set_u64(t, 2, thread->db_id);
803 
804 	call_object(tables->comm_thread_handler, t, "comm_thread_table");
805 
806 	Py_DECREF(t);
807 
808 	return 0;
809 }
810 
811 static int python_export_dso(struct db_export *dbe, struct dso *dso,
812 			     struct machine *machine)
813 {
814 	struct tables *tables = container_of(dbe, struct tables, dbe);
815 	char sbuild_id[SBUILD_ID_SIZE];
816 	PyObject *t;
817 
818 	build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);
819 
820 	t = tuple_new(5);
821 
822 	tuple_set_u64(t, 0, dso->db_id);
823 	tuple_set_u64(t, 1, machine->db_id);
824 	tuple_set_string(t, 2, dso->short_name);
825 	tuple_set_string(t, 3, dso->long_name);
826 	tuple_set_string(t, 4, sbuild_id);
827 
828 	call_object(tables->dso_handler, t, "dso_table");
829 
830 	Py_DECREF(t);
831 
832 	return 0;
833 }
834 
835 static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
836 				struct dso *dso)
837 {
838 	struct tables *tables = container_of(dbe, struct tables, dbe);
839 	u64 *sym_db_id = symbol__priv(sym);
840 	PyObject *t;
841 
842 	t = tuple_new(6);
843 
844 	tuple_set_u64(t, 0, *sym_db_id);
845 	tuple_set_u64(t, 1, dso->db_id);
846 	tuple_set_u64(t, 2, sym->start);
847 	tuple_set_u64(t, 3, sym->end);
848 	tuple_set_s32(t, 4, sym->binding);
849 	tuple_set_string(t, 5, sym->name);
850 
851 	call_object(tables->symbol_handler, t, "symbol_table");
852 
853 	Py_DECREF(t);
854 
855 	return 0;
856 }
857 
858 static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
859 				     const char *name)
860 {
861 	struct tables *tables = container_of(dbe, struct tables, dbe);
862 	PyObject *t;
863 
864 	t = tuple_new(2);
865 
866 	tuple_set_s32(t, 0, branch_type);
867 	tuple_set_string(t, 1, name);
868 
869 	call_object(tables->branch_type_handler, t, "branch_type_table");
870 
871 	Py_DECREF(t);
872 
873 	return 0;
874 }
875 
876 static int python_export_sample(struct db_export *dbe,
877 				struct export_sample *es)
878 {
879 	struct tables *tables = container_of(dbe, struct tables, dbe);
880 	PyObject *t;
881 
882 	t = tuple_new(22);
883 
884 	tuple_set_u64(t, 0, es->db_id);
885 	tuple_set_u64(t, 1, es->evsel->db_id);
886 	tuple_set_u64(t, 2, es->al->machine->db_id);
887 	tuple_set_u64(t, 3, es->al->thread->db_id);
888 	tuple_set_u64(t, 4, es->comm_db_id);
889 	tuple_set_u64(t, 5, es->dso_db_id);
890 	tuple_set_u64(t, 6, es->sym_db_id);
891 	tuple_set_u64(t, 7, es->offset);
892 	tuple_set_u64(t, 8, es->sample->ip);
893 	tuple_set_u64(t, 9, es->sample->time);
894 	tuple_set_s32(t, 10, es->sample->cpu);
895 	tuple_set_u64(t, 11, es->addr_dso_db_id);
896 	tuple_set_u64(t, 12, es->addr_sym_db_id);
897 	tuple_set_u64(t, 13, es->addr_offset);
898 	tuple_set_u64(t, 14, es->sample->addr);
899 	tuple_set_u64(t, 15, es->sample->period);
900 	tuple_set_u64(t, 16, es->sample->weight);
901 	tuple_set_u64(t, 17, es->sample->transaction);
902 	tuple_set_u64(t, 18, es->sample->data_src);
903 	tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
904 	tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
905 	tuple_set_u64(t, 21, es->call_path_id);
906 
907 	call_object(tables->sample_handler, t, "sample_table");
908 
909 	Py_DECREF(t);
910 
911 	return 0;
912 }
913 
914 static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
915 {
916 	struct tables *tables = container_of(dbe, struct tables, dbe);
917 	PyObject *t;
918 	u64 parent_db_id, sym_db_id;
919 
920 	parent_db_id = cp->parent ? cp->parent->db_id : 0;
921 	sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
922 
923 	t = tuple_new(4);
924 
925 	tuple_set_u64(t, 0, cp->db_id);
926 	tuple_set_u64(t, 1, parent_db_id);
927 	tuple_set_u64(t, 2, sym_db_id);
928 	tuple_set_u64(t, 3, cp->ip);
929 
930 	call_object(tables->call_path_handler, t, "call_path_table");
931 
932 	Py_DECREF(t);
933 
934 	return 0;
935 }
936 
937 static int python_export_call_return(struct db_export *dbe,
938 				     struct call_return *cr)
939 {
940 	struct tables *tables = container_of(dbe, struct tables, dbe);
941 	u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
942 	PyObject *t;
943 
944 	t = tuple_new(11);
945 
946 	tuple_set_u64(t, 0, cr->db_id);
947 	tuple_set_u64(t, 1, cr->thread->db_id);
948 	tuple_set_u64(t, 2, comm_db_id);
949 	tuple_set_u64(t, 3, cr->cp->db_id);
950 	tuple_set_u64(t, 4, cr->call_time);
951 	tuple_set_u64(t, 5, cr->return_time);
952 	tuple_set_u64(t, 6, cr->branch_count);
953 	tuple_set_u64(t, 7, cr->call_ref);
954 	tuple_set_u64(t, 8, cr->return_ref);
955 	tuple_set_u64(t, 9, cr->cp->parent->db_id);
956 	tuple_set_s32(t, 10, cr->flags);
957 
958 	call_object(tables->call_return_handler, t, "call_return_table");
959 
960 	Py_DECREF(t);
961 
962 	return 0;
963 }
964 
965 static int python_process_call_return(struct call_return *cr, void *data)
966 {
967 	struct db_export *dbe = data;
968 
969 	return db_export__call_return(dbe, cr);
970 }
971 
972 static void python_process_general_event(struct perf_sample *sample,
973 					 struct perf_evsel *evsel,
974 					 struct addr_location *al)
975 {
976 	PyObject *handler, *t, *dict, *callchain;
977 	static char handler_name[64];
978 	unsigned n = 0;
979 
980 	snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
981 
982 	handler = get_handler(handler_name);
983 	if (!handler)
984 		return;
985 
986 	/*
987 	 * Use the MAX_FIELDS to make the function expandable, though
988 	 * currently there is only one item for the tuple.
989 	 */
990 	t = PyTuple_New(MAX_FIELDS);
991 	if (!t)
992 		Py_FatalError("couldn't create Python tuple");
993 
994 	/* ip unwinding */
995 	callchain = python_process_callchain(sample, evsel, al);
996 	dict = get_perf_sample_dict(sample, evsel, al, callchain);
997 
998 	PyTuple_SetItem(t, n++, dict);
999 	if (_PyTuple_Resize(&t, n) == -1)
1000 		Py_FatalError("error resizing Python tuple");
1001 
1002 	call_object(handler, t, handler_name);
1003 
1004 	Py_DECREF(dict);
1005 	Py_DECREF(t);
1006 }
1007 
1008 static void python_process_event(union perf_event *event,
1009 				 struct perf_sample *sample,
1010 				 struct perf_evsel *evsel,
1011 				 struct addr_location *al)
1012 {
1013 	struct tables *tables = &tables_global;
1014 
1015 	switch (evsel->attr.type) {
1016 	case PERF_TYPE_TRACEPOINT:
1017 		python_process_tracepoint(sample, evsel, al);
1018 		break;
1019 	/* Reserve for future process_hw/sw/raw APIs */
1020 	default:
1021 		if (tables->db_export_mode)
1022 			db_export__sample(&tables->dbe, event, sample, evsel, al);
1023 		else
1024 			python_process_general_event(sample, evsel, al);
1025 	}
1026 }
1027 
1028 static void get_handler_name(char *str, size_t size,
1029 			     struct perf_evsel *evsel)
1030 {
1031 	char *p = str;
1032 
1033 	scnprintf(str, size, "stat__%s", perf_evsel__name(evsel));
1034 
1035 	while ((p = strchr(p, ':'))) {
1036 		*p = '_';
1037 		p++;
1038 	}
1039 }
1040 
1041 static void
1042 process_stat(struct perf_evsel *counter, int cpu, int thread, u64 tstamp,
1043 	     struct perf_counts_values *count)
1044 {
1045 	PyObject *handler, *t;
1046 	static char handler_name[256];
1047 	int n = 0;
1048 
1049 	t = PyTuple_New(MAX_FIELDS);
1050 	if (!t)
1051 		Py_FatalError("couldn't create Python tuple");
1052 
1053 	get_handler_name(handler_name, sizeof(handler_name),
1054 			 counter);
1055 
1056 	handler = get_handler(handler_name);
1057 	if (!handler) {
1058 		pr_debug("can't find python handler %s\n", handler_name);
1059 		return;
1060 	}
1061 
1062 	PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
1063 	PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
1064 
1065 	tuple_set_u64(t, n++, tstamp);
1066 	tuple_set_u64(t, n++, count->val);
1067 	tuple_set_u64(t, n++, count->ena);
1068 	tuple_set_u64(t, n++, count->run);
1069 
1070 	if (_PyTuple_Resize(&t, n) == -1)
1071 		Py_FatalError("error resizing Python tuple");
1072 
1073 	call_object(handler, t, handler_name);
1074 
1075 	Py_DECREF(t);
1076 }
1077 
1078 static void python_process_stat(struct perf_stat_config *config,
1079 				struct perf_evsel *counter, u64 tstamp)
1080 {
1081 	struct thread_map *threads = counter->threads;
1082 	struct cpu_map *cpus = counter->cpus;
1083 	int cpu, thread;
1084 
1085 	if (config->aggr_mode == AGGR_GLOBAL) {
1086 		process_stat(counter, -1, -1, tstamp,
1087 			     &counter->counts->aggr);
1088 		return;
1089 	}
1090 
1091 	for (thread = 0; thread < threads->nr; thread++) {
1092 		for (cpu = 0; cpu < cpus->nr; cpu++) {
1093 			process_stat(counter, cpus->map[cpu],
1094 				     thread_map__pid(threads, thread), tstamp,
1095 				     perf_counts(counter->counts, cpu, thread));
1096 		}
1097 	}
1098 }
1099 
1100 static void python_process_stat_interval(u64 tstamp)
1101 {
1102 	PyObject *handler, *t;
1103 	static const char handler_name[] = "stat__interval";
1104 	int n = 0;
1105 
1106 	t = PyTuple_New(MAX_FIELDS);
1107 	if (!t)
1108 		Py_FatalError("couldn't create Python tuple");
1109 
1110 	handler = get_handler(handler_name);
1111 	if (!handler) {
1112 		pr_debug("can't find python handler %s\n", handler_name);
1113 		return;
1114 	}
1115 
1116 	tuple_set_u64(t, n++, tstamp);
1117 
1118 	if (_PyTuple_Resize(&t, n) == -1)
1119 		Py_FatalError("error resizing Python tuple");
1120 
1121 	call_object(handler, t, handler_name);
1122 
1123 	Py_DECREF(t);
1124 }
1125 
1126 static int run_start_sub(void)
1127 {
1128 	main_module = PyImport_AddModule("__main__");
1129 	if (main_module == NULL)
1130 		return -1;
1131 	Py_INCREF(main_module);
1132 
1133 	main_dict = PyModule_GetDict(main_module);
1134 	if (main_dict == NULL)
1135 		goto error;
1136 	Py_INCREF(main_dict);
1137 
1138 	try_call_object("trace_begin", NULL);
1139 
1140 	return 0;
1141 
1142 error:
1143 	Py_XDECREF(main_dict);
1144 	Py_XDECREF(main_module);
1145 	return -1;
1146 }
1147 
1148 #define SET_TABLE_HANDLER_(name, handler_name, table_name) do {		\
1149 	tables->handler_name = get_handler(#table_name);		\
1150 	if (tables->handler_name)					\
1151 		tables->dbe.export_ ## name = python_export_ ## name;	\
1152 } while (0)
1153 
1154 #define SET_TABLE_HANDLER(name) \
1155 	SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
1156 
1157 static void set_table_handlers(struct tables *tables)
1158 {
1159 	const char *perf_db_export_mode = "perf_db_export_mode";
1160 	const char *perf_db_export_calls = "perf_db_export_calls";
1161 	const char *perf_db_export_callchains = "perf_db_export_callchains";
1162 	PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
1163 	bool export_calls = false;
1164 	bool export_callchains = false;
1165 	int ret;
1166 
1167 	memset(tables, 0, sizeof(struct tables));
1168 	if (db_export__init(&tables->dbe))
1169 		Py_FatalError("failed to initialize export");
1170 
1171 	db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
1172 	if (!db_export_mode)
1173 		return;
1174 
1175 	ret = PyObject_IsTrue(db_export_mode);
1176 	if (ret == -1)
1177 		handler_call_die(perf_db_export_mode);
1178 	if (!ret)
1179 		return;
1180 
1181 	/* handle export calls */
1182 	tables->dbe.crp = NULL;
1183 	db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
1184 	if (db_export_calls) {
1185 		ret = PyObject_IsTrue(db_export_calls);
1186 		if (ret == -1)
1187 			handler_call_die(perf_db_export_calls);
1188 		export_calls = !!ret;
1189 	}
1190 
1191 	if (export_calls) {
1192 		tables->dbe.crp =
1193 			call_return_processor__new(python_process_call_return,
1194 						   &tables->dbe);
1195 		if (!tables->dbe.crp)
1196 			Py_FatalError("failed to create calls processor");
1197 	}
1198 
1199 	/* handle export callchains */
1200 	tables->dbe.cpr = NULL;
1201 	db_export_callchains = PyDict_GetItemString(main_dict,
1202 						    perf_db_export_callchains);
1203 	if (db_export_callchains) {
1204 		ret = PyObject_IsTrue(db_export_callchains);
1205 		if (ret == -1)
1206 			handler_call_die(perf_db_export_callchains);
1207 		export_callchains = !!ret;
1208 	}
1209 
1210 	if (export_callchains) {
1211 		/*
1212 		 * Attempt to use the call path root from the call return
1213 		 * processor, if the call return processor is in use. Otherwise,
1214 		 * we allocate a new call path root. This prevents exporting
1215 		 * duplicate call path ids when both are in use simultaniously.
1216 		 */
1217 		if (tables->dbe.crp)
1218 			tables->dbe.cpr = tables->dbe.crp->cpr;
1219 		else
1220 			tables->dbe.cpr = call_path_root__new();
1221 
1222 		if (!tables->dbe.cpr)
1223 			Py_FatalError("failed to create call path root");
1224 	}
1225 
1226 	tables->db_export_mode = true;
1227 	/*
1228 	 * Reserve per symbol space for symbol->db_id via symbol__priv()
1229 	 */
1230 	symbol_conf.priv_size = sizeof(u64);
1231 
1232 	SET_TABLE_HANDLER(evsel);
1233 	SET_TABLE_HANDLER(machine);
1234 	SET_TABLE_HANDLER(thread);
1235 	SET_TABLE_HANDLER(comm);
1236 	SET_TABLE_HANDLER(comm_thread);
1237 	SET_TABLE_HANDLER(dso);
1238 	SET_TABLE_HANDLER(symbol);
1239 	SET_TABLE_HANDLER(branch_type);
1240 	SET_TABLE_HANDLER(sample);
1241 	SET_TABLE_HANDLER(call_path);
1242 	SET_TABLE_HANDLER(call_return);
1243 }
1244 
1245 #if PY_MAJOR_VERSION < 3
1246 static void _free_command_line(const char **command_line, int num)
1247 {
1248 	free(command_line);
1249 }
1250 #else
1251 static void _free_command_line(wchar_t **command_line, int num)
1252 {
1253 	int i;
1254 	for (i = 0; i < num; i++)
1255 		PyMem_RawFree(command_line[i]);
1256 	free(command_line);
1257 }
1258 #endif
1259 
1260 
1261 /*
1262  * Start trace script
1263  */
1264 static int python_start_script(const char *script, int argc, const char **argv)
1265 {
1266 	struct tables *tables = &tables_global;
1267 #if PY_MAJOR_VERSION < 3
1268 	const char **command_line;
1269 #else
1270 	wchar_t **command_line;
1271 #endif
1272 	char buf[PATH_MAX];
1273 	int i, err = 0;
1274 	FILE *fp;
1275 
1276 #if PY_MAJOR_VERSION < 3
1277 	command_line = malloc((argc + 1) * sizeof(const char *));
1278 	command_line[0] = script;
1279 	for (i = 1; i < argc + 1; i++)
1280 		command_line[i] = argv[i - 1];
1281 #else
1282 	command_line = malloc((argc + 1) * sizeof(wchar_t *));
1283 	command_line[0] = Py_DecodeLocale(script, NULL);
1284 	for (i = 1; i < argc + 1; i++)
1285 		command_line[i] = Py_DecodeLocale(argv[i - 1], NULL);
1286 #endif
1287 
1288 	Py_Initialize();
1289 
1290 #if PY_MAJOR_VERSION < 3
1291 	initperf_trace_context();
1292 	PySys_SetArgv(argc + 1, (char **)command_line);
1293 #else
1294 	PyInit_perf_trace_context();
1295 	PySys_SetArgv(argc + 1, command_line);
1296 #endif
1297 
1298 	fp = fopen(script, "r");
1299 	if (!fp) {
1300 		sprintf(buf, "Can't open python script \"%s\"", script);
1301 		perror(buf);
1302 		err = -1;
1303 		goto error;
1304 	}
1305 
1306 	err = PyRun_SimpleFile(fp, script);
1307 	if (err) {
1308 		fprintf(stderr, "Error running python script %s\n", script);
1309 		goto error;
1310 	}
1311 
1312 	err = run_start_sub();
1313 	if (err) {
1314 		fprintf(stderr, "Error starting python script %s\n", script);
1315 		goto error;
1316 	}
1317 
1318 	set_table_handlers(tables);
1319 
1320 	if (tables->db_export_mode) {
1321 		err = db_export__branch_types(&tables->dbe);
1322 		if (err)
1323 			goto error;
1324 	}
1325 
1326 	_free_command_line(command_line, argc + 1);
1327 
1328 	return err;
1329 error:
1330 	Py_Finalize();
1331 	_free_command_line(command_line, argc + 1);
1332 
1333 	return err;
1334 }
1335 
1336 static int python_flush_script(void)
1337 {
1338 	struct tables *tables = &tables_global;
1339 
1340 	return db_export__flush(&tables->dbe);
1341 }
1342 
1343 /*
1344  * Stop trace script
1345  */
1346 static int python_stop_script(void)
1347 {
1348 	struct tables *tables = &tables_global;
1349 
1350 	try_call_object("trace_end", NULL);
1351 
1352 	db_export__exit(&tables->dbe);
1353 
1354 	Py_XDECREF(main_dict);
1355 	Py_XDECREF(main_module);
1356 	Py_Finalize();
1357 
1358 	return 0;
1359 }
1360 
1361 static int python_generate_script(struct pevent *pevent, const char *outfile)
1362 {
1363 	struct event_format *event = NULL;
1364 	struct format_field *f;
1365 	char fname[PATH_MAX];
1366 	int not_first, count;
1367 	FILE *ofp;
1368 
1369 	sprintf(fname, "%s.py", outfile);
1370 	ofp = fopen(fname, "w");
1371 	if (ofp == NULL) {
1372 		fprintf(stderr, "couldn't open %s\n", fname);
1373 		return -1;
1374 	}
1375 	fprintf(ofp, "# perf script event handlers, "
1376 		"generated by perf script -g python\n");
1377 
1378 	fprintf(ofp, "# Licensed under the terms of the GNU GPL"
1379 		" License version 2\n\n");
1380 
1381 	fprintf(ofp, "# The common_* event handler fields are the most useful "
1382 		"fields common to\n");
1383 
1384 	fprintf(ofp, "# all events.  They don't necessarily correspond to "
1385 		"the 'common_*' fields\n");
1386 
1387 	fprintf(ofp, "# in the format files.  Those fields not available as "
1388 		"handler params can\n");
1389 
1390 	fprintf(ofp, "# be retrieved using Python functions of the form "
1391 		"common_*(context).\n");
1392 
1393 	fprintf(ofp, "# See the perf-script-python Documentation for the list "
1394 		"of available functions.\n\n");
1395 
1396 	fprintf(ofp, "import os\n");
1397 	fprintf(ofp, "import sys\n\n");
1398 
1399 	fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
1400 	fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
1401 	fprintf(ofp, "\nfrom perf_trace_context import *\n");
1402 	fprintf(ofp, "from Core import *\n\n\n");
1403 
1404 	fprintf(ofp, "def trace_begin():\n");
1405 	fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
1406 
1407 	fprintf(ofp, "def trace_end():\n");
1408 	fprintf(ofp, "\tprint \"in trace_end\"\n\n");
1409 
1410 	while ((event = trace_find_next_event(pevent, event))) {
1411 		fprintf(ofp, "def %s__%s(", event->system, event->name);
1412 		fprintf(ofp, "event_name, ");
1413 		fprintf(ofp, "context, ");
1414 		fprintf(ofp, "common_cpu,\n");
1415 		fprintf(ofp, "\tcommon_secs, ");
1416 		fprintf(ofp, "common_nsecs, ");
1417 		fprintf(ofp, "common_pid, ");
1418 		fprintf(ofp, "common_comm,\n\t");
1419 		fprintf(ofp, "common_callchain, ");
1420 
1421 		not_first = 0;
1422 		count = 0;
1423 
1424 		for (f = event->format.fields; f; f = f->next) {
1425 			if (not_first++)
1426 				fprintf(ofp, ", ");
1427 			if (++count % 5 == 0)
1428 				fprintf(ofp, "\n\t");
1429 
1430 			fprintf(ofp, "%s", f->name);
1431 		}
1432 		if (not_first++)
1433 			fprintf(ofp, ", ");
1434 		if (++count % 5 == 0)
1435 			fprintf(ofp, "\n\t\t");
1436 		fprintf(ofp, "perf_sample_dict");
1437 
1438 		fprintf(ofp, "):\n");
1439 
1440 		fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
1441 			"common_secs, common_nsecs,\n\t\t\t"
1442 			"common_pid, common_comm)\n\n");
1443 
1444 		fprintf(ofp, "\t\tprint \"");
1445 
1446 		not_first = 0;
1447 		count = 0;
1448 
1449 		for (f = event->format.fields; f; f = f->next) {
1450 			if (not_first++)
1451 				fprintf(ofp, ", ");
1452 			if (count && count % 3 == 0) {
1453 				fprintf(ofp, "\" \\\n\t\t\"");
1454 			}
1455 			count++;
1456 
1457 			fprintf(ofp, "%s=", f->name);
1458 			if (f->flags & FIELD_IS_STRING ||
1459 			    f->flags & FIELD_IS_FLAG ||
1460 			    f->flags & FIELD_IS_ARRAY ||
1461 			    f->flags & FIELD_IS_SYMBOLIC)
1462 				fprintf(ofp, "%%s");
1463 			else if (f->flags & FIELD_IS_SIGNED)
1464 				fprintf(ofp, "%%d");
1465 			else
1466 				fprintf(ofp, "%%u");
1467 		}
1468 
1469 		fprintf(ofp, "\" %% \\\n\t\t(");
1470 
1471 		not_first = 0;
1472 		count = 0;
1473 
1474 		for (f = event->format.fields; f; f = f->next) {
1475 			if (not_first++)
1476 				fprintf(ofp, ", ");
1477 
1478 			if (++count % 5 == 0)
1479 				fprintf(ofp, "\n\t\t");
1480 
1481 			if (f->flags & FIELD_IS_FLAG) {
1482 				if ((count - 1) % 5 != 0) {
1483 					fprintf(ofp, "\n\t\t");
1484 					count = 4;
1485 				}
1486 				fprintf(ofp, "flag_str(\"");
1487 				fprintf(ofp, "%s__%s\", ", event->system,
1488 					event->name);
1489 				fprintf(ofp, "\"%s\", %s)", f->name,
1490 					f->name);
1491 			} else if (f->flags & FIELD_IS_SYMBOLIC) {
1492 				if ((count - 1) % 5 != 0) {
1493 					fprintf(ofp, "\n\t\t");
1494 					count = 4;
1495 				}
1496 				fprintf(ofp, "symbol_str(\"");
1497 				fprintf(ofp, "%s__%s\", ", event->system,
1498 					event->name);
1499 				fprintf(ofp, "\"%s\", %s)", f->name,
1500 					f->name);
1501 			} else
1502 				fprintf(ofp, "%s", f->name);
1503 		}
1504 
1505 		fprintf(ofp, ")\n\n");
1506 
1507 		fprintf(ofp, "\t\tprint 'Sample: {'+"
1508 			"get_dict_as_string(perf_sample_dict['sample'], ', ')+'}'\n\n");
1509 
1510 		fprintf(ofp, "\t\tfor node in common_callchain:");
1511 		fprintf(ofp, "\n\t\t\tif 'sym' in node:");
1512 		fprintf(ofp, "\n\t\t\t\tprint \"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name'])");
1513 		fprintf(ofp, "\n\t\t\telse:");
1514 		fprintf(ofp, "\n\t\t\t\tprint \"\t[%%x]\" %% (node['ip'])\n\n");
1515 		fprintf(ofp, "\t\tprint \"\\n\"\n\n");
1516 
1517 	}
1518 
1519 	fprintf(ofp, "def trace_unhandled(event_name, context, "
1520 		"event_fields_dict, perf_sample_dict):\n");
1521 
1522 	fprintf(ofp, "\t\tprint get_dict_as_string(event_fields_dict)\n");
1523 	fprintf(ofp, "\t\tprint 'Sample: {'+"
1524 		"get_dict_as_string(perf_sample_dict['sample'], ', ')+'}'\n\n");
1525 
1526 	fprintf(ofp, "def print_header("
1527 		"event_name, cpu, secs, nsecs, pid, comm):\n"
1528 		"\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
1529 		"(event_name, cpu, secs, nsecs, pid, comm),\n\n");
1530 
1531 	fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
1532 		"\treturn delimiter.join"
1533 		"(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
1534 
1535 	fclose(ofp);
1536 
1537 	fprintf(stderr, "generated Python script: %s\n", fname);
1538 
1539 	return 0;
1540 }
1541 
1542 struct scripting_ops python_scripting_ops = {
1543 	.name			= "Python",
1544 	.start_script		= python_start_script,
1545 	.flush_script		= python_flush_script,
1546 	.stop_script		= python_stop_script,
1547 	.process_event		= python_process_event,
1548 	.process_stat		= python_process_stat,
1549 	.process_stat_interval	= python_process_stat_interval,
1550 	.generate_script	= python_generate_script,
1551 };
1552