xref: /linux/tools/perf/util/scripting-engines/trace-event-python.c (revision f4f346c3465949ebba80c6cc52cd8d2eeaa545fd)
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 #ifdef HAVE_LIBTRACEEVENT
34 #include <event-parse.h>
35 #endif
36 
37 #include "../build-id.h"
38 #include "../counts.h"
39 #include "../debug.h"
40 #include "../dso.h"
41 #include "../callchain.h"
42 #include "../env.h"
43 #include "../evsel.h"
44 #include "../event.h"
45 #include "../thread.h"
46 #include "../comm.h"
47 #include "../machine.h"
48 #include "../mem-info.h"
49 #include "../db-export.h"
50 #include "../thread-stack.h"
51 #include "../trace-event.h"
52 #include "../call-path.h"
53 #include "map.h"
54 #include "symbol.h"
55 #include "thread_map.h"
56 #include "print_binary.h"
57 #include "stat.h"
58 #include "mem-events.h"
59 #include "util/perf_regs.h"
60 
61 #define _PyUnicode_FromString(arg) \
62   PyUnicode_FromString(arg)
63 #define _PyUnicode_FromStringAndSize(arg1, arg2) \
64   PyUnicode_FromStringAndSize((arg1), (arg2))
65 #define _PyBytes_FromStringAndSize(arg1, arg2) \
66   PyBytes_FromStringAndSize((arg1), (arg2))
67 #define _PyLong_FromLong(arg) \
68   PyLong_FromLong(arg)
69 #define _PyLong_AsLong(arg) \
70   PyLong_AsLong(arg)
71 #define _PyCapsule_New(arg1, arg2, arg3) \
72   PyCapsule_New((arg1), (arg2), (arg3))
73 
74 PyMODINIT_FUNC PyInit_perf_trace_context(void);
75 
76 #ifdef HAVE_LIBTRACEEVENT
77 #define TRACE_EVENT_TYPE_MAX				\
78 	((1 << (sizeof(unsigned short) * 8)) - 1)
79 
80 #define N_COMMON_FIELDS	7
81 
82 static char *cur_field_name;
83 static int zero_flag_atom;
84 #endif
85 
86 #define MAX_FIELDS	64
87 
88 extern struct scripting_context *scripting_context;
89 
90 static PyObject *main_module, *main_dict;
91 
92 struct tables {
93 	struct db_export	dbe;
94 	PyObject		*evsel_handler;
95 	PyObject		*machine_handler;
96 	PyObject		*thread_handler;
97 	PyObject		*comm_handler;
98 	PyObject		*comm_thread_handler;
99 	PyObject		*dso_handler;
100 	PyObject		*symbol_handler;
101 	PyObject		*branch_type_handler;
102 	PyObject		*sample_handler;
103 	PyObject		*call_path_handler;
104 	PyObject		*call_return_handler;
105 	PyObject		*synth_handler;
106 	PyObject		*context_switch_handler;
107 	bool			db_export_mode;
108 };
109 
110 static struct tables tables_global;
111 
112 static void handler_call_die(const char *handler_name) __noreturn;
handler_call_die(const char * handler_name)113 static void handler_call_die(const char *handler_name)
114 {
115 	PyErr_Print();
116 	Py_FatalError("problem in Python trace event handler");
117 	// Py_FatalError does not return
118 	// but we have to make the compiler happy
119 	abort();
120 }
121 
122 /*
123  * Insert val into the dictionary and decrement the reference counter.
124  * This is necessary for dictionaries since PyDict_SetItemString() does not
125  * steal a reference, as opposed to PyTuple_SetItem().
126  */
pydict_set_item_string_decref(PyObject * dict,const char * key,PyObject * val)127 static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
128 {
129 	PyDict_SetItemString(dict, key, val);
130 	Py_DECREF(val);
131 }
132 
get_handler(const char * handler_name)133 static PyObject *get_handler(const char *handler_name)
134 {
135 	PyObject *handler;
136 
137 	handler = PyDict_GetItemString(main_dict, handler_name);
138 	if (handler && !PyCallable_Check(handler))
139 		return NULL;
140 	return handler;
141 }
142 
call_object(PyObject * handler,PyObject * args,const char * die_msg)143 static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
144 {
145 	PyObject *retval;
146 
147 	retval = PyObject_CallObject(handler, args);
148 	if (retval == NULL)
149 		handler_call_die(die_msg);
150 	Py_DECREF(retval);
151 }
152 
try_call_object(const char * handler_name,PyObject * args)153 static void try_call_object(const char *handler_name, PyObject *args)
154 {
155 	PyObject *handler;
156 
157 	handler = get_handler(handler_name);
158 	if (handler)
159 		call_object(handler, args, handler_name);
160 }
161 
162 #ifdef HAVE_LIBTRACEEVENT
get_argument_count(PyObject * handler)163 static int get_argument_count(PyObject *handler)
164 {
165 	int arg_count = 0;
166 
167 	PyObject *code_obj = code_obj = PyObject_GetAttrString(handler, "__code__");
168 	PyErr_Clear();
169 	if (code_obj) {
170 		PyObject *arg_count_obj = PyObject_GetAttrString(code_obj,
171 			"co_argcount");
172 		if (arg_count_obj) {
173 			arg_count = (int) _PyLong_AsLong(arg_count_obj);
174 			Py_DECREF(arg_count_obj);
175 		}
176 		Py_DECREF(code_obj);
177 	}
178 	return arg_count;
179 }
180 
define_value(enum tep_print_arg_type field_type,const char * ev_name,const char * field_name,const char * field_value,const char * field_str)181 static void define_value(enum tep_print_arg_type field_type,
182 			 const char *ev_name,
183 			 const char *field_name,
184 			 const char *field_value,
185 			 const char *field_str)
186 {
187 	const char *handler_name = "define_flag_value";
188 	PyObject *t;
189 	unsigned long long value;
190 	unsigned n = 0;
191 
192 	if (field_type == TEP_PRINT_SYMBOL)
193 		handler_name = "define_symbolic_value";
194 
195 	t = PyTuple_New(4);
196 	if (!t)
197 		Py_FatalError("couldn't create Python tuple");
198 
199 	value = eval_flag(field_value);
200 
201 	PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
202 	PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
203 	PyTuple_SetItem(t, n++, _PyLong_FromLong(value));
204 	PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_str));
205 
206 	try_call_object(handler_name, t);
207 
208 	Py_DECREF(t);
209 }
210 
define_values(enum tep_print_arg_type field_type,struct tep_print_flag_sym * field,const char * ev_name,const char * field_name)211 static void define_values(enum tep_print_arg_type field_type,
212 			  struct tep_print_flag_sym *field,
213 			  const char *ev_name,
214 			  const char *field_name)
215 {
216 	define_value(field_type, ev_name, field_name, field->value,
217 		     field->str);
218 
219 	if (field->next)
220 		define_values(field_type, field->next, ev_name, field_name);
221 }
222 
define_field(enum tep_print_arg_type field_type,const char * ev_name,const char * field_name,const char * delim)223 static void define_field(enum tep_print_arg_type field_type,
224 			 const char *ev_name,
225 			 const char *field_name,
226 			 const char *delim)
227 {
228 	const char *handler_name = "define_flag_field";
229 	PyObject *t;
230 	unsigned n = 0;
231 
232 	if (field_type == TEP_PRINT_SYMBOL)
233 		handler_name = "define_symbolic_field";
234 
235 	if (field_type == TEP_PRINT_FLAGS)
236 		t = PyTuple_New(3);
237 	else
238 		t = PyTuple_New(2);
239 	if (!t)
240 		Py_FatalError("couldn't create Python tuple");
241 
242 	PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
243 	PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
244 	if (field_type == TEP_PRINT_FLAGS)
245 		PyTuple_SetItem(t, n++, _PyUnicode_FromString(delim));
246 
247 	try_call_object(handler_name, t);
248 
249 	Py_DECREF(t);
250 }
251 
define_event_symbols(struct tep_event * event,const char * ev_name,struct tep_print_arg * args)252 static void define_event_symbols(struct tep_event *event,
253 				 const char *ev_name,
254 				 struct tep_print_arg *args)
255 {
256 	if (args == NULL)
257 		return;
258 
259 	switch (args->type) {
260 	case TEP_PRINT_NULL:
261 		break;
262 	case TEP_PRINT_ATOM:
263 		define_value(TEP_PRINT_FLAGS, ev_name, cur_field_name, "0",
264 			     args->atom.atom);
265 		zero_flag_atom = 0;
266 		break;
267 	case TEP_PRINT_FIELD:
268 		free(cur_field_name);
269 		cur_field_name = strdup(args->field.name);
270 		break;
271 	case TEP_PRINT_FLAGS:
272 		define_event_symbols(event, ev_name, args->flags.field);
273 		define_field(TEP_PRINT_FLAGS, ev_name, cur_field_name,
274 			     args->flags.delim);
275 		define_values(TEP_PRINT_FLAGS, args->flags.flags, ev_name,
276 			      cur_field_name);
277 		break;
278 	case TEP_PRINT_SYMBOL:
279 		define_event_symbols(event, ev_name, args->symbol.field);
280 		define_field(TEP_PRINT_SYMBOL, ev_name, cur_field_name, NULL);
281 		define_values(TEP_PRINT_SYMBOL, args->symbol.symbols, ev_name,
282 			      cur_field_name);
283 		break;
284 	case TEP_PRINT_HEX:
285 	case TEP_PRINT_HEX_STR:
286 		define_event_symbols(event, ev_name, args->hex.field);
287 		define_event_symbols(event, ev_name, args->hex.size);
288 		break;
289 	case TEP_PRINT_INT_ARRAY:
290 		define_event_symbols(event, ev_name, args->int_array.field);
291 		define_event_symbols(event, ev_name, args->int_array.count);
292 		define_event_symbols(event, ev_name, args->int_array.el_size);
293 		break;
294 	case TEP_PRINT_STRING:
295 		break;
296 	case TEP_PRINT_TYPE:
297 		define_event_symbols(event, ev_name, args->typecast.item);
298 		break;
299 	case TEP_PRINT_OP:
300 		if (strcmp(args->op.op, ":") == 0)
301 			zero_flag_atom = 1;
302 		define_event_symbols(event, ev_name, args->op.left);
303 		define_event_symbols(event, ev_name, args->op.right);
304 		break;
305 	default:
306 		/* gcc warns for these? */
307 	case TEP_PRINT_BSTRING:
308 	case TEP_PRINT_DYNAMIC_ARRAY:
309 	case TEP_PRINT_DYNAMIC_ARRAY_LEN:
310 	case TEP_PRINT_FUNC:
311 	case TEP_PRINT_BITMASK:
312 		/* we should warn... */
313 		return;
314 	}
315 
316 	if (args->next)
317 		define_event_symbols(event, ev_name, args->next);
318 }
319 
get_field_numeric_entry(struct tep_event * event,struct tep_format_field * field,void * data)320 static PyObject *get_field_numeric_entry(struct tep_event *event,
321 		struct tep_format_field *field, void *data)
322 {
323 	bool is_array = field->flags & TEP_FIELD_IS_ARRAY;
324 	PyObject *obj = NULL, *list = NULL;
325 	unsigned long long val;
326 	unsigned int item_size, n_items, i;
327 
328 	if (is_array) {
329 		list = PyList_New(field->arraylen);
330 		if (!list)
331 			Py_FatalError("couldn't create Python list");
332 		item_size = field->size / field->arraylen;
333 		n_items = field->arraylen;
334 	} else {
335 		item_size = field->size;
336 		n_items = 1;
337 	}
338 
339 	for (i = 0; i < n_items; i++) {
340 
341 		val = read_size(event, data + field->offset + i * item_size,
342 				item_size);
343 		if (field->flags & TEP_FIELD_IS_SIGNED) {
344 			if ((long long)val >= LONG_MIN &&
345 					(long long)val <= LONG_MAX)
346 				obj = _PyLong_FromLong(val);
347 			else
348 				obj = PyLong_FromLongLong(val);
349 		} else {
350 			if (val <= LONG_MAX)
351 				obj = _PyLong_FromLong(val);
352 			else
353 				obj = PyLong_FromUnsignedLongLong(val);
354 		}
355 		if (is_array)
356 			PyList_SET_ITEM(list, i, obj);
357 	}
358 	if (is_array)
359 		obj = list;
360 	return obj;
361 }
362 #endif
363 
get_dsoname(struct map * map)364 static const char *get_dsoname(struct map *map)
365 {
366 	const char *dsoname = "[unknown]";
367 	struct dso *dso = map ? map__dso(map) : NULL;
368 
369 	if (dso) {
370 		if (symbol_conf.show_kernel_path && dso__long_name(dso))
371 			dsoname = dso__long_name(dso);
372 		else
373 			dsoname = dso__name(dso);
374 	}
375 
376 	return dsoname;
377 }
378 
get_offset(struct symbol * sym,struct addr_location * al)379 static unsigned long get_offset(struct symbol *sym, struct addr_location *al)
380 {
381 	unsigned long offset;
382 
383 	if (al->addr < sym->end)
384 		offset = al->addr - sym->start;
385 	else
386 		offset = al->addr - map__start(al->map) - sym->start;
387 
388 	return offset;
389 }
390 
python_process_callchain(struct perf_sample * sample,struct evsel * evsel,struct addr_location * al)391 static PyObject *python_process_callchain(struct perf_sample *sample,
392 					 struct evsel *evsel,
393 					 struct addr_location *al)
394 {
395 	PyObject *pylist;
396 	struct callchain_cursor *cursor;
397 
398 	pylist = PyList_New(0);
399 	if (!pylist)
400 		Py_FatalError("couldn't create Python list");
401 
402 	if (!symbol_conf.use_callchain || !sample->callchain)
403 		goto exit;
404 
405 	cursor = get_tls_callchain_cursor();
406 	if (thread__resolve_callchain(al->thread, cursor, evsel,
407 				      sample, NULL, NULL,
408 				      scripting_max_stack) != 0) {
409 		pr_err("Failed to resolve callchain. Skipping\n");
410 		goto exit;
411 	}
412 	callchain_cursor_commit(cursor);
413 
414 
415 	while (1) {
416 		PyObject *pyelem;
417 		struct callchain_cursor_node *node;
418 		node = callchain_cursor_current(cursor);
419 		if (!node)
420 			break;
421 
422 		pyelem = PyDict_New();
423 		if (!pyelem)
424 			Py_FatalError("couldn't create Python dictionary");
425 
426 
427 		pydict_set_item_string_decref(pyelem, "ip",
428 				PyLong_FromUnsignedLongLong(node->ip));
429 
430 		if (node->ms.sym) {
431 			PyObject *pysym  = PyDict_New();
432 			if (!pysym)
433 				Py_FatalError("couldn't create Python dictionary");
434 			pydict_set_item_string_decref(pysym, "start",
435 					PyLong_FromUnsignedLongLong(node->ms.sym->start));
436 			pydict_set_item_string_decref(pysym, "end",
437 					PyLong_FromUnsignedLongLong(node->ms.sym->end));
438 			pydict_set_item_string_decref(pysym, "binding",
439 					_PyLong_FromLong(node->ms.sym->binding));
440 			pydict_set_item_string_decref(pysym, "name",
441 					_PyUnicode_FromStringAndSize(node->ms.sym->name,
442 							node->ms.sym->namelen));
443 			pydict_set_item_string_decref(pyelem, "sym", pysym);
444 
445 			if (node->ms.map) {
446 				struct map *map = node->ms.map;
447 				struct addr_location node_al;
448 				unsigned long offset;
449 
450 				addr_location__init(&node_al);
451 				node_al.addr = map__map_ip(map, node->ip);
452 				node_al.map  = map__get(map);
453 				offset = get_offset(node->ms.sym, &node_al);
454 				addr_location__exit(&node_al);
455 
456 				pydict_set_item_string_decref(
457 					pyelem, "sym_off",
458 					PyLong_FromUnsignedLongLong(offset));
459 			}
460 			if (node->srcline && strcmp(":0", node->srcline)) {
461 				pydict_set_item_string_decref(
462 					pyelem, "sym_srcline",
463 					_PyUnicode_FromString(node->srcline));
464 			}
465 		}
466 
467 		if (node->ms.map) {
468 			const char *dsoname = get_dsoname(node->ms.map);
469 
470 			pydict_set_item_string_decref(pyelem, "dso",
471 					_PyUnicode_FromString(dsoname));
472 		}
473 
474 		callchain_cursor_advance(cursor);
475 		PyList_Append(pylist, pyelem);
476 		Py_DECREF(pyelem);
477 	}
478 
479 exit:
480 	return pylist;
481 }
482 
python_process_brstack(struct perf_sample * sample,struct thread * thread)483 static PyObject *python_process_brstack(struct perf_sample *sample,
484 					struct thread *thread)
485 {
486 	struct branch_stack *br = sample->branch_stack;
487 	struct branch_entry *entries = perf_sample__branch_entries(sample);
488 	PyObject *pylist;
489 	u64 i;
490 
491 	pylist = PyList_New(0);
492 	if (!pylist)
493 		Py_FatalError("couldn't create Python list");
494 
495 	if (!(br && br->nr))
496 		goto exit;
497 
498 	for (i = 0; i < br->nr; i++) {
499 		PyObject *pyelem;
500 		struct addr_location al;
501 		const char *dsoname;
502 
503 		pyelem = PyDict_New();
504 		if (!pyelem)
505 			Py_FatalError("couldn't create Python dictionary");
506 
507 		pydict_set_item_string_decref(pyelem, "from",
508 		    PyLong_FromUnsignedLongLong(entries[i].from));
509 		pydict_set_item_string_decref(pyelem, "to",
510 		    PyLong_FromUnsignedLongLong(entries[i].to));
511 		pydict_set_item_string_decref(pyelem, "mispred",
512 		    PyBool_FromLong(entries[i].flags.mispred));
513 		pydict_set_item_string_decref(pyelem, "predicted",
514 		    PyBool_FromLong(entries[i].flags.predicted));
515 		pydict_set_item_string_decref(pyelem, "in_tx",
516 		    PyBool_FromLong(entries[i].flags.in_tx));
517 		pydict_set_item_string_decref(pyelem, "abort",
518 		    PyBool_FromLong(entries[i].flags.abort));
519 		pydict_set_item_string_decref(pyelem, "cycles",
520 		    PyLong_FromUnsignedLongLong(entries[i].flags.cycles));
521 
522 		addr_location__init(&al);
523 		thread__find_map_fb(thread, sample->cpumode,
524 				    entries[i].from, &al);
525 		dsoname = get_dsoname(al.map);
526 		pydict_set_item_string_decref(pyelem, "from_dsoname",
527 					      _PyUnicode_FromString(dsoname));
528 
529 		thread__find_map_fb(thread, sample->cpumode,
530 				    entries[i].to, &al);
531 		dsoname = get_dsoname(al.map);
532 		pydict_set_item_string_decref(pyelem, "to_dsoname",
533 					      _PyUnicode_FromString(dsoname));
534 
535 		addr_location__exit(&al);
536 		PyList_Append(pylist, pyelem);
537 		Py_DECREF(pyelem);
538 	}
539 
540 exit:
541 	return pylist;
542 }
543 
get_symoff(struct symbol * sym,struct addr_location * al,bool print_off,char * bf,int size)544 static int get_symoff(struct symbol *sym, struct addr_location *al,
545 		      bool print_off, char *bf, int size)
546 {
547 	unsigned long offset;
548 
549 	if (!sym || !sym->name[0])
550 		return scnprintf(bf, size, "%s", "[unknown]");
551 
552 	if (!print_off)
553 		return scnprintf(bf, size, "%s", sym->name);
554 
555 	offset = get_offset(sym, al);
556 
557 	return scnprintf(bf, size, "%s+0x%x", sym->name, offset);
558 }
559 
get_br_mspred(struct branch_flags * flags,char * bf,int size)560 static int get_br_mspred(struct branch_flags *flags, char *bf, int size)
561 {
562 	if (!flags->mispred  && !flags->predicted)
563 		return scnprintf(bf, size, "%s", "-");
564 
565 	if (flags->mispred)
566 		return scnprintf(bf, size, "%s", "M");
567 
568 	return scnprintf(bf, size, "%s", "P");
569 }
570 
python_process_brstacksym(struct perf_sample * sample,struct thread * thread)571 static PyObject *python_process_brstacksym(struct perf_sample *sample,
572 					   struct thread *thread)
573 {
574 	struct branch_stack *br = sample->branch_stack;
575 	struct branch_entry *entries = perf_sample__branch_entries(sample);
576 	PyObject *pylist;
577 	u64 i;
578 	char bf[512];
579 
580 	pylist = PyList_New(0);
581 	if (!pylist)
582 		Py_FatalError("couldn't create Python list");
583 
584 	if (!(br && br->nr))
585 		goto exit;
586 
587 	for (i = 0; i < br->nr; i++) {
588 		PyObject *pyelem;
589 		struct addr_location al;
590 
591 		addr_location__init(&al);
592 		pyelem = PyDict_New();
593 		if (!pyelem)
594 			Py_FatalError("couldn't create Python dictionary");
595 
596 		thread__find_symbol_fb(thread, sample->cpumode,
597 				       entries[i].from, &al);
598 		get_symoff(al.sym, &al, true, bf, sizeof(bf));
599 		pydict_set_item_string_decref(pyelem, "from",
600 					      _PyUnicode_FromString(bf));
601 
602 		thread__find_symbol_fb(thread, sample->cpumode,
603 				       entries[i].to, &al);
604 		get_symoff(al.sym, &al, true, bf, sizeof(bf));
605 		pydict_set_item_string_decref(pyelem, "to",
606 					      _PyUnicode_FromString(bf));
607 
608 		get_br_mspred(&entries[i].flags, bf, sizeof(bf));
609 		pydict_set_item_string_decref(pyelem, "pred",
610 					      _PyUnicode_FromString(bf));
611 
612 		if (entries[i].flags.in_tx) {
613 			pydict_set_item_string_decref(pyelem, "in_tx",
614 					      _PyUnicode_FromString("X"));
615 		} else {
616 			pydict_set_item_string_decref(pyelem, "in_tx",
617 					      _PyUnicode_FromString("-"));
618 		}
619 
620 		if (entries[i].flags.abort) {
621 			pydict_set_item_string_decref(pyelem, "abort",
622 					      _PyUnicode_FromString("A"));
623 		} else {
624 			pydict_set_item_string_decref(pyelem, "abort",
625 					      _PyUnicode_FromString("-"));
626 		}
627 
628 		PyList_Append(pylist, pyelem);
629 		Py_DECREF(pyelem);
630 		addr_location__exit(&al);
631 	}
632 
633 exit:
634 	return pylist;
635 }
636 
get_sample_value_as_tuple(struct sample_read_value * value,u64 read_format)637 static PyObject *get_sample_value_as_tuple(struct sample_read_value *value,
638 					   u64 read_format)
639 {
640 	PyObject *t;
641 
642 	t = PyTuple_New(3);
643 	if (!t)
644 		Py_FatalError("couldn't create Python tuple");
645 	PyTuple_SetItem(t, 0, PyLong_FromUnsignedLongLong(value->id));
646 	PyTuple_SetItem(t, 1, PyLong_FromUnsignedLongLong(value->value));
647 	if (read_format & PERF_FORMAT_LOST)
648 		PyTuple_SetItem(t, 2, PyLong_FromUnsignedLongLong(value->lost));
649 
650 	return t;
651 }
652 
set_sample_read_in_dict(PyObject * dict_sample,struct perf_sample * sample,struct evsel * evsel)653 static void set_sample_read_in_dict(PyObject *dict_sample,
654 					 struct perf_sample *sample,
655 					 struct evsel *evsel)
656 {
657 	u64 read_format = evsel->core.attr.read_format;
658 	PyObject *values;
659 	unsigned int i;
660 
661 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
662 		pydict_set_item_string_decref(dict_sample, "time_enabled",
663 			PyLong_FromUnsignedLongLong(sample->read.time_enabled));
664 	}
665 
666 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
667 		pydict_set_item_string_decref(dict_sample, "time_running",
668 			PyLong_FromUnsignedLongLong(sample->read.time_running));
669 	}
670 
671 	if (read_format & PERF_FORMAT_GROUP)
672 		values = PyList_New(sample->read.group.nr);
673 	else
674 		values = PyList_New(1);
675 
676 	if (!values)
677 		Py_FatalError("couldn't create Python list");
678 
679 	if (read_format & PERF_FORMAT_GROUP) {
680 		struct sample_read_value *v = sample->read.group.values;
681 
682 		i = 0;
683 		sample_read_group__for_each(v, sample->read.group.nr, read_format) {
684 			PyObject *t = get_sample_value_as_tuple(v, read_format);
685 			PyList_SET_ITEM(values, i, t);
686 			i++;
687 		}
688 	} else {
689 		PyObject *t = get_sample_value_as_tuple(&sample->read.one,
690 							read_format);
691 		PyList_SET_ITEM(values, 0, t);
692 	}
693 	pydict_set_item_string_decref(dict_sample, "values", values);
694 }
695 
set_sample_datasrc_in_dict(PyObject * dict,struct perf_sample * sample)696 static void set_sample_datasrc_in_dict(PyObject *dict,
697 				      struct perf_sample *sample)
698 {
699 	struct mem_info *mi = mem_info__new();
700 	char decode[100];
701 
702 	if (!mi)
703 		Py_FatalError("couldn't create mem-info");
704 
705 	pydict_set_item_string_decref(dict, "datasrc",
706 			PyLong_FromUnsignedLongLong(sample->data_src));
707 
708 	mem_info__data_src(mi)->val = sample->data_src;
709 	perf_script__meminfo_scnprintf(decode, 100, mi);
710 	mem_info__put(mi);
711 
712 	pydict_set_item_string_decref(dict, "datasrc_decode",
713 			_PyUnicode_FromString(decode));
714 }
715 
regs_map(struct regs_dump * regs,uint64_t mask,const char * arch,char * bf,int size)716 static void regs_map(struct regs_dump *regs, uint64_t mask, const char *arch, char *bf, int size)
717 {
718 	unsigned int i = 0, r;
719 	int printed = 0;
720 
721 	bf[0] = 0;
722 
723 	if (size <= 0)
724 		return;
725 
726 	if (!regs || !regs->regs)
727 		return;
728 
729 	for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
730 		u64 val = regs->regs[i++];
731 
732 		printed += scnprintf(bf + printed, size - printed,
733 				     "%5s:0x%" PRIx64 " ",
734 				     perf_reg_name(r, arch), val);
735 	}
736 }
737 
738 #define MAX_REG_SIZE 128
739 
set_regs_in_dict(PyObject * dict,struct perf_sample * sample,struct evsel * evsel)740 static int set_regs_in_dict(PyObject *dict,
741 			     struct perf_sample *sample,
742 			     struct evsel *evsel)
743 {
744 	struct perf_event_attr *attr = &evsel->core.attr;
745 	const char *arch = perf_env__arch(evsel__env(evsel));
746 
747 	int size = (__sw_hweight64(attr->sample_regs_intr) * MAX_REG_SIZE) + 1;
748 	char *bf = NULL;
749 
750 	if (sample->intr_regs) {
751 		bf = malloc(size);
752 		if (!bf)
753 			return -1;
754 
755 		regs_map(sample->intr_regs, attr->sample_regs_intr, arch, bf, size);
756 
757 		pydict_set_item_string_decref(dict, "iregs",
758 					_PyUnicode_FromString(bf));
759 	}
760 
761 	if (sample->user_regs) {
762 		if (!bf) {
763 			bf = malloc(size);
764 			if (!bf)
765 				return -1;
766 		}
767 		regs_map(sample->user_regs, attr->sample_regs_user, arch, bf, size);
768 
769 		pydict_set_item_string_decref(dict, "uregs",
770 					_PyUnicode_FromString(bf));
771 	}
772 	free(bf);
773 
774 	return 0;
775 }
776 
set_sym_in_dict(PyObject * dict,struct addr_location * al,const char * dso_field,const char * dso_bid_field,const char * dso_map_start,const char * dso_map_end,const char * sym_field,const char * symoff_field,const char * map_pgoff)777 static void set_sym_in_dict(PyObject *dict, struct addr_location *al,
778 			    const char *dso_field, const char *dso_bid_field,
779 			    const char *dso_map_start, const char *dso_map_end,
780 			    const char *sym_field, const char *symoff_field,
781 			    const char *map_pgoff)
782 {
783 	if (al->map) {
784 		char sbuild_id[SBUILD_ID_SIZE];
785 		struct dso *dso = map__dso(al->map);
786 
787 		pydict_set_item_string_decref(dict, dso_field,
788 					      _PyUnicode_FromString(dso__name(dso)));
789 		build_id__snprintf(dso__bid(dso), sbuild_id, sizeof(sbuild_id));
790 		pydict_set_item_string_decref(dict, dso_bid_field,
791 			_PyUnicode_FromString(sbuild_id));
792 		pydict_set_item_string_decref(dict, dso_map_start,
793 			PyLong_FromUnsignedLong(map__start(al->map)));
794 		pydict_set_item_string_decref(dict, dso_map_end,
795 			PyLong_FromUnsignedLong(map__end(al->map)));
796 		pydict_set_item_string_decref(dict, map_pgoff,
797 			PyLong_FromUnsignedLongLong(map__pgoff(al->map)));
798 	}
799 	if (al->sym) {
800 		pydict_set_item_string_decref(dict, sym_field,
801 			_PyUnicode_FromString(al->sym->name));
802 		pydict_set_item_string_decref(dict, symoff_field,
803 			PyLong_FromUnsignedLong(get_offset(al->sym, al)));
804 	}
805 }
806 
set_sample_flags(PyObject * dict,u32 flags)807 static void set_sample_flags(PyObject *dict, u32 flags)
808 {
809 	const char *ch = PERF_IP_FLAG_CHARS;
810 	char *p, str[33];
811 
812 	for (p = str; *ch; ch++, flags >>= 1) {
813 		if (flags & 1)
814 			*p++ = *ch;
815 	}
816 	*p = 0;
817 	pydict_set_item_string_decref(dict, "flags", _PyUnicode_FromString(str));
818 }
819 
python_process_sample_flags(struct perf_sample * sample,PyObject * dict_sample)820 static void python_process_sample_flags(struct perf_sample *sample, PyObject *dict_sample)
821 {
822 	char flags_disp[SAMPLE_FLAGS_BUF_SIZE];
823 
824 	set_sample_flags(dict_sample, sample->flags);
825 	perf_sample__sprintf_flags(sample->flags, flags_disp, sizeof(flags_disp));
826 	pydict_set_item_string_decref(dict_sample, "flags_disp",
827 		_PyUnicode_FromString(flags_disp));
828 }
829 
get_perf_sample_dict(struct perf_sample * sample,struct evsel * evsel,struct addr_location * al,struct addr_location * addr_al,PyObject * callchain)830 static PyObject *get_perf_sample_dict(struct perf_sample *sample,
831 					 struct evsel *evsel,
832 					 struct addr_location *al,
833 					 struct addr_location *addr_al,
834 					 PyObject *callchain)
835 {
836 	PyObject *dict, *dict_sample, *brstack, *brstacksym;
837 
838 	dict = PyDict_New();
839 	if (!dict)
840 		Py_FatalError("couldn't create Python dictionary");
841 
842 	dict_sample = PyDict_New();
843 	if (!dict_sample)
844 		Py_FatalError("couldn't create Python dictionary");
845 
846 	pydict_set_item_string_decref(dict, "ev_name", _PyUnicode_FromString(evsel__name(evsel)));
847 	pydict_set_item_string_decref(dict, "attr", _PyBytes_FromStringAndSize((const char *)&evsel->core.attr, sizeof(evsel->core.attr)));
848 
849 	pydict_set_item_string_decref(dict_sample, "id",
850 			PyLong_FromUnsignedLongLong(sample->id));
851 	pydict_set_item_string_decref(dict_sample, "stream_id",
852 			PyLong_FromUnsignedLongLong(sample->stream_id));
853 	pydict_set_item_string_decref(dict_sample, "pid",
854 			_PyLong_FromLong(sample->pid));
855 	pydict_set_item_string_decref(dict_sample, "tid",
856 			_PyLong_FromLong(sample->tid));
857 	pydict_set_item_string_decref(dict_sample, "cpu",
858 			_PyLong_FromLong(sample->cpu));
859 	pydict_set_item_string_decref(dict_sample, "ip",
860 			PyLong_FromUnsignedLongLong(sample->ip));
861 	pydict_set_item_string_decref(dict_sample, "time",
862 			PyLong_FromUnsignedLongLong(sample->time));
863 	pydict_set_item_string_decref(dict_sample, "period",
864 			PyLong_FromUnsignedLongLong(sample->period));
865 	pydict_set_item_string_decref(dict_sample, "phys_addr",
866 			PyLong_FromUnsignedLongLong(sample->phys_addr));
867 	pydict_set_item_string_decref(dict_sample, "addr",
868 			PyLong_FromUnsignedLongLong(sample->addr));
869 	set_sample_read_in_dict(dict_sample, sample, evsel);
870 	pydict_set_item_string_decref(dict_sample, "weight",
871 			PyLong_FromUnsignedLongLong(sample->weight));
872 	pydict_set_item_string_decref(dict_sample, "ins_lat",
873 			PyLong_FromUnsignedLong(sample->ins_lat));
874 	pydict_set_item_string_decref(dict_sample, "transaction",
875 			PyLong_FromUnsignedLongLong(sample->transaction));
876 	set_sample_datasrc_in_dict(dict_sample, sample);
877 	pydict_set_item_string_decref(dict, "sample", dict_sample);
878 
879 	pydict_set_item_string_decref(dict, "raw_buf", _PyBytes_FromStringAndSize(
880 			(const char *)sample->raw_data, sample->raw_size));
881 	pydict_set_item_string_decref(dict, "comm",
882 			_PyUnicode_FromString(thread__comm_str(al->thread)));
883 	set_sym_in_dict(dict, al, "dso", "dso_bid", "dso_map_start", "dso_map_end",
884 			"symbol", "symoff", "map_pgoff");
885 
886 	pydict_set_item_string_decref(dict, "callchain", callchain);
887 
888 	brstack = python_process_brstack(sample, al->thread);
889 	pydict_set_item_string_decref(dict, "brstack", brstack);
890 
891 	brstacksym = python_process_brstacksym(sample, al->thread);
892 	pydict_set_item_string_decref(dict, "brstacksym", brstacksym);
893 
894 	if (sample->machine_pid) {
895 		pydict_set_item_string_decref(dict_sample, "machine_pid",
896 				_PyLong_FromLong(sample->machine_pid));
897 		pydict_set_item_string_decref(dict_sample, "vcpu",
898 				_PyLong_FromLong(sample->vcpu));
899 	}
900 
901 	pydict_set_item_string_decref(dict_sample, "cpumode",
902 			_PyLong_FromLong((unsigned long)sample->cpumode));
903 
904 	if (addr_al) {
905 		pydict_set_item_string_decref(dict_sample, "addr_correlates_sym",
906 			PyBool_FromLong(1));
907 		set_sym_in_dict(dict_sample, addr_al, "addr_dso", "addr_dso_bid",
908 				"addr_dso_map_start", "addr_dso_map_end",
909 				"addr_symbol", "addr_symoff", "addr_map_pgoff");
910 	}
911 
912 	if (sample->flags)
913 		python_process_sample_flags(sample, dict_sample);
914 
915 	/* Instructions per cycle (IPC) */
916 	if (sample->insn_cnt && sample->cyc_cnt) {
917 		pydict_set_item_string_decref(dict_sample, "insn_cnt",
918 			PyLong_FromUnsignedLongLong(sample->insn_cnt));
919 		pydict_set_item_string_decref(dict_sample, "cyc_cnt",
920 			PyLong_FromUnsignedLongLong(sample->cyc_cnt));
921 	}
922 
923 	if (set_regs_in_dict(dict, sample, evsel))
924 		Py_FatalError("Failed to setting regs in dict");
925 
926 	return dict;
927 }
928 
929 #ifdef HAVE_LIBTRACEEVENT
python_process_tracepoint(struct perf_sample * sample,struct evsel * evsel,struct addr_location * al,struct addr_location * addr_al)930 static void python_process_tracepoint(struct perf_sample *sample,
931 				      struct evsel *evsel,
932 				      struct addr_location *al,
933 				      struct addr_location *addr_al)
934 {
935 	struct tep_event *event;
936 	PyObject *handler, *context, *t, *obj = NULL, *callchain;
937 	PyObject *dict = NULL, *all_entries_dict = NULL;
938 	static char handler_name[256];
939 	struct tep_format_field *field;
940 	unsigned long s, ns;
941 	unsigned n = 0;
942 	int pid;
943 	int cpu = sample->cpu;
944 	void *data = sample->raw_data;
945 	unsigned long long nsecs = sample->time;
946 	const char *comm = thread__comm_str(al->thread);
947 	const char *default_handler_name = "trace_unhandled";
948 	DECLARE_BITMAP(events_defined, TRACE_EVENT_TYPE_MAX);
949 
950 	bitmap_zero(events_defined, TRACE_EVENT_TYPE_MAX);
951 
952 	event = evsel__tp_format(evsel);
953 	if (!event) {
954 		snprintf(handler_name, sizeof(handler_name),
955 			 "ug! no event found for type %" PRIu64, (u64)evsel->core.attr.config);
956 		Py_FatalError(handler_name);
957 	}
958 
959 	pid = raw_field_value(event, "common_pid", data);
960 
961 	sprintf(handler_name, "%s__%s", event->system, event->name);
962 
963 	if (!__test_and_set_bit(event->id, events_defined))
964 		define_event_symbols(event, handler_name, event->print_fmt.args);
965 
966 	handler = get_handler(handler_name);
967 	if (!handler) {
968 		handler = get_handler(default_handler_name);
969 		if (!handler)
970 			return;
971 		dict = PyDict_New();
972 		if (!dict)
973 			Py_FatalError("couldn't create Python dict");
974 	}
975 
976 	t = PyTuple_New(MAX_FIELDS);
977 	if (!t)
978 		Py_FatalError("couldn't create Python tuple");
979 
980 
981 	s = nsecs / NSEC_PER_SEC;
982 	ns = nsecs - s * NSEC_PER_SEC;
983 
984 	context = _PyCapsule_New(scripting_context, NULL, NULL);
985 
986 	PyTuple_SetItem(t, n++, _PyUnicode_FromString(handler_name));
987 	PyTuple_SetItem(t, n++, context);
988 
989 	/* ip unwinding */
990 	callchain = python_process_callchain(sample, evsel, al);
991 	/* Need an additional reference for the perf_sample dict */
992 	Py_INCREF(callchain);
993 
994 	if (!dict) {
995 		PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
996 		PyTuple_SetItem(t, n++, _PyLong_FromLong(s));
997 		PyTuple_SetItem(t, n++, _PyLong_FromLong(ns));
998 		PyTuple_SetItem(t, n++, _PyLong_FromLong(pid));
999 		PyTuple_SetItem(t, n++, _PyUnicode_FromString(comm));
1000 		PyTuple_SetItem(t, n++, callchain);
1001 	} else {
1002 		pydict_set_item_string_decref(dict, "common_cpu", _PyLong_FromLong(cpu));
1003 		pydict_set_item_string_decref(dict, "common_s", _PyLong_FromLong(s));
1004 		pydict_set_item_string_decref(dict, "common_ns", _PyLong_FromLong(ns));
1005 		pydict_set_item_string_decref(dict, "common_pid", _PyLong_FromLong(pid));
1006 		pydict_set_item_string_decref(dict, "common_comm", _PyUnicode_FromString(comm));
1007 		pydict_set_item_string_decref(dict, "common_callchain", callchain);
1008 	}
1009 	for (field = event->format.fields; field; field = field->next) {
1010 		unsigned int offset, len;
1011 		unsigned long long val;
1012 
1013 		if (field->flags & TEP_FIELD_IS_ARRAY) {
1014 			offset = field->offset;
1015 			len    = field->size;
1016 			if (field->flags & TEP_FIELD_IS_DYNAMIC) {
1017 				val     = tep_read_number(scripting_context->pevent,
1018 							  data + offset, len);
1019 				offset  = val;
1020 				len     = offset >> 16;
1021 				offset &= 0xffff;
1022 				if (tep_field_is_relative(field->flags))
1023 					offset += field->offset + field->size;
1024 			}
1025 			if (field->flags & TEP_FIELD_IS_STRING &&
1026 			    is_printable_array(data + offset, len)) {
1027 				obj = _PyUnicode_FromString((char *) data + offset);
1028 			} else {
1029 				obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
1030 				field->flags &= ~TEP_FIELD_IS_STRING;
1031 			}
1032 		} else { /* FIELD_IS_NUMERIC */
1033 			obj = get_field_numeric_entry(event, field, data);
1034 		}
1035 		if (!dict)
1036 			PyTuple_SetItem(t, n++, obj);
1037 		else
1038 			pydict_set_item_string_decref(dict, field->name, obj);
1039 
1040 	}
1041 
1042 	if (dict)
1043 		PyTuple_SetItem(t, n++, dict);
1044 
1045 	if (get_argument_count(handler) == (int) n + 1) {
1046 		all_entries_dict = get_perf_sample_dict(sample, evsel, al, addr_al,
1047 			callchain);
1048 		PyTuple_SetItem(t, n++,	all_entries_dict);
1049 	} else {
1050 		Py_DECREF(callchain);
1051 	}
1052 
1053 	if (_PyTuple_Resize(&t, n) == -1)
1054 		Py_FatalError("error resizing Python tuple");
1055 
1056 	if (!dict)
1057 		call_object(handler, t, handler_name);
1058 	else
1059 		call_object(handler, t, default_handler_name);
1060 
1061 	Py_DECREF(t);
1062 }
1063 #else
python_process_tracepoint(struct perf_sample * sample __maybe_unused,struct evsel * evsel __maybe_unused,struct addr_location * al __maybe_unused,struct addr_location * addr_al __maybe_unused)1064 static void python_process_tracepoint(struct perf_sample *sample __maybe_unused,
1065 				      struct evsel *evsel __maybe_unused,
1066 				      struct addr_location *al __maybe_unused,
1067 				      struct addr_location *addr_al __maybe_unused)
1068 {
1069 	fprintf(stderr, "Tracepoint events are not supported because "
1070 			"perf is not linked with libtraceevent.\n");
1071 }
1072 #endif
1073 
tuple_new(unsigned int sz)1074 static PyObject *tuple_new(unsigned int sz)
1075 {
1076 	PyObject *t;
1077 
1078 	t = PyTuple_New(sz);
1079 	if (!t)
1080 		Py_FatalError("couldn't create Python tuple");
1081 	return t;
1082 }
1083 
tuple_set_s64(PyObject * t,unsigned int pos,s64 val)1084 static int tuple_set_s64(PyObject *t, unsigned int pos, s64 val)
1085 {
1086 #if BITS_PER_LONG == 64
1087 	return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
1088 #endif
1089 #if BITS_PER_LONG == 32
1090 	return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
1091 #endif
1092 }
1093 
1094 /*
1095  * Databases support only signed 64-bit numbers, so even though we are
1096  * exporting a u64, it must be as s64.
1097  */
1098 #define tuple_set_d64 tuple_set_s64
1099 
tuple_set_u64(PyObject * t,unsigned int pos,u64 val)1100 static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
1101 {
1102 #if BITS_PER_LONG == 64
1103 	return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
1104 #endif
1105 #if BITS_PER_LONG == 32
1106 	return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLongLong(val));
1107 #endif
1108 }
1109 
tuple_set_u32(PyObject * t,unsigned int pos,u32 val)1110 static int tuple_set_u32(PyObject *t, unsigned int pos, u32 val)
1111 {
1112 	return PyTuple_SetItem(t, pos, PyLong_FromUnsignedLong(val));
1113 }
1114 
tuple_set_s32(PyObject * t,unsigned int pos,s32 val)1115 static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
1116 {
1117 	return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
1118 }
1119 
tuple_set_bool(PyObject * t,unsigned int pos,bool val)1120 static int tuple_set_bool(PyObject *t, unsigned int pos, bool val)
1121 {
1122 	return PyTuple_SetItem(t, pos, PyBool_FromLong(val));
1123 }
1124 
tuple_set_string(PyObject * t,unsigned int pos,const char * s)1125 static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
1126 {
1127 	return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
1128 }
1129 
tuple_set_bytes(PyObject * t,unsigned int pos,void * bytes,unsigned int sz)1130 static int tuple_set_bytes(PyObject *t, unsigned int pos, void *bytes,
1131 			   unsigned int sz)
1132 {
1133 	return PyTuple_SetItem(t, pos, _PyBytes_FromStringAndSize(bytes, sz));
1134 }
1135 
python_export_evsel(struct db_export * dbe,struct evsel * evsel)1136 static int python_export_evsel(struct db_export *dbe, struct evsel *evsel)
1137 {
1138 	struct tables *tables = container_of(dbe, struct tables, dbe);
1139 	PyObject *t;
1140 
1141 	t = tuple_new(2);
1142 
1143 	tuple_set_d64(t, 0, evsel->db_id);
1144 	tuple_set_string(t, 1, evsel__name(evsel));
1145 
1146 	call_object(tables->evsel_handler, t, "evsel_table");
1147 
1148 	Py_DECREF(t);
1149 
1150 	return 0;
1151 }
1152 
python_export_machine(struct db_export * dbe,struct machine * machine)1153 static int python_export_machine(struct db_export *dbe,
1154 				 struct machine *machine)
1155 {
1156 	struct tables *tables = container_of(dbe, struct tables, dbe);
1157 	PyObject *t;
1158 
1159 	t = tuple_new(3);
1160 
1161 	tuple_set_d64(t, 0, machine->db_id);
1162 	tuple_set_s32(t, 1, machine->pid);
1163 	tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");
1164 
1165 	call_object(tables->machine_handler, t, "machine_table");
1166 
1167 	Py_DECREF(t);
1168 
1169 	return 0;
1170 }
1171 
python_export_thread(struct db_export * dbe,struct thread * thread,u64 main_thread_db_id,struct machine * machine)1172 static int python_export_thread(struct db_export *dbe, struct thread *thread,
1173 				u64 main_thread_db_id, struct machine *machine)
1174 {
1175 	struct tables *tables = container_of(dbe, struct tables, dbe);
1176 	PyObject *t;
1177 
1178 	t = tuple_new(5);
1179 
1180 	tuple_set_d64(t, 0, thread__db_id(thread));
1181 	tuple_set_d64(t, 1, machine->db_id);
1182 	tuple_set_d64(t, 2, main_thread_db_id);
1183 	tuple_set_s32(t, 3, thread__pid(thread));
1184 	tuple_set_s32(t, 4, thread__tid(thread));
1185 
1186 	call_object(tables->thread_handler, t, "thread_table");
1187 
1188 	Py_DECREF(t);
1189 
1190 	return 0;
1191 }
1192 
python_export_comm(struct db_export * dbe,struct comm * comm,struct thread * thread)1193 static int python_export_comm(struct db_export *dbe, struct comm *comm,
1194 			      struct thread *thread)
1195 {
1196 	struct tables *tables = container_of(dbe, struct tables, dbe);
1197 	PyObject *t;
1198 
1199 	t = tuple_new(5);
1200 
1201 	tuple_set_d64(t, 0, comm->db_id);
1202 	tuple_set_string(t, 1, comm__str(comm));
1203 	tuple_set_d64(t, 2, thread__db_id(thread));
1204 	tuple_set_d64(t, 3, comm->start);
1205 	tuple_set_s32(t, 4, comm->exec);
1206 
1207 	call_object(tables->comm_handler, t, "comm_table");
1208 
1209 	Py_DECREF(t);
1210 
1211 	return 0;
1212 }
1213 
python_export_comm_thread(struct db_export * dbe,u64 db_id,struct comm * comm,struct thread * thread)1214 static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
1215 				     struct comm *comm, struct thread *thread)
1216 {
1217 	struct tables *tables = container_of(dbe, struct tables, dbe);
1218 	PyObject *t;
1219 
1220 	t = tuple_new(3);
1221 
1222 	tuple_set_d64(t, 0, db_id);
1223 	tuple_set_d64(t, 1, comm->db_id);
1224 	tuple_set_d64(t, 2, thread__db_id(thread));
1225 
1226 	call_object(tables->comm_thread_handler, t, "comm_thread_table");
1227 
1228 	Py_DECREF(t);
1229 
1230 	return 0;
1231 }
1232 
python_export_dso(struct db_export * dbe,struct dso * dso,struct machine * machine)1233 static int python_export_dso(struct db_export *dbe, struct dso *dso,
1234 			     struct machine *machine)
1235 {
1236 	struct tables *tables = container_of(dbe, struct tables, dbe);
1237 	char sbuild_id[SBUILD_ID_SIZE];
1238 	PyObject *t;
1239 
1240 	build_id__snprintf(dso__bid(dso), sbuild_id, sizeof(sbuild_id));
1241 
1242 	t = tuple_new(5);
1243 
1244 	tuple_set_d64(t, 0, dso__db_id(dso));
1245 	tuple_set_d64(t, 1, machine->db_id);
1246 	tuple_set_string(t, 2, dso__short_name(dso));
1247 	tuple_set_string(t, 3, dso__long_name(dso));
1248 	tuple_set_string(t, 4, sbuild_id);
1249 
1250 	call_object(tables->dso_handler, t, "dso_table");
1251 
1252 	Py_DECREF(t);
1253 
1254 	return 0;
1255 }
1256 
python_export_symbol(struct db_export * dbe,struct symbol * sym,struct dso * dso)1257 static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
1258 				struct dso *dso)
1259 {
1260 	struct tables *tables = container_of(dbe, struct tables, dbe);
1261 	u64 *sym_db_id = symbol__priv(sym);
1262 	PyObject *t;
1263 
1264 	t = tuple_new(6);
1265 
1266 	tuple_set_d64(t, 0, *sym_db_id);
1267 	tuple_set_d64(t, 1, dso__db_id(dso));
1268 	tuple_set_d64(t, 2, sym->start);
1269 	tuple_set_d64(t, 3, sym->end);
1270 	tuple_set_s32(t, 4, sym->binding);
1271 	tuple_set_string(t, 5, sym->name);
1272 
1273 	call_object(tables->symbol_handler, t, "symbol_table");
1274 
1275 	Py_DECREF(t);
1276 
1277 	return 0;
1278 }
1279 
python_export_branch_type(struct db_export * dbe,u32 branch_type,const char * name)1280 static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
1281 				     const char *name)
1282 {
1283 	struct tables *tables = container_of(dbe, struct tables, dbe);
1284 	PyObject *t;
1285 
1286 	t = tuple_new(2);
1287 
1288 	tuple_set_s32(t, 0, branch_type);
1289 	tuple_set_string(t, 1, name);
1290 
1291 	call_object(tables->branch_type_handler, t, "branch_type_table");
1292 
1293 	Py_DECREF(t);
1294 
1295 	return 0;
1296 }
1297 
python_export_sample_table(struct db_export * dbe,struct export_sample * es)1298 static void python_export_sample_table(struct db_export *dbe,
1299 				       struct export_sample *es)
1300 {
1301 	struct tables *tables = container_of(dbe, struct tables, dbe);
1302 	PyObject *t;
1303 
1304 	t = tuple_new(28);
1305 
1306 	tuple_set_d64(t, 0, es->db_id);
1307 	tuple_set_d64(t, 1, es->evsel->db_id);
1308 	tuple_set_d64(t, 2, maps__machine(thread__maps(es->al->thread))->db_id);
1309 	tuple_set_d64(t, 3, thread__db_id(es->al->thread));
1310 	tuple_set_d64(t, 4, es->comm_db_id);
1311 	tuple_set_d64(t, 5, es->dso_db_id);
1312 	tuple_set_d64(t, 6, es->sym_db_id);
1313 	tuple_set_d64(t, 7, es->offset);
1314 	tuple_set_d64(t, 8, es->sample->ip);
1315 	tuple_set_d64(t, 9, es->sample->time);
1316 	tuple_set_s32(t, 10, es->sample->cpu);
1317 	tuple_set_d64(t, 11, es->addr_dso_db_id);
1318 	tuple_set_d64(t, 12, es->addr_sym_db_id);
1319 	tuple_set_d64(t, 13, es->addr_offset);
1320 	tuple_set_d64(t, 14, es->sample->addr);
1321 	tuple_set_d64(t, 15, es->sample->period);
1322 	tuple_set_d64(t, 16, es->sample->weight);
1323 	tuple_set_d64(t, 17, es->sample->transaction);
1324 	tuple_set_d64(t, 18, es->sample->data_src);
1325 	tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
1326 	tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
1327 	tuple_set_d64(t, 21, es->call_path_id);
1328 	tuple_set_d64(t, 22, es->sample->insn_cnt);
1329 	tuple_set_d64(t, 23, es->sample->cyc_cnt);
1330 	tuple_set_s32(t, 24, es->sample->flags);
1331 	tuple_set_d64(t, 25, es->sample->id);
1332 	tuple_set_d64(t, 26, es->sample->stream_id);
1333 	tuple_set_u32(t, 27, es->sample->ins_lat);
1334 
1335 	call_object(tables->sample_handler, t, "sample_table");
1336 
1337 	Py_DECREF(t);
1338 }
1339 
python_export_synth(struct db_export * dbe,struct export_sample * es)1340 static void python_export_synth(struct db_export *dbe, struct export_sample *es)
1341 {
1342 	struct tables *tables = container_of(dbe, struct tables, dbe);
1343 	PyObject *t;
1344 
1345 	t = tuple_new(3);
1346 
1347 	tuple_set_d64(t, 0, es->db_id);
1348 	tuple_set_d64(t, 1, es->evsel->core.attr.config);
1349 	tuple_set_bytes(t, 2, es->sample->raw_data, es->sample->raw_size);
1350 
1351 	call_object(tables->synth_handler, t, "synth_data");
1352 
1353 	Py_DECREF(t);
1354 }
1355 
python_export_sample(struct db_export * dbe,struct export_sample * es)1356 static int python_export_sample(struct db_export *dbe,
1357 				struct export_sample *es)
1358 {
1359 	struct tables *tables = container_of(dbe, struct tables, dbe);
1360 
1361 	python_export_sample_table(dbe, es);
1362 
1363 	if (es->evsel->core.attr.type == PERF_TYPE_SYNTH && tables->synth_handler)
1364 		python_export_synth(dbe, es);
1365 
1366 	return 0;
1367 }
1368 
python_export_call_path(struct db_export * dbe,struct call_path * cp)1369 static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
1370 {
1371 	struct tables *tables = container_of(dbe, struct tables, dbe);
1372 	PyObject *t;
1373 	u64 parent_db_id, sym_db_id;
1374 
1375 	parent_db_id = cp->parent ? cp->parent->db_id : 0;
1376 	sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;
1377 
1378 	t = tuple_new(4);
1379 
1380 	tuple_set_d64(t, 0, cp->db_id);
1381 	tuple_set_d64(t, 1, parent_db_id);
1382 	tuple_set_d64(t, 2, sym_db_id);
1383 	tuple_set_d64(t, 3, cp->ip);
1384 
1385 	call_object(tables->call_path_handler, t, "call_path_table");
1386 
1387 	Py_DECREF(t);
1388 
1389 	return 0;
1390 }
1391 
python_export_call_return(struct db_export * dbe,struct call_return * cr)1392 static int python_export_call_return(struct db_export *dbe,
1393 				     struct call_return *cr)
1394 {
1395 	struct tables *tables = container_of(dbe, struct tables, dbe);
1396 	u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
1397 	PyObject *t;
1398 
1399 	t = tuple_new(14);
1400 
1401 	tuple_set_d64(t, 0, cr->db_id);
1402 	tuple_set_d64(t, 1, thread__db_id(cr->thread));
1403 	tuple_set_d64(t, 2, comm_db_id);
1404 	tuple_set_d64(t, 3, cr->cp->db_id);
1405 	tuple_set_d64(t, 4, cr->call_time);
1406 	tuple_set_d64(t, 5, cr->return_time);
1407 	tuple_set_d64(t, 6, cr->branch_count);
1408 	tuple_set_d64(t, 7, cr->call_ref);
1409 	tuple_set_d64(t, 8, cr->return_ref);
1410 	tuple_set_d64(t, 9, cr->cp->parent->db_id);
1411 	tuple_set_s32(t, 10, cr->flags);
1412 	tuple_set_d64(t, 11, cr->parent_db_id);
1413 	tuple_set_d64(t, 12, cr->insn_count);
1414 	tuple_set_d64(t, 13, cr->cyc_count);
1415 
1416 	call_object(tables->call_return_handler, t, "call_return_table");
1417 
1418 	Py_DECREF(t);
1419 
1420 	return 0;
1421 }
1422 
python_export_context_switch(struct db_export * dbe,u64 db_id,struct machine * machine,struct perf_sample * sample,u64 th_out_id,u64 comm_out_id,u64 th_in_id,u64 comm_in_id,int flags)1423 static int python_export_context_switch(struct db_export *dbe, u64 db_id,
1424 					struct machine *machine,
1425 					struct perf_sample *sample,
1426 					u64 th_out_id, u64 comm_out_id,
1427 					u64 th_in_id, u64 comm_in_id, int flags)
1428 {
1429 	struct tables *tables = container_of(dbe, struct tables, dbe);
1430 	PyObject *t;
1431 
1432 	t = tuple_new(9);
1433 
1434 	tuple_set_d64(t, 0, db_id);
1435 	tuple_set_d64(t, 1, machine->db_id);
1436 	tuple_set_d64(t, 2, sample->time);
1437 	tuple_set_s32(t, 3, sample->cpu);
1438 	tuple_set_d64(t, 4, th_out_id);
1439 	tuple_set_d64(t, 5, comm_out_id);
1440 	tuple_set_d64(t, 6, th_in_id);
1441 	tuple_set_d64(t, 7, comm_in_id);
1442 	tuple_set_s32(t, 8, flags);
1443 
1444 	call_object(tables->context_switch_handler, t, "context_switch");
1445 
1446 	Py_DECREF(t);
1447 
1448 	return 0;
1449 }
1450 
python_process_call_return(struct call_return * cr,u64 * parent_db_id,void * data)1451 static int python_process_call_return(struct call_return *cr, u64 *parent_db_id,
1452 				      void *data)
1453 {
1454 	struct db_export *dbe = data;
1455 
1456 	return db_export__call_return(dbe, cr, parent_db_id);
1457 }
1458 
python_process_general_event(struct perf_sample * sample,struct evsel * evsel,struct addr_location * al,struct addr_location * addr_al)1459 static void python_process_general_event(struct perf_sample *sample,
1460 					 struct evsel *evsel,
1461 					 struct addr_location *al,
1462 					 struct addr_location *addr_al)
1463 {
1464 	PyObject *handler, *t, *dict, *callchain;
1465 	static char handler_name[64];
1466 	unsigned n = 0;
1467 
1468 	snprintf(handler_name, sizeof(handler_name), "%s", "process_event");
1469 
1470 	handler = get_handler(handler_name);
1471 	if (!handler)
1472 		return;
1473 
1474 	/*
1475 	 * Use the MAX_FIELDS to make the function expandable, though
1476 	 * currently there is only one item for the tuple.
1477 	 */
1478 	t = PyTuple_New(MAX_FIELDS);
1479 	if (!t)
1480 		Py_FatalError("couldn't create Python tuple");
1481 
1482 	/* ip unwinding */
1483 	callchain = python_process_callchain(sample, evsel, al);
1484 	dict = get_perf_sample_dict(sample, evsel, al, addr_al, callchain);
1485 
1486 	PyTuple_SetItem(t, n++, dict);
1487 	if (_PyTuple_Resize(&t, n) == -1)
1488 		Py_FatalError("error resizing Python tuple");
1489 
1490 	call_object(handler, t, handler_name);
1491 
1492 	Py_DECREF(t);
1493 }
1494 
python_process_event(union perf_event * event,struct perf_sample * sample,struct evsel * evsel,struct addr_location * al,struct addr_location * addr_al)1495 static void python_process_event(union perf_event *event,
1496 				 struct perf_sample *sample,
1497 				 struct evsel *evsel,
1498 				 struct addr_location *al,
1499 				 struct addr_location *addr_al)
1500 {
1501 	struct tables *tables = &tables_global;
1502 
1503 	scripting_context__update(scripting_context, event, sample, evsel, al, addr_al);
1504 
1505 	switch (evsel->core.attr.type) {
1506 	case PERF_TYPE_TRACEPOINT:
1507 		python_process_tracepoint(sample, evsel, al, addr_al);
1508 		break;
1509 	/* Reserve for future process_hw/sw/raw APIs */
1510 	default:
1511 		if (tables->db_export_mode)
1512 			db_export__sample(&tables->dbe, event, sample, evsel, al, addr_al);
1513 		else
1514 			python_process_general_event(sample, evsel, al, addr_al);
1515 	}
1516 }
1517 
python_process_throttle(union perf_event * event,struct perf_sample * sample,struct machine * machine)1518 static void python_process_throttle(union perf_event *event,
1519 				    struct perf_sample *sample,
1520 				    struct machine *machine)
1521 {
1522 	const char *handler_name;
1523 	PyObject *handler, *t;
1524 
1525 	if (event->header.type == PERF_RECORD_THROTTLE)
1526 		handler_name = "throttle";
1527 	else
1528 		handler_name = "unthrottle";
1529 	handler = get_handler(handler_name);
1530 	if (!handler)
1531 		return;
1532 
1533 	t = tuple_new(6);
1534 	if (!t)
1535 		return;
1536 
1537 	tuple_set_u64(t, 0, event->throttle.time);
1538 	tuple_set_u64(t, 1, event->throttle.id);
1539 	tuple_set_u64(t, 2, event->throttle.stream_id);
1540 	tuple_set_s32(t, 3, sample->cpu);
1541 	tuple_set_s32(t, 4, sample->pid);
1542 	tuple_set_s32(t, 5, sample->tid);
1543 
1544 	call_object(handler, t, handler_name);
1545 
1546 	Py_DECREF(t);
1547 }
1548 
python_do_process_switch(union perf_event * event,struct perf_sample * sample,struct machine * machine)1549 static void python_do_process_switch(union perf_event *event,
1550 				     struct perf_sample *sample,
1551 				     struct machine *machine)
1552 {
1553 	const char *handler_name = "context_switch";
1554 	bool out = event->header.misc & PERF_RECORD_MISC_SWITCH_OUT;
1555 	bool out_preempt = out && (event->header.misc & PERF_RECORD_MISC_SWITCH_OUT_PREEMPT);
1556 	pid_t np_pid = -1, np_tid = -1;
1557 	PyObject *handler, *t;
1558 
1559 	handler = get_handler(handler_name);
1560 	if (!handler)
1561 		return;
1562 
1563 	if (event->header.type == PERF_RECORD_SWITCH_CPU_WIDE) {
1564 		np_pid = event->context_switch.next_prev_pid;
1565 		np_tid = event->context_switch.next_prev_tid;
1566 	}
1567 
1568 	t = tuple_new(11);
1569 	if (!t)
1570 		return;
1571 
1572 	tuple_set_u64(t, 0, sample->time);
1573 	tuple_set_s32(t, 1, sample->cpu);
1574 	tuple_set_s32(t, 2, sample->pid);
1575 	tuple_set_s32(t, 3, sample->tid);
1576 	tuple_set_s32(t, 4, np_pid);
1577 	tuple_set_s32(t, 5, np_tid);
1578 	tuple_set_s32(t, 6, machine->pid);
1579 	tuple_set_bool(t, 7, out);
1580 	tuple_set_bool(t, 8, out_preempt);
1581 	tuple_set_s32(t, 9, sample->machine_pid);
1582 	tuple_set_s32(t, 10, sample->vcpu);
1583 
1584 	call_object(handler, t, handler_name);
1585 
1586 	Py_DECREF(t);
1587 }
1588 
python_process_switch(union perf_event * event,struct perf_sample * sample,struct machine * machine)1589 static void python_process_switch(union perf_event *event,
1590 				  struct perf_sample *sample,
1591 				  struct machine *machine)
1592 {
1593 	struct tables *tables = &tables_global;
1594 
1595 	if (tables->db_export_mode)
1596 		db_export__switch(&tables->dbe, event, sample, machine);
1597 	else
1598 		python_do_process_switch(event, sample, machine);
1599 }
1600 
python_process_auxtrace_error(struct perf_session * session __maybe_unused,union perf_event * event)1601 static void python_process_auxtrace_error(struct perf_session *session __maybe_unused,
1602 					  union perf_event *event)
1603 {
1604 	struct perf_record_auxtrace_error *e = &event->auxtrace_error;
1605 	u8 cpumode = e->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
1606 	const char *handler_name = "auxtrace_error";
1607 	unsigned long long tm = e->time;
1608 	const char *msg = e->msg;
1609 	PyObject *handler, *t;
1610 
1611 	handler = get_handler(handler_name);
1612 	if (!handler)
1613 		return;
1614 
1615 	if (!e->fmt) {
1616 		tm = 0;
1617 		msg = (const char *)&e->time;
1618 	}
1619 
1620 	t = tuple_new(11);
1621 
1622 	tuple_set_u32(t, 0, e->type);
1623 	tuple_set_u32(t, 1, e->code);
1624 	tuple_set_s32(t, 2, e->cpu);
1625 	tuple_set_s32(t, 3, e->pid);
1626 	tuple_set_s32(t, 4, e->tid);
1627 	tuple_set_u64(t, 5, e->ip);
1628 	tuple_set_u64(t, 6, tm);
1629 	tuple_set_string(t, 7, msg);
1630 	tuple_set_u32(t, 8, cpumode);
1631 	tuple_set_s32(t, 9, e->machine_pid);
1632 	tuple_set_s32(t, 10, e->vcpu);
1633 
1634 	call_object(handler, t, handler_name);
1635 
1636 	Py_DECREF(t);
1637 }
1638 
get_handler_name(char * str,size_t size,struct evsel * evsel)1639 static void get_handler_name(char *str, size_t size,
1640 			     struct evsel *evsel)
1641 {
1642 	char *p = str;
1643 
1644 	scnprintf(str, size, "stat__%s", evsel__name(evsel));
1645 
1646 	while ((p = strchr(p, ':'))) {
1647 		*p = '_';
1648 		p++;
1649 	}
1650 }
1651 
1652 static void
process_stat(struct evsel * counter,struct perf_cpu cpu,int thread,u64 tstamp,struct perf_counts_values * count)1653 process_stat(struct evsel *counter, struct perf_cpu cpu, int thread, u64 tstamp,
1654 	     struct perf_counts_values *count)
1655 {
1656 	PyObject *handler, *t;
1657 	static char handler_name[256];
1658 	int n = 0;
1659 
1660 	t = PyTuple_New(MAX_FIELDS);
1661 	if (!t)
1662 		Py_FatalError("couldn't create Python tuple");
1663 
1664 	get_handler_name(handler_name, sizeof(handler_name),
1665 			 counter);
1666 
1667 	handler = get_handler(handler_name);
1668 	if (!handler) {
1669 		pr_debug("can't find python handler %s\n", handler_name);
1670 		return;
1671 	}
1672 
1673 	PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu.cpu));
1674 	PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
1675 
1676 	tuple_set_u64(t, n++, tstamp);
1677 	tuple_set_u64(t, n++, count->val);
1678 	tuple_set_u64(t, n++, count->ena);
1679 	tuple_set_u64(t, n++, count->run);
1680 
1681 	if (_PyTuple_Resize(&t, n) == -1)
1682 		Py_FatalError("error resizing Python tuple");
1683 
1684 	call_object(handler, t, handler_name);
1685 
1686 	Py_DECREF(t);
1687 }
1688 
python_process_stat(struct perf_stat_config * config,struct evsel * counter,u64 tstamp)1689 static void python_process_stat(struct perf_stat_config *config,
1690 				struct evsel *counter, u64 tstamp)
1691 {
1692 	struct perf_thread_map *threads = counter->core.threads;
1693 	struct perf_cpu_map *cpus = counter->core.cpus;
1694 
1695 	for (int thread = 0; thread < perf_thread_map__nr(threads); thread++) {
1696 		int idx;
1697 		struct perf_cpu cpu;
1698 
1699 		perf_cpu_map__for_each_cpu(cpu, idx, cpus) {
1700 			process_stat(counter, cpu,
1701 				     perf_thread_map__pid(threads, thread), tstamp,
1702 				     perf_counts(counter->counts, idx, thread));
1703 		}
1704 	}
1705 }
1706 
python_process_stat_interval(u64 tstamp)1707 static void python_process_stat_interval(u64 tstamp)
1708 {
1709 	PyObject *handler, *t;
1710 	static const char handler_name[] = "stat__interval";
1711 	int n = 0;
1712 
1713 	t = PyTuple_New(MAX_FIELDS);
1714 	if (!t)
1715 		Py_FatalError("couldn't create Python tuple");
1716 
1717 	handler = get_handler(handler_name);
1718 	if (!handler) {
1719 		pr_debug("can't find python handler %s\n", handler_name);
1720 		return;
1721 	}
1722 
1723 	tuple_set_u64(t, n++, tstamp);
1724 
1725 	if (_PyTuple_Resize(&t, n) == -1)
1726 		Py_FatalError("error resizing Python tuple");
1727 
1728 	call_object(handler, t, handler_name);
1729 
1730 	Py_DECREF(t);
1731 }
1732 
perf_script_context_init(void)1733 static int perf_script_context_init(void)
1734 {
1735 	PyObject *perf_script_context;
1736 	PyObject *perf_trace_context;
1737 	PyObject *dict;
1738 	int ret;
1739 
1740 	perf_trace_context = PyImport_AddModule("perf_trace_context");
1741 	if (!perf_trace_context)
1742 		return -1;
1743 	dict = PyModule_GetDict(perf_trace_context);
1744 	if (!dict)
1745 		return -1;
1746 
1747 	perf_script_context = _PyCapsule_New(scripting_context, NULL, NULL);
1748 	if (!perf_script_context)
1749 		return -1;
1750 
1751 	ret = PyDict_SetItemString(dict, "perf_script_context", perf_script_context);
1752 	if (!ret)
1753 		ret = PyDict_SetItemString(main_dict, "perf_script_context", perf_script_context);
1754 	Py_DECREF(perf_script_context);
1755 	return ret;
1756 }
1757 
run_start_sub(void)1758 static int run_start_sub(void)
1759 {
1760 	main_module = PyImport_AddModule("__main__");
1761 	if (main_module == NULL)
1762 		return -1;
1763 	Py_INCREF(main_module);
1764 
1765 	main_dict = PyModule_GetDict(main_module);
1766 	if (main_dict == NULL)
1767 		goto error;
1768 	Py_INCREF(main_dict);
1769 
1770 	if (perf_script_context_init())
1771 		goto error;
1772 
1773 	try_call_object("trace_begin", NULL);
1774 
1775 	return 0;
1776 
1777 error:
1778 	Py_XDECREF(main_dict);
1779 	Py_XDECREF(main_module);
1780 	return -1;
1781 }
1782 
1783 #define SET_TABLE_HANDLER_(name, handler_name, table_name) do {		\
1784 	tables->handler_name = get_handler(#table_name);		\
1785 	if (tables->handler_name)					\
1786 		tables->dbe.export_ ## name = python_export_ ## name;	\
1787 } while (0)
1788 
1789 #define SET_TABLE_HANDLER(name) \
1790 	SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)
1791 
set_table_handlers(struct tables * tables)1792 static void set_table_handlers(struct tables *tables)
1793 {
1794 	const char *perf_db_export_mode = "perf_db_export_mode";
1795 	const char *perf_db_export_calls = "perf_db_export_calls";
1796 	const char *perf_db_export_callchains = "perf_db_export_callchains";
1797 	PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
1798 	bool export_calls = false;
1799 	bool export_callchains = false;
1800 	int ret;
1801 
1802 	memset(tables, 0, sizeof(struct tables));
1803 	if (db_export__init(&tables->dbe))
1804 		Py_FatalError("failed to initialize export");
1805 
1806 	db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
1807 	if (!db_export_mode)
1808 		return;
1809 
1810 	ret = PyObject_IsTrue(db_export_mode);
1811 	if (ret == -1)
1812 		handler_call_die(perf_db_export_mode);
1813 	if (!ret)
1814 		return;
1815 
1816 	/* handle export calls */
1817 	tables->dbe.crp = NULL;
1818 	db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
1819 	if (db_export_calls) {
1820 		ret = PyObject_IsTrue(db_export_calls);
1821 		if (ret == -1)
1822 			handler_call_die(perf_db_export_calls);
1823 		export_calls = !!ret;
1824 	}
1825 
1826 	if (export_calls) {
1827 		tables->dbe.crp =
1828 			call_return_processor__new(python_process_call_return,
1829 						   &tables->dbe);
1830 		if (!tables->dbe.crp)
1831 			Py_FatalError("failed to create calls processor");
1832 	}
1833 
1834 	/* handle export callchains */
1835 	tables->dbe.cpr = NULL;
1836 	db_export_callchains = PyDict_GetItemString(main_dict,
1837 						    perf_db_export_callchains);
1838 	if (db_export_callchains) {
1839 		ret = PyObject_IsTrue(db_export_callchains);
1840 		if (ret == -1)
1841 			handler_call_die(perf_db_export_callchains);
1842 		export_callchains = !!ret;
1843 	}
1844 
1845 	if (export_callchains) {
1846 		/*
1847 		 * Attempt to use the call path root from the call return
1848 		 * processor, if the call return processor is in use. Otherwise,
1849 		 * we allocate a new call path root. This prevents exporting
1850 		 * duplicate call path ids when both are in use simultaneously.
1851 		 */
1852 		if (tables->dbe.crp)
1853 			tables->dbe.cpr = tables->dbe.crp->cpr;
1854 		else
1855 			tables->dbe.cpr = call_path_root__new();
1856 
1857 		if (!tables->dbe.cpr)
1858 			Py_FatalError("failed to create call path root");
1859 	}
1860 
1861 	tables->db_export_mode = true;
1862 	/*
1863 	 * Reserve per symbol space for symbol->db_id via symbol__priv()
1864 	 */
1865 	symbol_conf.priv_size = sizeof(u64);
1866 
1867 	SET_TABLE_HANDLER(evsel);
1868 	SET_TABLE_HANDLER(machine);
1869 	SET_TABLE_HANDLER(thread);
1870 	SET_TABLE_HANDLER(comm);
1871 	SET_TABLE_HANDLER(comm_thread);
1872 	SET_TABLE_HANDLER(dso);
1873 	SET_TABLE_HANDLER(symbol);
1874 	SET_TABLE_HANDLER(branch_type);
1875 	SET_TABLE_HANDLER(sample);
1876 	SET_TABLE_HANDLER(call_path);
1877 	SET_TABLE_HANDLER(call_return);
1878 	SET_TABLE_HANDLER(context_switch);
1879 
1880 	/*
1881 	 * Synthesized events are samples but with architecture-specific data
1882 	 * stored in sample->raw_data. They are exported via
1883 	 * python_export_sample() and consequently do not need a separate export
1884 	 * callback.
1885 	 */
1886 	tables->synth_handler = get_handler("synth_data");
1887 }
1888 
_free_command_line(wchar_t ** command_line,int num)1889 static void _free_command_line(wchar_t **command_line, int num)
1890 {
1891 	int i;
1892 	for (i = 0; i < num; i++)
1893 		PyMem_RawFree(command_line[i]);
1894 	free(command_line);
1895 }
1896 
1897 
1898 /*
1899  * Start trace script
1900  */
python_start_script(const char * script,int argc,const char ** argv,struct perf_session * session)1901 static int python_start_script(const char *script, int argc, const char **argv,
1902 			       struct perf_session *session)
1903 {
1904 	struct tables *tables = &tables_global;
1905 	wchar_t **command_line;
1906 	char buf[PATH_MAX];
1907 	int i, err = 0;
1908 	FILE *fp;
1909 
1910 	scripting_context->session = session;
1911 	command_line = malloc((argc + 1) * sizeof(wchar_t *));
1912 	if (!command_line)
1913 		return -1;
1914 
1915 	command_line[0] = Py_DecodeLocale(script, NULL);
1916 	for (i = 1; i < argc + 1; i++)
1917 		command_line[i] = Py_DecodeLocale(argv[i - 1], NULL);
1918 	PyImport_AppendInittab("perf_trace_context", PyInit_perf_trace_context);
1919 	Py_Initialize();
1920 
1921 	PySys_SetArgv(argc + 1, command_line);
1922 
1923 	fp = fopen(script, "r");
1924 	if (!fp) {
1925 		sprintf(buf, "Can't open python script \"%s\"", script);
1926 		perror(buf);
1927 		err = -1;
1928 		goto error;
1929 	}
1930 
1931 	err = PyRun_SimpleFile(fp, script);
1932 	if (err) {
1933 		fprintf(stderr, "Error running python script %s\n", script);
1934 		goto error;
1935 	}
1936 
1937 	err = run_start_sub();
1938 	if (err) {
1939 		fprintf(stderr, "Error starting python script %s\n", script);
1940 		goto error;
1941 	}
1942 
1943 	set_table_handlers(tables);
1944 
1945 	if (tables->db_export_mode) {
1946 		err = db_export__branch_types(&tables->dbe);
1947 		if (err)
1948 			goto error;
1949 	}
1950 
1951 	_free_command_line(command_line, argc + 1);
1952 
1953 	return err;
1954 error:
1955 	Py_Finalize();
1956 	_free_command_line(command_line, argc + 1);
1957 
1958 	return err;
1959 }
1960 
python_flush_script(void)1961 static int python_flush_script(void)
1962 {
1963 	return 0;
1964 }
1965 
1966 /*
1967  * Stop trace script
1968  */
python_stop_script(void)1969 static int python_stop_script(void)
1970 {
1971 	struct tables *tables = &tables_global;
1972 
1973 	try_call_object("trace_end", NULL);
1974 
1975 	db_export__exit(&tables->dbe);
1976 
1977 	Py_XDECREF(main_dict);
1978 	Py_XDECREF(main_module);
1979 	Py_Finalize();
1980 
1981 	return 0;
1982 }
1983 
1984 #ifdef HAVE_LIBTRACEEVENT
python_generate_script(struct tep_handle * pevent,const char * outfile)1985 static int python_generate_script(struct tep_handle *pevent, const char *outfile)
1986 {
1987 	int i, not_first, count, nr_events;
1988 	struct tep_event **all_events;
1989 	struct tep_event *event = NULL;
1990 	struct tep_format_field *f;
1991 	char fname[PATH_MAX];
1992 	FILE *ofp;
1993 
1994 	sprintf(fname, "%s.py", outfile);
1995 	ofp = fopen(fname, "w");
1996 	if (ofp == NULL) {
1997 		fprintf(stderr, "couldn't open %s\n", fname);
1998 		return -1;
1999 	}
2000 	fprintf(ofp, "# perf script event handlers, "
2001 		"generated by perf script -g python\n");
2002 
2003 	fprintf(ofp, "# Licensed under the terms of the GNU GPL"
2004 		" License version 2\n\n");
2005 
2006 	fprintf(ofp, "# The common_* event handler fields are the most useful "
2007 		"fields common to\n");
2008 
2009 	fprintf(ofp, "# all events.  They don't necessarily correspond to "
2010 		"the 'common_*' fields\n");
2011 
2012 	fprintf(ofp, "# in the format files.  Those fields not available as "
2013 		"handler params can\n");
2014 
2015 	fprintf(ofp, "# be retrieved using Python functions of the form "
2016 		"common_*(context).\n");
2017 
2018 	fprintf(ofp, "# See the perf-script-python Documentation for the list "
2019 		"of available functions.\n\n");
2020 
2021 	fprintf(ofp, "from __future__ import print_function\n\n");
2022 	fprintf(ofp, "import os\n");
2023 	fprintf(ofp, "import sys\n\n");
2024 
2025 	fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
2026 	fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
2027 	fprintf(ofp, "\nfrom perf_trace_context import *\n");
2028 	fprintf(ofp, "from Core import *\n\n\n");
2029 
2030 	fprintf(ofp, "def trace_begin():\n");
2031 	fprintf(ofp, "\tprint(\"in trace_begin\")\n\n");
2032 
2033 	fprintf(ofp, "def trace_end():\n");
2034 	fprintf(ofp, "\tprint(\"in trace_end\")\n\n");
2035 
2036 	nr_events = tep_get_events_count(pevent);
2037 	all_events = tep_list_events(pevent, TEP_EVENT_SORT_ID);
2038 
2039 	for (i = 0; all_events && i < nr_events; i++) {
2040 		event = all_events[i];
2041 		fprintf(ofp, "def %s__%s(", event->system, event->name);
2042 		fprintf(ofp, "event_name, ");
2043 		fprintf(ofp, "context, ");
2044 		fprintf(ofp, "common_cpu,\n");
2045 		fprintf(ofp, "\tcommon_secs, ");
2046 		fprintf(ofp, "common_nsecs, ");
2047 		fprintf(ofp, "common_pid, ");
2048 		fprintf(ofp, "common_comm,\n\t");
2049 		fprintf(ofp, "common_callchain, ");
2050 
2051 		not_first = 0;
2052 		count = 0;
2053 
2054 		for (f = event->format.fields; f; f = f->next) {
2055 			if (not_first++)
2056 				fprintf(ofp, ", ");
2057 			if (++count % 5 == 0)
2058 				fprintf(ofp, "\n\t");
2059 
2060 			fprintf(ofp, "%s", f->name);
2061 		}
2062 		if (not_first++)
2063 			fprintf(ofp, ", ");
2064 		if (++count % 5 == 0)
2065 			fprintf(ofp, "\n\t\t");
2066 		fprintf(ofp, "perf_sample_dict");
2067 
2068 		fprintf(ofp, "):\n");
2069 
2070 		fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
2071 			"common_secs, common_nsecs,\n\t\t\t"
2072 			"common_pid, common_comm)\n\n");
2073 
2074 		fprintf(ofp, "\t\tprint(\"");
2075 
2076 		not_first = 0;
2077 		count = 0;
2078 
2079 		for (f = event->format.fields; f; f = f->next) {
2080 			if (not_first++)
2081 				fprintf(ofp, ", ");
2082 			if (count && count % 3 == 0) {
2083 				fprintf(ofp, "\" \\\n\t\t\"");
2084 			}
2085 			count++;
2086 
2087 			fprintf(ofp, "%s=", f->name);
2088 			if (f->flags & TEP_FIELD_IS_STRING ||
2089 			    f->flags & TEP_FIELD_IS_FLAG ||
2090 			    f->flags & TEP_FIELD_IS_ARRAY ||
2091 			    f->flags & TEP_FIELD_IS_SYMBOLIC)
2092 				fprintf(ofp, "%%s");
2093 			else if (f->flags & TEP_FIELD_IS_SIGNED)
2094 				fprintf(ofp, "%%d");
2095 			else
2096 				fprintf(ofp, "%%u");
2097 		}
2098 
2099 		fprintf(ofp, "\" %% \\\n\t\t(");
2100 
2101 		not_first = 0;
2102 		count = 0;
2103 
2104 		for (f = event->format.fields; f; f = f->next) {
2105 			if (not_first++)
2106 				fprintf(ofp, ", ");
2107 
2108 			if (++count % 5 == 0)
2109 				fprintf(ofp, "\n\t\t");
2110 
2111 			if (f->flags & TEP_FIELD_IS_FLAG) {
2112 				if ((count - 1) % 5 != 0) {
2113 					fprintf(ofp, "\n\t\t");
2114 					count = 4;
2115 				}
2116 				fprintf(ofp, "flag_str(\"");
2117 				fprintf(ofp, "%s__%s\", ", event->system,
2118 					event->name);
2119 				fprintf(ofp, "\"%s\", %s)", f->name,
2120 					f->name);
2121 			} else if (f->flags & TEP_FIELD_IS_SYMBOLIC) {
2122 				if ((count - 1) % 5 != 0) {
2123 					fprintf(ofp, "\n\t\t");
2124 					count = 4;
2125 				}
2126 				fprintf(ofp, "symbol_str(\"");
2127 				fprintf(ofp, "%s__%s\", ", event->system,
2128 					event->name);
2129 				fprintf(ofp, "\"%s\", %s)", f->name,
2130 					f->name);
2131 			} else
2132 				fprintf(ofp, "%s", f->name);
2133 		}
2134 
2135 		fprintf(ofp, "))\n\n");
2136 
2137 		fprintf(ofp, "\t\tprint('Sample: {'+"
2138 			"get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
2139 
2140 		fprintf(ofp, "\t\tfor node in common_callchain:");
2141 		fprintf(ofp, "\n\t\t\tif 'sym' in node:");
2142 		fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x] %%s%%s%%s%%s\" %% (");
2143 		fprintf(ofp, "\n\t\t\t\t\tnode['ip'], node['sym']['name'],");
2144 		fprintf(ofp, "\n\t\t\t\t\t\"+0x{:x}\".format(node['sym_off']) if 'sym_off' in node else \"\",");
2145 		fprintf(ofp, "\n\t\t\t\t\t\" ({})\".format(node['dso'])  if 'dso' in node else \"\",");
2146 		fprintf(ofp, "\n\t\t\t\t\t\" \" + node['sym_srcline'] if 'sym_srcline' in node else \"\"))");
2147 		fprintf(ofp, "\n\t\t\telse:");
2148 		fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x]\" %% (node['ip']))\n\n");
2149 		fprintf(ofp, "\t\tprint()\n\n");
2150 
2151 	}
2152 
2153 	fprintf(ofp, "def trace_unhandled(event_name, context, "
2154 		"event_fields_dict, perf_sample_dict):\n");
2155 
2156 	fprintf(ofp, "\t\tprint(get_dict_as_string(event_fields_dict))\n");
2157 	fprintf(ofp, "\t\tprint('Sample: {'+"
2158 		"get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
2159 
2160 	fprintf(ofp, "def print_header("
2161 		"event_name, cpu, secs, nsecs, pid, comm):\n"
2162 		"\tprint(\"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
2163 		"(event_name, cpu, secs, nsecs, pid, comm), end=\"\")\n\n");
2164 
2165 	fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
2166 		"\treturn delimiter.join"
2167 		"(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
2168 
2169 	fclose(ofp);
2170 
2171 	fprintf(stderr, "generated Python script: %s\n", fname);
2172 
2173 	return 0;
2174 }
2175 #else
python_generate_script(struct tep_handle * pevent __maybe_unused,const char * outfile __maybe_unused)2176 static int python_generate_script(struct tep_handle *pevent __maybe_unused,
2177 				  const char *outfile __maybe_unused)
2178 {
2179 	fprintf(stderr, "Generating Python perf-script is not supported."
2180 		"  Install libtraceevent and rebuild perf to enable it.\n"
2181 		"For example:\n  # apt install libtraceevent-dev (ubuntu)"
2182 		"\n  # yum install libtraceevent-devel (Fedora)"
2183 		"\n  etc.\n");
2184 	return -1;
2185 }
2186 #endif
2187 
2188 struct scripting_ops python_scripting_ops = {
2189 	.name			= "Python",
2190 	.dirname		= "python",
2191 	.start_script		= python_start_script,
2192 	.flush_script		= python_flush_script,
2193 	.stop_script		= python_stop_script,
2194 	.process_event		= python_process_event,
2195 	.process_switch		= python_process_switch,
2196 	.process_auxtrace_error	= python_process_auxtrace_error,
2197 	.process_stat		= python_process_stat,
2198 	.process_stat_interval	= python_process_stat_interval,
2199 	.process_throttle	= python_process_throttle,
2200 	.generate_script	= python_generate_script,
2201 };
2202