1 /*
2  * trace-event-python.  Feed trace events to an embedded Python interpreter.
3  *
4  * Copyright (C) 2010 Tom Zanussi <[email protected]>
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21 
22 #include <Python.h>
23 
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <errno.h>
28 
29 #include "../../perf.h"
30 #include "../evsel.h"
31 #include "../util.h"
32 #include "../event.h"
33 #include "../thread.h"
34 #include "../trace-event.h"
35 #include "../machine.h"
36 
37 PyMODINIT_FUNC initperf_trace_context(void);
38 
39 #define FTRACE_MAX_EVENT				\
40 	((1 << (sizeof(unsigned short) * 8)) - 1)
41 
42 struct event_format *events[FTRACE_MAX_EVENT];
43 
44 #define MAX_FIELDS	64
45 #define N_COMMON_FIELDS	7
46 
47 extern struct scripting_context *scripting_context;
48 
49 static char *cur_field_name;
50 static int zero_flag_atom;
51 
52 static PyObject *main_module, *main_dict;
53 
54 static void handler_call_die(const char *handler_name) NORETURN;
55 static void handler_call_die(const char *handler_name)
56 {
57 	PyErr_Print();
58 	Py_FatalError("problem in Python trace event handler");
59 	// Py_FatalError does not return
60 	// but we have to make the compiler happy
61 	abort();
62 }
63 
64 /*
65  * Insert val into into the dictionary and decrement the reference counter.
66  * This is necessary for dictionaries since PyDict_SetItemString() does not
67  * steal a reference, as opposed to PyTuple_SetItem().
68  */
69 static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
70 {
71 	PyDict_SetItemString(dict, key, val);
72 	Py_DECREF(val);
73 }
74 
75 static void define_value(enum print_arg_type field_type,
76 			 const char *ev_name,
77 			 const char *field_name,
78 			 const char *field_value,
79 			 const char *field_str)
80 {
81 	const char *handler_name = "define_flag_value";
82 	PyObject *handler, *t, *retval;
83 	unsigned long long value;
84 	unsigned n = 0;
85 
86 	if (field_type == PRINT_SYMBOL)
87 		handler_name = "define_symbolic_value";
88 
89 	t = PyTuple_New(4);
90 	if (!t)
91 		Py_FatalError("couldn't create Python tuple");
92 
93 	value = eval_flag(field_value);
94 
95 	PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
96 	PyTuple_SetItem(t, n++, PyString_FromString(field_name));
97 	PyTuple_SetItem(t, n++, PyInt_FromLong(value));
98 	PyTuple_SetItem(t, n++, PyString_FromString(field_str));
99 
100 	handler = PyDict_GetItemString(main_dict, handler_name);
101 	if (handler && PyCallable_Check(handler)) {
102 		retval = PyObject_CallObject(handler, t);
103 		if (retval == NULL)
104 			handler_call_die(handler_name);
105 		Py_DECREF(retval);
106 	}
107 
108 	Py_DECREF(t);
109 }
110 
111 static void define_values(enum print_arg_type field_type,
112 			  struct print_flag_sym *field,
113 			  const char *ev_name,
114 			  const char *field_name)
115 {
116 	define_value(field_type, ev_name, field_name, field->value,
117 		     field->str);
118 
119 	if (field->next)
120 		define_values(field_type, field->next, ev_name, field_name);
121 }
122 
123 static void define_field(enum print_arg_type field_type,
124 			 const char *ev_name,
125 			 const char *field_name,
126 			 const char *delim)
127 {
128 	const char *handler_name = "define_flag_field";
129 	PyObject *handler, *t, *retval;
130 	unsigned n = 0;
131 
132 	if (field_type == PRINT_SYMBOL)
133 		handler_name = "define_symbolic_field";
134 
135 	if (field_type == PRINT_FLAGS)
136 		t = PyTuple_New(3);
137 	else
138 		t = PyTuple_New(2);
139 	if (!t)
140 		Py_FatalError("couldn't create Python tuple");
141 
142 	PyTuple_SetItem(t, n++, PyString_FromString(ev_name));
143 	PyTuple_SetItem(t, n++, PyString_FromString(field_name));
144 	if (field_type == PRINT_FLAGS)
145 		PyTuple_SetItem(t, n++, PyString_FromString(delim));
146 
147 	handler = PyDict_GetItemString(main_dict, handler_name);
148 	if (handler && PyCallable_Check(handler)) {
149 		retval = PyObject_CallObject(handler, t);
150 		if (retval == NULL)
151 			handler_call_die(handler_name);
152 		Py_DECREF(retval);
153 	}
154 
155 	Py_DECREF(t);
156 }
157 
158 static void define_event_symbols(struct event_format *event,
159 				 const char *ev_name,
160 				 struct print_arg *args)
161 {
162 	switch (args->type) {
163 	case PRINT_NULL:
164 		break;
165 	case PRINT_ATOM:
166 		define_value(PRINT_FLAGS, ev_name, cur_field_name, "0",
167 			     args->atom.atom);
168 		zero_flag_atom = 0;
169 		break;
170 	case PRINT_FIELD:
171 		free(cur_field_name);
172 		cur_field_name = strdup(args->field.name);
173 		break;
174 	case PRINT_FLAGS:
175 		define_event_symbols(event, ev_name, args->flags.field);
176 		define_field(PRINT_FLAGS, ev_name, cur_field_name,
177 			     args->flags.delim);
178 		define_values(PRINT_FLAGS, args->flags.flags, ev_name,
179 			      cur_field_name);
180 		break;
181 	case PRINT_SYMBOL:
182 		define_event_symbols(event, ev_name, args->symbol.field);
183 		define_field(PRINT_SYMBOL, ev_name, cur_field_name, NULL);
184 		define_values(PRINT_SYMBOL, args->symbol.symbols, ev_name,
185 			      cur_field_name);
186 		break;
187 	case PRINT_HEX:
188 		define_event_symbols(event, ev_name, args->hex.field);
189 		define_event_symbols(event, ev_name, args->hex.size);
190 		break;
191 	case PRINT_STRING:
192 		break;
193 	case PRINT_TYPE:
194 		define_event_symbols(event, ev_name, args->typecast.item);
195 		break;
196 	case PRINT_OP:
197 		if (strcmp(args->op.op, ":") == 0)
198 			zero_flag_atom = 1;
199 		define_event_symbols(event, ev_name, args->op.left);
200 		define_event_symbols(event, ev_name, args->op.right);
201 		break;
202 	default:
203 		/* gcc warns for these? */
204 	case PRINT_BSTRING:
205 	case PRINT_DYNAMIC_ARRAY:
206 	case PRINT_FUNC:
207 	case PRINT_BITMASK:
208 		/* we should warn... */
209 		return;
210 	}
211 
212 	if (args->next)
213 		define_event_symbols(event, ev_name, args->next);
214 }
215 
216 static inline struct event_format *find_cache_event(struct perf_evsel *evsel)
217 {
218 	static char ev_name[256];
219 	struct event_format *event;
220 	int type = evsel->attr.config;
221 
222 	/*
223  	 * XXX: Do we really need to cache this since now we have evsel->tp_format
224  	 * cached already? Need to re-read this "cache" routine that as well calls
225  	 * define_event_symbols() :-\
226  	 */
227 	if (events[type])
228 		return events[type];
229 
230 	events[type] = event = evsel->tp_format;
231 	if (!event)
232 		return NULL;
233 
234 	sprintf(ev_name, "%s__%s", event->system, event->name);
235 
236 	define_event_symbols(event, ev_name, event->print_fmt.args);
237 
238 	return event;
239 }
240 
241 static PyObject *get_field_numeric_entry(struct event_format *event,
242 		struct format_field *field, void *data)
243 {
244 	bool is_array = field->flags & FIELD_IS_ARRAY;
245 	PyObject *obj, *list = NULL;
246 	unsigned long long val;
247 	unsigned int item_size, n_items, i;
248 
249 	if (is_array) {
250 		list = PyList_New(field->arraylen);
251 		item_size = field->size / field->arraylen;
252 		n_items = field->arraylen;
253 	} else {
254 		item_size = field->size;
255 		n_items = 1;
256 	}
257 
258 	for (i = 0; i < n_items; i++) {
259 
260 		val = read_size(event, data + field->offset + i * item_size,
261 				item_size);
262 		if (field->flags & FIELD_IS_SIGNED) {
263 			if ((long long)val >= LONG_MIN &&
264 					(long long)val <= LONG_MAX)
265 				obj = PyInt_FromLong(val);
266 			else
267 				obj = PyLong_FromLongLong(val);
268 		} else {
269 			if (val <= LONG_MAX)
270 				obj = PyInt_FromLong(val);
271 			else
272 				obj = PyLong_FromUnsignedLongLong(val);
273 		}
274 		if (is_array)
275 			PyList_SET_ITEM(list, i, obj);
276 	}
277 	if (is_array)
278 		obj = list;
279 	return obj;
280 }
281 
282 
283 static PyObject *python_process_callchain(struct perf_sample *sample,
284 					 struct perf_evsel *evsel,
285 					 struct addr_location *al)
286 {
287 	PyObject *pylist;
288 
289 	pylist = PyList_New(0);
290 	if (!pylist)
291 		Py_FatalError("couldn't create Python list");
292 
293 	if (!symbol_conf.use_callchain || !sample->callchain)
294 		goto exit;
295 
296 	if (machine__resolve_callchain(al->machine, evsel, al->thread,
297 					   sample, NULL, NULL,
298 					   PERF_MAX_STACK_DEPTH) != 0) {
299 		pr_err("Failed to resolve callchain. Skipping\n");
300 		goto exit;
301 	}
302 	callchain_cursor_commit(&callchain_cursor);
303 
304 
305 	while (1) {
306 		PyObject *pyelem;
307 		struct callchain_cursor_node *node;
308 		node = callchain_cursor_current(&callchain_cursor);
309 		if (!node)
310 			break;
311 
312 		pyelem = PyDict_New();
313 		if (!pyelem)
314 			Py_FatalError("couldn't create Python dictionary");
315 
316 
317 		pydict_set_item_string_decref(pyelem, "ip",
318 				PyLong_FromUnsignedLongLong(node->ip));
319 
320 		if (node->sym) {
321 			PyObject *pysym  = PyDict_New();
322 			if (!pysym)
323 				Py_FatalError("couldn't create Python dictionary");
324 			pydict_set_item_string_decref(pysym, "start",
325 					PyLong_FromUnsignedLongLong(node->sym->start));
326 			pydict_set_item_string_decref(pysym, "end",
327 					PyLong_FromUnsignedLongLong(node->sym->end));
328 			pydict_set_item_string_decref(pysym, "binding",
329 					PyInt_FromLong(node->sym->binding));
330 			pydict_set_item_string_decref(pysym, "name",
331 					PyString_FromStringAndSize(node->sym->name,
332 							node->sym->namelen));
333 			pydict_set_item_string_decref(pyelem, "sym", pysym);
334 		}
335 
336 		if (node->map) {
337 			struct map *map = node->map;
338 			const char *dsoname = "[unknown]";
339 			if (map && map->dso && (map->dso->name || map->dso->long_name)) {
340 				if (symbol_conf.show_kernel_path && map->dso->long_name)
341 					dsoname = map->dso->long_name;
342 				else if (map->dso->name)
343 					dsoname = map->dso->name;
344 			}
345 			pydict_set_item_string_decref(pyelem, "dso",
346 					PyString_FromString(dsoname));
347 		}
348 
349 		callchain_cursor_advance(&callchain_cursor);
350 		PyList_Append(pylist, pyelem);
351 		Py_DECREF(pyelem);
352 	}
353 
354 exit:
355 	return pylist;
356 }
357 
358 
359 static void python_process_tracepoint(struct perf_sample *sample,
360 				      struct perf_evsel *evsel,
361 				      struct thread *thread,
362 				      struct addr_location *al)
363 {
364 	PyObject *handler, *retval, *context, *t, *obj, *callchain;
365 	PyObject *dict = NULL;
366 	static char handler_name[256];
367 	struct format_field *field;
368 	unsigned long s, ns;
369 	struct event_format *event;
370 	unsigned n = 0;
371 	int pid;
372 	int cpu = sample->cpu;
373 	void *data = sample->raw_data;
374 	unsigned long long nsecs = sample->time;
375 	const char *comm = thread__comm_str(thread);
376 
377 	t = PyTuple_New(MAX_FIELDS);
378 	if (!t)
379 		Py_FatalError("couldn't create Python tuple");
380 
381 	event = find_cache_event(evsel);
382 	if (!event)
383 		die("ug! no event found for type %d", (int)evsel->attr.config);
384 
385 	pid = raw_field_value(event, "common_pid", data);
386 
387 	sprintf(handler_name, "%s__%s", event->system, event->name);
388 
389 	handler = PyDict_GetItemString(main_dict, handler_name);
390 	if (handler && !PyCallable_Check(handler))
391 		handler = NULL;
392 	if (!handler) {
393 		dict = PyDict_New();
394 		if (!dict)
395 			Py_FatalError("couldn't create Python dict");
396 	}
397 	s = nsecs / NSECS_PER_SEC;
398 	ns = nsecs - s * NSECS_PER_SEC;
399 
400 	scripting_context->event_data = data;
401 	scripting_context->pevent = evsel->tp_format->pevent;
402 
403 	context = PyCObject_FromVoidPtr(scripting_context, NULL);
404 
405 	PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
406 	PyTuple_SetItem(t, n++, context);
407 
408 	/* ip unwinding */
409 	callchain = python_process_callchain(sample, evsel, al);
410 
411 	if (handler) {
412 		PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
413 		PyTuple_SetItem(t, n++, PyInt_FromLong(s));
414 		PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
415 		PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
416 		PyTuple_SetItem(t, n++, PyString_FromString(comm));
417 		PyTuple_SetItem(t, n++, callchain);
418 	} else {
419 		pydict_set_item_string_decref(dict, "common_cpu", PyInt_FromLong(cpu));
420 		pydict_set_item_string_decref(dict, "common_s", PyInt_FromLong(s));
421 		pydict_set_item_string_decref(dict, "common_ns", PyInt_FromLong(ns));
422 		pydict_set_item_string_decref(dict, "common_pid", PyInt_FromLong(pid));
423 		pydict_set_item_string_decref(dict, "common_comm", PyString_FromString(comm));
424 		pydict_set_item_string_decref(dict, "common_callchain", callchain);
425 	}
426 	for (field = event->format.fields; field; field = field->next) {
427 		if (field->flags & FIELD_IS_STRING) {
428 			int offset;
429 			if (field->flags & FIELD_IS_DYNAMIC) {
430 				offset = *(int *)(data + field->offset);
431 				offset &= 0xffff;
432 			} else
433 				offset = field->offset;
434 			obj = PyString_FromString((char *)data + offset);
435 		} else { /* FIELD_IS_NUMERIC */
436 			obj = get_field_numeric_entry(event, field, data);
437 		}
438 		if (handler)
439 			PyTuple_SetItem(t, n++, obj);
440 		else
441 			pydict_set_item_string_decref(dict, field->name, obj);
442 
443 	}
444 
445 	if (!handler)
446 		PyTuple_SetItem(t, n++, dict);
447 
448 	if (_PyTuple_Resize(&t, n) == -1)
449 		Py_FatalError("error resizing Python tuple");
450 
451 	if (handler) {
452 		retval = PyObject_CallObject(handler, t);
453 		if (retval == NULL)
454 			handler_call_die(handler_name);
455 		Py_DECREF(retval);
456 	} else {
457 		handler = PyDict_GetItemString(main_dict, "trace_unhandled");
458 		if (handler && PyCallable_Check(handler)) {
459 
460 			retval = PyObject_CallObject(handler, t);
461 			if (retval == NULL)
462 				handler_call_die("trace_unhandled");
463 			Py_DECREF(retval);
464 		}
465 		Py_DECREF(dict);
466 	}
467 
468 	Py_DECREF(t);
469 }
470 
471 static void python_process_general_event(struct perf_sample *sample,
472 					 struct perf_evsel *evsel,
473 					 struct thread *thread,
474 					 struct addr_location *al)
475 {
476 	PyObject *handler, *retval, *t, *dict, *callchain;
477 	static char handler_name[64];
478 	unsigned n = 0;
479 
480 	/*
481 	 * Use the MAX_FIELDS to make the function expandable, though
482 	 * currently there is only one item for the tuple.
483 	 */
484 	t = PyTuple_New(MAX_FIELDS);
485 	if (!t)
486 		Py_FatalError("couldn't create Python tuple");
487 
488 	dict = PyDict_New();
489 	if (!dict)
490 		Py_FatalError("couldn't create Python dictionary");
491 
492 	snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
493 
494 	handler = PyDict_GetItemString(main_dict, handler_name);
495 	if (!handler || !PyCallable_Check(handler))
496 		goto exit;
497 
498 	pydict_set_item_string_decref(dict, "ev_name", PyString_FromString(perf_evsel__name(evsel)));
499 	pydict_set_item_string_decref(dict, "attr", PyString_FromStringAndSize(
500 			(const char *)&evsel->attr, sizeof(evsel->attr)));
501 	pydict_set_item_string_decref(dict, "sample", PyString_FromStringAndSize(
502 			(const char *)sample, sizeof(*sample)));
503 	pydict_set_item_string_decref(dict, "raw_buf", PyString_FromStringAndSize(
504 			(const char *)sample->raw_data, sample->raw_size));
505 	pydict_set_item_string_decref(dict, "comm",
506 			PyString_FromString(thread__comm_str(thread)));
507 	if (al->map) {
508 		pydict_set_item_string_decref(dict, "dso",
509 			PyString_FromString(al->map->dso->name));
510 	}
511 	if (al->sym) {
512 		pydict_set_item_string_decref(dict, "symbol",
513 			PyString_FromString(al->sym->name));
514 	}
515 
516 	/* ip unwinding */
517 	callchain = python_process_callchain(sample, evsel, al);
518 	pydict_set_item_string_decref(dict, "callchain", callchain);
519 
520 	PyTuple_SetItem(t, n++, dict);
521 	if (_PyTuple_Resize(&t, n) == -1)
522 		Py_FatalError("error resizing Python tuple");
523 
524 	retval = PyObject_CallObject(handler, t);
525 	if (retval == NULL)
526 		handler_call_die(handler_name);
527 	Py_DECREF(retval);
528 exit:
529 	Py_DECREF(dict);
530 	Py_DECREF(t);
531 }
532 
533 static void python_process_event(union perf_event *event __maybe_unused,
534 				 struct perf_sample *sample,
535 				 struct perf_evsel *evsel,
536 				 struct thread *thread,
537 				 struct addr_location *al)
538 {
539 	switch (evsel->attr.type) {
540 	case PERF_TYPE_TRACEPOINT:
541 		python_process_tracepoint(sample, evsel, thread, al);
542 		break;
543 	/* Reserve for future process_hw/sw/raw APIs */
544 	default:
545 		python_process_general_event(sample, evsel, thread, al);
546 	}
547 }
548 
549 static int run_start_sub(void)
550 {
551 	PyObject *handler, *retval;
552 	int err = 0;
553 
554 	main_module = PyImport_AddModule("__main__");
555 	if (main_module == NULL)
556 		return -1;
557 	Py_INCREF(main_module);
558 
559 	main_dict = PyModule_GetDict(main_module);
560 	if (main_dict == NULL) {
561 		err = -1;
562 		goto error;
563 	}
564 	Py_INCREF(main_dict);
565 
566 	handler = PyDict_GetItemString(main_dict, "trace_begin");
567 	if (handler == NULL || !PyCallable_Check(handler))
568 		goto out;
569 
570 	retval = PyObject_CallObject(handler, NULL);
571 	if (retval == NULL)
572 		handler_call_die("trace_begin");
573 
574 	Py_DECREF(retval);
575 	return err;
576 error:
577 	Py_XDECREF(main_dict);
578 	Py_XDECREF(main_module);
579 out:
580 	return err;
581 }
582 
583 /*
584  * Start trace script
585  */
586 static int python_start_script(const char *script, int argc, const char **argv)
587 {
588 	const char **command_line;
589 	char buf[PATH_MAX];
590 	int i, err = 0;
591 	FILE *fp;
592 
593 	command_line = malloc((argc + 1) * sizeof(const char *));
594 	command_line[0] = script;
595 	for (i = 1; i < argc + 1; i++)
596 		command_line[i] = argv[i - 1];
597 
598 	Py_Initialize();
599 
600 	initperf_trace_context();
601 
602 	PySys_SetArgv(argc + 1, (char **)command_line);
603 
604 	fp = fopen(script, "r");
605 	if (!fp) {
606 		sprintf(buf, "Can't open python script \"%s\"", script);
607 		perror(buf);
608 		err = -1;
609 		goto error;
610 	}
611 
612 	err = PyRun_SimpleFile(fp, script);
613 	if (err) {
614 		fprintf(stderr, "Error running python script %s\n", script);
615 		goto error;
616 	}
617 
618 	err = run_start_sub();
619 	if (err) {
620 		fprintf(stderr, "Error starting python script %s\n", script);
621 		goto error;
622 	}
623 
624 	free(command_line);
625 
626 	return err;
627 error:
628 	Py_Finalize();
629 	free(command_line);
630 
631 	return err;
632 }
633 
634 /*
635  * Stop trace script
636  */
637 static int python_stop_script(void)
638 {
639 	PyObject *handler, *retval;
640 	int err = 0;
641 
642 	handler = PyDict_GetItemString(main_dict, "trace_end");
643 	if (handler == NULL || !PyCallable_Check(handler))
644 		goto out;
645 
646 	retval = PyObject_CallObject(handler, NULL);
647 	if (retval == NULL)
648 		handler_call_die("trace_end");
649 	Py_DECREF(retval);
650 out:
651 	Py_XDECREF(main_dict);
652 	Py_XDECREF(main_module);
653 	Py_Finalize();
654 
655 	return err;
656 }
657 
658 static int python_generate_script(struct pevent *pevent, const char *outfile)
659 {
660 	struct event_format *event = NULL;
661 	struct format_field *f;
662 	char fname[PATH_MAX];
663 	int not_first, count;
664 	FILE *ofp;
665 
666 	sprintf(fname, "%s.py", outfile);
667 	ofp = fopen(fname, "w");
668 	if (ofp == NULL) {
669 		fprintf(stderr, "couldn't open %s\n", fname);
670 		return -1;
671 	}
672 	fprintf(ofp, "# perf script event handlers, "
673 		"generated by perf script -g python\n");
674 
675 	fprintf(ofp, "# Licensed under the terms of the GNU GPL"
676 		" License version 2\n\n");
677 
678 	fprintf(ofp, "# The common_* event handler fields are the most useful "
679 		"fields common to\n");
680 
681 	fprintf(ofp, "# all events.  They don't necessarily correspond to "
682 		"the 'common_*' fields\n");
683 
684 	fprintf(ofp, "# in the format files.  Those fields not available as "
685 		"handler params can\n");
686 
687 	fprintf(ofp, "# be retrieved using Python functions of the form "
688 		"common_*(context).\n");
689 
690 	fprintf(ofp, "# See the perf-trace-python Documentation for the list "
691 		"of available functions.\n\n");
692 
693 	fprintf(ofp, "import os\n");
694 	fprintf(ofp, "import sys\n\n");
695 
696 	fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
697 	fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
698 	fprintf(ofp, "\nfrom perf_trace_context import *\n");
699 	fprintf(ofp, "from Core import *\n\n\n");
700 
701 	fprintf(ofp, "def trace_begin():\n");
702 	fprintf(ofp, "\tprint \"in trace_begin\"\n\n");
703 
704 	fprintf(ofp, "def trace_end():\n");
705 	fprintf(ofp, "\tprint \"in trace_end\"\n\n");
706 
707 	while ((event = trace_find_next_event(pevent, event))) {
708 		fprintf(ofp, "def %s__%s(", event->system, event->name);
709 		fprintf(ofp, "event_name, ");
710 		fprintf(ofp, "context, ");
711 		fprintf(ofp, "common_cpu,\n");
712 		fprintf(ofp, "\tcommon_secs, ");
713 		fprintf(ofp, "common_nsecs, ");
714 		fprintf(ofp, "common_pid, ");
715 		fprintf(ofp, "common_comm,\n\t");
716 		fprintf(ofp, "common_callchain, ");
717 
718 		not_first = 0;
719 		count = 0;
720 
721 		for (f = event->format.fields; f; f = f->next) {
722 			if (not_first++)
723 				fprintf(ofp, ", ");
724 			if (++count % 5 == 0)
725 				fprintf(ofp, "\n\t");
726 
727 			fprintf(ofp, "%s", f->name);
728 		}
729 		fprintf(ofp, "):\n");
730 
731 		fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
732 			"common_secs, common_nsecs,\n\t\t\t"
733 			"common_pid, common_comm)\n\n");
734 
735 		fprintf(ofp, "\t\tprint \"");
736 
737 		not_first = 0;
738 		count = 0;
739 
740 		for (f = event->format.fields; f; f = f->next) {
741 			if (not_first++)
742 				fprintf(ofp, ", ");
743 			if (count && count % 3 == 0) {
744 				fprintf(ofp, "\" \\\n\t\t\"");
745 			}
746 			count++;
747 
748 			fprintf(ofp, "%s=", f->name);
749 			if (f->flags & FIELD_IS_STRING ||
750 			    f->flags & FIELD_IS_FLAG ||
751 			    f->flags & FIELD_IS_ARRAY ||
752 			    f->flags & FIELD_IS_SYMBOLIC)
753 				fprintf(ofp, "%%s");
754 			else if (f->flags & FIELD_IS_SIGNED)
755 				fprintf(ofp, "%%d");
756 			else
757 				fprintf(ofp, "%%u");
758 		}
759 
760 		fprintf(ofp, "\" %% \\\n\t\t(");
761 
762 		not_first = 0;
763 		count = 0;
764 
765 		for (f = event->format.fields; f; f = f->next) {
766 			if (not_first++)
767 				fprintf(ofp, ", ");
768 
769 			if (++count % 5 == 0)
770 				fprintf(ofp, "\n\t\t");
771 
772 			if (f->flags & FIELD_IS_FLAG) {
773 				if ((count - 1) % 5 != 0) {
774 					fprintf(ofp, "\n\t\t");
775 					count = 4;
776 				}
777 				fprintf(ofp, "flag_str(\"");
778 				fprintf(ofp, "%s__%s\", ", event->system,
779 					event->name);
780 				fprintf(ofp, "\"%s\", %s)", f->name,
781 					f->name);
782 			} else if (f->flags & FIELD_IS_SYMBOLIC) {
783 				if ((count - 1) % 5 != 0) {
784 					fprintf(ofp, "\n\t\t");
785 					count = 4;
786 				}
787 				fprintf(ofp, "symbol_str(\"");
788 				fprintf(ofp, "%s__%s\", ", event->system,
789 					event->name);
790 				fprintf(ofp, "\"%s\", %s)", f->name,
791 					f->name);
792 			} else
793 				fprintf(ofp, "%s", f->name);
794 		}
795 
796 		fprintf(ofp, ")\n\n");
797 
798 		fprintf(ofp, "\t\tfor node in common_callchain:");
799 		fprintf(ofp, "\n\t\t\tif 'sym' in node:");
800 		fprintf(ofp, "\n\t\t\t\tprint \"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name'])");
801 		fprintf(ofp, "\n\t\t\telse:");
802 		fprintf(ofp, "\n\t\t\t\tprint \"\t[%%x]\" %% (node['ip'])\n\n");
803 		fprintf(ofp, "\t\tprint \"\\n\"\n\n");
804 
805 	}
806 
807 	fprintf(ofp, "def trace_unhandled(event_name, context, "
808 		"event_fields_dict):\n");
809 
810 	fprintf(ofp, "\t\tprint ' '.join(['%%s=%%s'%%(k,str(v))"
811 		"for k,v in sorted(event_fields_dict.items())])\n\n");
812 
813 	fprintf(ofp, "def print_header("
814 		"event_name, cpu, secs, nsecs, pid, comm):\n"
815 		"\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
816 		"(event_name, cpu, secs, nsecs, pid, comm),\n");
817 
818 	fclose(ofp);
819 
820 	fprintf(stderr, "generated Python script: %s\n", fname);
821 
822 	return 0;
823 }
824 
825 struct scripting_ops python_scripting_ops = {
826 	.name = "Python",
827 	.start_script = python_start_script,
828 	.stop_script = python_stop_script,
829 	.process_event = python_process_event,
830 	.generate_script = python_generate_script,
831 };
832