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