trace-event-python.c 48.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * trace-event-python.  Feed trace events to an embedded Python interpreter.
 *
 * Copyright (C) 2010 Tom Zanussi <tzanussi@gmail.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#include <Python.h>

24
#include <inttypes.h>
25 26 27
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
28
#include <stdbool.h>
29
#include <errno.h>
30
#include <linux/bitmap.h>
31
#include <linux/compiler.h>
32
#include <linux/time64.h>
33

34
#include "../build-id.h"
35
#include "../counts.h"
36
#include "../debug.h"
37
#include "../dso.h"
38
#include "../callchain.h"
39
#include "../evsel.h"
40 41
#include "../event.h"
#include "../thread.h"
42 43 44
#include "../comm.h"
#include "../machine.h"
#include "../db-export.h"
45
#include "../thread-stack.h"
46
#include "../trace-event.h"
47
#include "../call-path.h"
48
#include "map.h"
49
#include "symbol.h"
50
#include "thread_map.h"
51
#include "print_binary.h"
52
#include "stat.h"
53
#include "mem-events.h"
54

55 56 57 58 59 60 61 62 63 64 65 66 67 68
#if PY_MAJOR_VERSION < 3
#define _PyUnicode_FromString(arg) \
  PyString_FromString(arg)
#define _PyUnicode_FromStringAndSize(arg1, arg2) \
  PyString_FromStringAndSize((arg1), (arg2))
#define _PyBytes_FromStringAndSize(arg1, arg2) \
  PyString_FromStringAndSize((arg1), (arg2))
#define _PyLong_FromLong(arg) \
  PyInt_FromLong(arg)
#define _PyLong_AsLong(arg) \
  PyInt_AsLong(arg)
#define _PyCapsule_New(arg1, arg2, arg3) \
  PyCObject_FromVoidPtr((arg1), (arg2))

69
PyMODINIT_FUNC initperf_trace_context(void);
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
#else
#define _PyUnicode_FromString(arg) \
  PyUnicode_FromString(arg)
#define _PyUnicode_FromStringAndSize(arg1, arg2) \
  PyUnicode_FromStringAndSize((arg1), (arg2))
#define _PyBytes_FromStringAndSize(arg1, arg2) \
  PyBytes_FromStringAndSize((arg1), (arg2))
#define _PyLong_FromLong(arg) \
  PyLong_FromLong(arg)
#define _PyLong_AsLong(arg) \
  PyLong_AsLong(arg)
#define _PyCapsule_New(arg1, arg2, arg3) \
  PyCapsule_New((arg1), (arg2), (arg3))

PyMODINIT_FUNC PyInit_perf_trace_context(void);
#endif
86

87
#define TRACE_EVENT_TYPE_MAX				\
88 89
	((1 << (sizeof(unsigned short) * 8)) - 1)

90
static DECLARE_BITMAP(events_defined, TRACE_EVENT_TYPE_MAX);
91 92 93 94 95 96 97 98 99 100 101

#define MAX_FIELDS	64
#define N_COMMON_FIELDS	7

extern struct scripting_context *scripting_context;

static char *cur_field_name;
static int zero_flag_atom;

static PyObject *main_module, *main_dict;

102 103 104 105 106 107 108 109 110
struct tables {
	struct db_export	dbe;
	PyObject		*evsel_handler;
	PyObject		*machine_handler;
	PyObject		*thread_handler;
	PyObject		*comm_handler;
	PyObject		*comm_thread_handler;
	PyObject		*dso_handler;
	PyObject		*symbol_handler;
111
	PyObject		*branch_type_handler;
112
	PyObject		*sample_handler;
113 114
	PyObject		*call_path_handler;
	PyObject		*call_return_handler;
115
	PyObject		*synth_handler;
116
	PyObject		*context_switch_handler;
117 118 119 120 121
	bool			db_export_mode;
};

static struct tables tables_global;

122
static void handler_call_die(const char *handler_name) __noreturn;
123 124 125 126
static void handler_call_die(const char *handler_name)
{
	PyErr_Print();
	Py_FatalError("problem in Python trace event handler");
127 128 129
	// Py_FatalError does not return
	// but we have to make the compiler happy
	abort();
130 131
}

132 133
/*
 * Insert val into into the dictionary and decrement the reference counter.
134
 * This is necessary for dictionaries since PyDict_SetItemString() does not
135 136 137 138 139 140 141 142
 * steal a reference, as opposed to PyTuple_SetItem().
 */
static void pydict_set_item_string_decref(PyObject *dict, const char *key, PyObject *val)
{
	PyDict_SetItemString(dict, key, val);
	Py_DECREF(val);
}

143 144 145 146 147 148 149 150 151 152
static PyObject *get_handler(const char *handler_name)
{
	PyObject *handler;

	handler = PyDict_GetItemString(main_dict, handler_name);
	if (handler && !PyCallable_Check(handler))
		return NULL;
	return handler;
}

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
static int get_argument_count(PyObject *handler)
{
	int arg_count = 0;

	/*
	 * The attribute for the code object is func_code in Python 2,
	 * whereas it is __code__ in Python 3.0+.
	 */
	PyObject *code_obj = PyObject_GetAttrString(handler,
		"func_code");
	if (PyErr_Occurred()) {
		PyErr_Clear();
		code_obj = PyObject_GetAttrString(handler,
			"__code__");
	}
	PyErr_Clear();
	if (code_obj) {
		PyObject *arg_count_obj = PyObject_GetAttrString(code_obj,
			"co_argcount");
		if (arg_count_obj) {
173
			arg_count = (int) _PyLong_AsLong(arg_count_obj);
174 175 176 177 178 179 180
			Py_DECREF(arg_count_obj);
		}
		Py_DECREF(code_obj);
	}
	return arg_count;
}

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
static void call_object(PyObject *handler, PyObject *args, const char *die_msg)
{
	PyObject *retval;

	retval = PyObject_CallObject(handler, args);
	if (retval == NULL)
		handler_call_die(die_msg);
	Py_DECREF(retval);
}

static void try_call_object(const char *handler_name, PyObject *args)
{
	PyObject *handler;

	handler = get_handler(handler_name);
	if (handler)
		call_object(handler, args, handler_name);
}

200
static void define_value(enum tep_print_arg_type field_type,
201 202 203 204 205 206
			 const char *ev_name,
			 const char *field_name,
			 const char *field_value,
			 const char *field_str)
{
	const char *handler_name = "define_flag_value";
207
	PyObject *t;
208 209 210
	unsigned long long value;
	unsigned n = 0;

211
	if (field_type == TEP_PRINT_SYMBOL)
212 213
		handler_name = "define_symbolic_value";

214
	t = PyTuple_New(4);
215 216 217 218 219
	if (!t)
		Py_FatalError("couldn't create Python tuple");

	value = eval_flag(field_value);

220 221 222 223
	PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
	PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
	PyTuple_SetItem(t, n++, _PyLong_FromLong(value));
	PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_str));
224

225
	try_call_object(handler_name, t);
226 227 228 229

	Py_DECREF(t);
}

230
static void define_values(enum tep_print_arg_type field_type,
231
			  struct tep_print_flag_sym *field,
232 233 234 235 236 237 238 239 240 241
			  const char *ev_name,
			  const char *field_name)
{
	define_value(field_type, ev_name, field_name, field->value,
		     field->str);

	if (field->next)
		define_values(field_type, field->next, ev_name, field_name);
}

242
static void define_field(enum tep_print_arg_type field_type,
243 244 245 246 247
			 const char *ev_name,
			 const char *field_name,
			 const char *delim)
{
	const char *handler_name = "define_flag_field";
248
	PyObject *t;
249 250
	unsigned n = 0;

251
	if (field_type == TEP_PRINT_SYMBOL)
252 253
		handler_name = "define_symbolic_field";

254
	if (field_type == TEP_PRINT_FLAGS)
255 256 257
		t = PyTuple_New(3);
	else
		t = PyTuple_New(2);
258 259 260
	if (!t)
		Py_FatalError("couldn't create Python tuple");

261 262
	PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
	PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
263
	if (field_type == TEP_PRINT_FLAGS)
264
		PyTuple_SetItem(t, n++, _PyUnicode_FromString(delim));
265

266
	try_call_object(handler_name, t);
267 268 269 270

	Py_DECREF(t);
}

271
static void define_event_symbols(struct tep_event *event,
272
				 const char *ev_name,
273
				 struct tep_print_arg *args)
274
{
275 276 277
	if (args == NULL)
		return;

278
	switch (args->type) {
279
	case TEP_PRINT_NULL:
280
		break;
281 282
	case TEP_PRINT_ATOM:
		define_value(TEP_PRINT_FLAGS, ev_name, cur_field_name, "0",
283 284 285
			     args->atom.atom);
		zero_flag_atom = 0;
		break;
286
	case TEP_PRINT_FIELD:
287
		free(cur_field_name);
288 289
		cur_field_name = strdup(args->field.name);
		break;
290
	case TEP_PRINT_FLAGS:
291
		define_event_symbols(event, ev_name, args->flags.field);
292
		define_field(TEP_PRINT_FLAGS, ev_name, cur_field_name,
293
			     args->flags.delim);
294
		define_values(TEP_PRINT_FLAGS, args->flags.flags, ev_name,
295 296
			      cur_field_name);
		break;
297
	case TEP_PRINT_SYMBOL:
298
		define_event_symbols(event, ev_name, args->symbol.field);
299 300
		define_field(TEP_PRINT_SYMBOL, ev_name, cur_field_name, NULL);
		define_values(TEP_PRINT_SYMBOL, args->symbol.symbols, ev_name,
301 302
			      cur_field_name);
		break;
303 304
	case TEP_PRINT_HEX:
	case TEP_PRINT_HEX_STR:
305 306 307
		define_event_symbols(event, ev_name, args->hex.field);
		define_event_symbols(event, ev_name, args->hex.size);
		break;
308
	case TEP_PRINT_INT_ARRAY:
309 310 311 312
		define_event_symbols(event, ev_name, args->int_array.field);
		define_event_symbols(event, ev_name, args->int_array.count);
		define_event_symbols(event, ev_name, args->int_array.el_size);
		break;
313
	case TEP_PRINT_STRING:
314
		break;
315
	case TEP_PRINT_TYPE:
316 317
		define_event_symbols(event, ev_name, args->typecast.item);
		break;
318
	case TEP_PRINT_OP:
319 320 321 322 323 324
		if (strcmp(args->op.op, ":") == 0)
			zero_flag_atom = 1;
		define_event_symbols(event, ev_name, args->op.left);
		define_event_symbols(event, ev_name, args->op.right);
		break;
	default:
325
		/* gcc warns for these? */
326 327 328 329 330
	case TEP_PRINT_BSTRING:
	case TEP_PRINT_DYNAMIC_ARRAY:
	case TEP_PRINT_DYNAMIC_ARRAY_LEN:
	case TEP_PRINT_FUNC:
	case TEP_PRINT_BITMASK:
331 332 333 334 335 336 337 338
		/* we should warn... */
		return;
	}

	if (args->next)
		define_event_symbols(event, ev_name, args->next);
}

339
static PyObject *get_field_numeric_entry(struct tep_event *event,
340
		struct tep_format_field *field, void *data)
341
{
342
	bool is_array = field->flags & TEP_FIELD_IS_ARRAY;
343
	PyObject *obj = NULL, *list = NULL;
344
	unsigned long long val;
345
	unsigned int item_size, n_items, i;
346

347 348 349 350
	if (is_array) {
		list = PyList_New(field->arraylen);
		item_size = field->size / field->arraylen;
		n_items = field->arraylen;
351
	} else {
352 353
		item_size = field->size;
		n_items = 1;
354
	}
355 356 357 358 359

	for (i = 0; i < n_items; i++) {

		val = read_size(event, data + field->offset + i * item_size,
				item_size);
360
		if (field->flags & TEP_FIELD_IS_SIGNED) {
361 362
			if ((long long)val >= LONG_MIN &&
					(long long)val <= LONG_MAX)
363
				obj = _PyLong_FromLong(val);
364 365 366 367
			else
				obj = PyLong_FromLongLong(val);
		} else {
			if (val <= LONG_MAX)
368
				obj = _PyLong_FromLong(val);
369 370 371 372 373 374 375 376
			else
				obj = PyLong_FromUnsignedLongLong(val);
		}
		if (is_array)
			PyList_SET_ITEM(list, i, obj);
	}
	if (is_array)
		obj = list;
377 378 379
	return obj;
}

380 381 382 383 384 385 386 387 388 389 390 391 392
static const char *get_dsoname(struct map *map)
{
	const char *dsoname = "[unknown]";

	if (map && map->dso) {
		if (symbol_conf.show_kernel_path && map->dso->long_name)
			dsoname = map->dso->long_name;
		else
			dsoname = map->dso->name;
	}

	return dsoname;
}
393 394

static PyObject *python_process_callchain(struct perf_sample *sample,
395
					 struct evsel *evsel,
396 397 398 399 400 401 402 403 404 405 406
					 struct addr_location *al)
{
	PyObject *pylist;

	pylist = PyList_New(0);
	if (!pylist)
		Py_FatalError("couldn't create Python list");

	if (!symbol_conf.use_callchain || !sample->callchain)
		goto exit;

407
	if (thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
408
				      sample, NULL, NULL,
409
				      scripting_max_stack) != 0) {
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
		pr_err("Failed to resolve callchain. Skipping\n");
		goto exit;
	}
	callchain_cursor_commit(&callchain_cursor);


	while (1) {
		PyObject *pyelem;
		struct callchain_cursor_node *node;
		node = callchain_cursor_current(&callchain_cursor);
		if (!node)
			break;

		pyelem = PyDict_New();
		if (!pyelem)
			Py_FatalError("couldn't create Python dictionary");


		pydict_set_item_string_decref(pyelem, "ip",
				PyLong_FromUnsignedLongLong(node->ip));

431
		if (node->ms.sym) {
432 433 434 435
			PyObject *pysym  = PyDict_New();
			if (!pysym)
				Py_FatalError("couldn't create Python dictionary");
			pydict_set_item_string_decref(pysym, "start",
436
					PyLong_FromUnsignedLongLong(node->ms.sym->start));
437
			pydict_set_item_string_decref(pysym, "end",
438
					PyLong_FromUnsignedLongLong(node->ms.sym->end));
439
			pydict_set_item_string_decref(pysym, "binding",
440
					_PyLong_FromLong(node->ms.sym->binding));
441
			pydict_set_item_string_decref(pysym, "name",
442 443
					_PyUnicode_FromStringAndSize(node->ms.sym->name,
							node->ms.sym->namelen));
444 445 446
			pydict_set_item_string_decref(pyelem, "sym", pysym);
		}

447 448
		if (node->ms.map) {
			const char *dsoname = get_dsoname(node->ms.map);
449

450
			pydict_set_item_string_decref(pyelem, "dso",
451
					_PyUnicode_FromString(dsoname));
452 453 454 455 456 457 458 459 460 461 462
		}

		callchain_cursor_advance(&callchain_cursor);
		PyList_Append(pylist, pyelem);
		Py_DECREF(pyelem);
	}

exit:
	return pylist;
}

463 464 465 466
static PyObject *python_process_brstack(struct perf_sample *sample,
					struct thread *thread)
{
	struct branch_stack *br = sample->branch_stack;
467
	struct branch_entry *entries = perf_sample__branch_entries(sample);
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
	PyObject *pylist;
	u64 i;

	pylist = PyList_New(0);
	if (!pylist)
		Py_FatalError("couldn't create Python list");

	if (!(br && br->nr))
		goto exit;

	for (i = 0; i < br->nr; i++) {
		PyObject *pyelem;
		struct addr_location al;
		const char *dsoname;

		pyelem = PyDict_New();
		if (!pyelem)
			Py_FatalError("couldn't create Python dictionary");

		pydict_set_item_string_decref(pyelem, "from",
488
		    PyLong_FromUnsignedLongLong(entries[i].from));
489
		pydict_set_item_string_decref(pyelem, "to",
490
		    PyLong_FromUnsignedLongLong(entries[i].to));
491
		pydict_set_item_string_decref(pyelem, "mispred",
492
		    PyBool_FromLong(entries[i].flags.mispred));
493
		pydict_set_item_string_decref(pyelem, "predicted",
494
		    PyBool_FromLong(entries[i].flags.predicted));
495
		pydict_set_item_string_decref(pyelem, "in_tx",
496
		    PyBool_FromLong(entries[i].flags.in_tx));
497
		pydict_set_item_string_decref(pyelem, "abort",
498
		    PyBool_FromLong(entries[i].flags.abort));
499
		pydict_set_item_string_decref(pyelem, "cycles",
500
		    PyLong_FromUnsignedLongLong(entries[i].flags.cycles));
501

502
		thread__find_map_fb(thread, sample->cpumode,
503
				    entries[i].from, &al);
504 505 506 507
		dsoname = get_dsoname(al.map);
		pydict_set_item_string_decref(pyelem, "from_dsoname",
					      _PyUnicode_FromString(dsoname));

508
		thread__find_map_fb(thread, sample->cpumode,
509
				    entries[i].to, &al);
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
		dsoname = get_dsoname(al.map);
		pydict_set_item_string_decref(pyelem, "to_dsoname",
					      _PyUnicode_FromString(dsoname));

		PyList_Append(pylist, pyelem);
		Py_DECREF(pyelem);
	}

exit:
	return pylist;
}

static unsigned long get_offset(struct symbol *sym, struct addr_location *al)
{
	unsigned long offset;

	if (al->addr < sym->end)
		offset = al->addr - sym->start;
	else
		offset = al->addr - al->map->start - sym->start;

	return offset;
}

static int get_symoff(struct symbol *sym, struct addr_location *al,
		      bool print_off, char *bf, int size)
{
	unsigned long offset;

	if (!sym || !sym->name[0])
		return scnprintf(bf, size, "%s", "[unknown]");

	if (!print_off)
		return scnprintf(bf, size, "%s", sym->name);

	offset = get_offset(sym, al);

	return scnprintf(bf, size, "%s+0x%x", sym->name, offset);
}

static int get_br_mspred(struct branch_flags *flags, char *bf, int size)
{
	if (!flags->mispred  && !flags->predicted)
		return scnprintf(bf, size, "%s", "-");

	if (flags->mispred)
		return scnprintf(bf, size, "%s", "M");

	return scnprintf(bf, size, "%s", "P");
}

static PyObject *python_process_brstacksym(struct perf_sample *sample,
					   struct thread *thread)
{
	struct branch_stack *br = sample->branch_stack;
565
	struct branch_entry *entries = perf_sample__branch_entries(sample);
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
	PyObject *pylist;
	u64 i;
	char bf[512];
	struct addr_location al;

	pylist = PyList_New(0);
	if (!pylist)
		Py_FatalError("couldn't create Python list");

	if (!(br && br->nr))
		goto exit;

	for (i = 0; i < br->nr; i++) {
		PyObject *pyelem;

		pyelem = PyDict_New();
		if (!pyelem)
			Py_FatalError("couldn't create Python dictionary");

585
		thread__find_symbol_fb(thread, sample->cpumode,
586
				       entries[i].from, &al);
587 588 589 590
		get_symoff(al.sym, &al, true, bf, sizeof(bf));
		pydict_set_item_string_decref(pyelem, "from",
					      _PyUnicode_FromString(bf));

591
		thread__find_symbol_fb(thread, sample->cpumode,
592
				       entries[i].to, &al);
593 594 595 596
		get_symoff(al.sym, &al, true, bf, sizeof(bf));
		pydict_set_item_string_decref(pyelem, "to",
					      _PyUnicode_FromString(bf));

597
		get_br_mspred(&entries[i].flags, bf, sizeof(bf));
598 599 600
		pydict_set_item_string_decref(pyelem, "pred",
					      _PyUnicode_FromString(bf));

601
		if (entries[i].flags.in_tx) {
602 603 604 605 606 607 608
			pydict_set_item_string_decref(pyelem, "in_tx",
					      _PyUnicode_FromString("X"));
		} else {
			pydict_set_item_string_decref(pyelem, "in_tx",
					      _PyUnicode_FromString("-"));
		}

609
		if (entries[i].flags.abort) {
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
			pydict_set_item_string_decref(pyelem, "abort",
					      _PyUnicode_FromString("A"));
		} else {
			pydict_set_item_string_decref(pyelem, "abort",
					      _PyUnicode_FromString("-"));
		}

		PyList_Append(pylist, pyelem);
		Py_DECREF(pyelem);
	}

exit:
	return pylist;
}

625 626 627 628 629 630 631 632 633 634 635 636 637 638
static PyObject *get_sample_value_as_tuple(struct sample_read_value *value)
{
	PyObject *t;

	t = PyTuple_New(2);
	if (!t)
		Py_FatalError("couldn't create Python tuple");
	PyTuple_SetItem(t, 0, PyLong_FromUnsignedLongLong(value->id));
	PyTuple_SetItem(t, 1, PyLong_FromUnsignedLongLong(value->value));
	return t;
}

static void set_sample_read_in_dict(PyObject *dict_sample,
					 struct perf_sample *sample,
639
					 struct evsel *evsel)
640
{
641
	u64 read_format = evsel->core.attr.read_format;
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
	PyObject *values;
	unsigned int i;

	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
		pydict_set_item_string_decref(dict_sample, "time_enabled",
			PyLong_FromUnsignedLongLong(sample->read.time_enabled));
	}

	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
		pydict_set_item_string_decref(dict_sample, "time_running",
			PyLong_FromUnsignedLongLong(sample->read.time_running));
	}

	if (read_format & PERF_FORMAT_GROUP)
		values = PyList_New(sample->read.group.nr);
	else
		values = PyList_New(1);

	if (!values)
		Py_FatalError("couldn't create Python list");

	if (read_format & PERF_FORMAT_GROUP) {
		for (i = 0; i < sample->read.group.nr; i++) {
			PyObject *t = get_sample_value_as_tuple(&sample->read.group.values[i]);
			PyList_SET_ITEM(values, i, t);
		}
	} else {
		PyObject *t = get_sample_value_as_tuple(&sample->read.one);
		PyList_SET_ITEM(values, 0, t);
	}
	pydict_set_item_string_decref(dict_sample, "values", values);
}

675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
static void set_sample_datasrc_in_dict(PyObject *dict,
				       struct perf_sample *sample)
{
	struct mem_info mi = { .data_src.val = sample->data_src };
	char decode[100];

	pydict_set_item_string_decref(dict, "datasrc",
			PyLong_FromUnsignedLongLong(sample->data_src));

	perf_script__meminfo_scnprintf(decode, 100, &mi);

	pydict_set_item_string_decref(dict, "datasrc_decode",
			_PyUnicode_FromString(decode));
}

static int regs_map(struct regs_dump *regs, uint64_t mask, char *bf, int size)
{
	unsigned int i = 0, r;
	int printed = 0;

	bf[0] = 0;

697 698 699
	if (!regs || !regs->regs)
		return 0;

700 701 702 703 704 705 706 707 708 709 710 711 712
	for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
		u64 val = regs->regs[i++];

		printed += scnprintf(bf + printed, size - printed,
				     "%5s:0x%" PRIx64 " ",
				     perf_reg_name(r), val);
	}

	return printed;
}

static void set_regs_in_dict(PyObject *dict,
			     struct perf_sample *sample,
713
			     struct evsel *evsel)
714
{
715
	struct perf_event_attr *attr = &evsel->core.attr;
716 717 718 719 720 721 722 723 724 725 726 727 728
	char bf[512];

	regs_map(&sample->intr_regs, attr->sample_regs_intr, bf, sizeof(bf));

	pydict_set_item_string_decref(dict, "iregs",
			_PyUnicode_FromString(bf));

	regs_map(&sample->user_regs, attr->sample_regs_user, bf, sizeof(bf));

	pydict_set_item_string_decref(dict, "uregs",
			_PyUnicode_FromString(bf));
}

729
static PyObject *get_perf_sample_dict(struct perf_sample *sample,
730
					 struct evsel *evsel,
731 732 733
					 struct addr_location *al,
					 PyObject *callchain)
{
734
	PyObject *dict, *dict_sample, *brstack, *brstacksym;
735 736 737 738 739 740 741 742 743

	dict = PyDict_New();
	if (!dict)
		Py_FatalError("couldn't create Python dictionary");

	dict_sample = PyDict_New();
	if (!dict_sample)
		Py_FatalError("couldn't create Python dictionary");

744
	pydict_set_item_string_decref(dict, "ev_name", _PyUnicode_FromString(evsel__name(evsel)));
745
	pydict_set_item_string_decref(dict, "attr", _PyBytes_FromStringAndSize((const char *)&evsel->core.attr, sizeof(evsel->core.attr)));
746 747

	pydict_set_item_string_decref(dict_sample, "pid",
748
			_PyLong_FromLong(sample->pid));
749
	pydict_set_item_string_decref(dict_sample, "tid",
750
			_PyLong_FromLong(sample->tid));
751
	pydict_set_item_string_decref(dict_sample, "cpu",
752
			_PyLong_FromLong(sample->cpu));
753 754 755 756 757 758
	pydict_set_item_string_decref(dict_sample, "ip",
			PyLong_FromUnsignedLongLong(sample->ip));
	pydict_set_item_string_decref(dict_sample, "time",
			PyLong_FromUnsignedLongLong(sample->time));
	pydict_set_item_string_decref(dict_sample, "period",
			PyLong_FromUnsignedLongLong(sample->period));
759 760
	pydict_set_item_string_decref(dict_sample, "phys_addr",
			PyLong_FromUnsignedLongLong(sample->phys_addr));
761 762
	pydict_set_item_string_decref(dict_sample, "addr",
			PyLong_FromUnsignedLongLong(sample->addr));
763
	set_sample_read_in_dict(dict_sample, sample, evsel);
764 765 766 767 768
	pydict_set_item_string_decref(dict_sample, "weight",
			PyLong_FromUnsignedLongLong(sample->weight));
	pydict_set_item_string_decref(dict_sample, "transaction",
			PyLong_FromUnsignedLongLong(sample->transaction));
	set_sample_datasrc_in_dict(dict_sample, sample);
769 770
	pydict_set_item_string_decref(dict, "sample", dict_sample);

771
	pydict_set_item_string_decref(dict, "raw_buf", _PyBytes_FromStringAndSize(
772 773
			(const char *)sample->raw_data, sample->raw_size));
	pydict_set_item_string_decref(dict, "comm",
774
			_PyUnicode_FromString(thread__comm_str(al->thread)));
775 776
	if (al->map) {
		pydict_set_item_string_decref(dict, "dso",
777
			_PyUnicode_FromString(al->map->dso->name));
778 779 780
	}
	if (al->sym) {
		pydict_set_item_string_decref(dict, "symbol",
781
			_PyUnicode_FromString(al->sym->name));
782 783 784 785
	}

	pydict_set_item_string_decref(dict, "callchain", callchain);

786 787 788 789 790 791 792 793
	brstack = python_process_brstack(sample, al->thread);
	pydict_set_item_string_decref(dict, "brstack", brstack);

	brstacksym = python_process_brstacksym(sample, al->thread);
	pydict_set_item_string_decref(dict, "brstacksym", brstacksym);

	set_regs_in_dict(dict, sample, evsel);

794 795 796
	return dict;
}

797
static void python_process_tracepoint(struct perf_sample *sample,
798
				      struct evsel *evsel,
799
				      struct addr_location *al)
800
{
801
	struct tep_event *event = evsel->tp_format;
802
	PyObject *handler, *context, *t, *obj = NULL, *callchain;
803
	PyObject *dict = NULL, *all_entries_dict = NULL;
804
	static char handler_name[256];
805
	struct tep_format_field *field;
806 807 808
	unsigned long s, ns;
	unsigned n = 0;
	int pid;
809 810 811
	int cpu = sample->cpu;
	void *data = sample->raw_data;
	unsigned long long nsecs = sample->time;
812
	const char *comm = thread__comm_str(al->thread);
813
	const char *default_handler_name = "trace_unhandled";
814

815 816
	if (!event) {
		snprintf(handler_name, sizeof(handler_name),
817
			 "ug! no event found for type %" PRIu64, (u64)evsel->core.attr.config);
818 819
		Py_FatalError(handler_name);
	}
820

821
	pid = raw_field_value(event, "common_pid", data);
822 823 824

	sprintf(handler_name, "%s__%s", event->system, event->name);

825 826 827
	if (!test_and_set_bit(event->id, events_defined))
		define_event_symbols(event, handler_name, event->print_fmt.args);

828
	handler = get_handler(handler_name);
829
	if (!handler) {
830 831 832
		handler = get_handler(default_handler_name);
		if (!handler)
			return;
833 834 835 836
		dict = PyDict_New();
		if (!dict)
			Py_FatalError("couldn't create Python dict");
	}
837 838 839 840 841 842

	t = PyTuple_New(MAX_FIELDS);
	if (!t)
		Py_FatalError("couldn't create Python tuple");


843 844
	s = nsecs / NSEC_PER_SEC;
	ns = nsecs - s * NSEC_PER_SEC;
845 846

	scripting_context->event_data = data;
847
	scripting_context->pevent = evsel->tp_format->tep;
848

849
	context = _PyCapsule_New(scripting_context, NULL, NULL);
850

851
	PyTuple_SetItem(t, n++, _PyUnicode_FromString(handler_name));
K
Kyle McMartin 已提交
852
	PyTuple_SetItem(t, n++, context);
853

854 855
	/* ip unwinding */
	callchain = python_process_callchain(sample, evsel, al);
856 857
	/* Need an additional reference for the perf_sample dict */
	Py_INCREF(callchain);
858

859
	if (!dict) {
860 861 862 863 864
		PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
		PyTuple_SetItem(t, n++, _PyLong_FromLong(s));
		PyTuple_SetItem(t, n++, _PyLong_FromLong(ns));
		PyTuple_SetItem(t, n++, _PyLong_FromLong(pid));
		PyTuple_SetItem(t, n++, _PyUnicode_FromString(comm));
865
		PyTuple_SetItem(t, n++, callchain);
866
	} else {
867 868 869 870 871
		pydict_set_item_string_decref(dict, "common_cpu", _PyLong_FromLong(cpu));
		pydict_set_item_string_decref(dict, "common_s", _PyLong_FromLong(s));
		pydict_set_item_string_decref(dict, "common_ns", _PyLong_FromLong(ns));
		pydict_set_item_string_decref(dict, "common_pid", _PyLong_FromLong(pid));
		pydict_set_item_string_decref(dict, "common_comm", _PyUnicode_FromString(comm));
872
		pydict_set_item_string_decref(dict, "common_callchain", callchain);
873
	}
874
	for (field = event->format.fields; field; field = field->next) {
875 876 877
		unsigned int offset, len;
		unsigned long long val;

878
		if (field->flags & TEP_FIELD_IS_ARRAY) {
879 880
			offset = field->offset;
			len    = field->size;
881
			if (field->flags & TEP_FIELD_IS_DYNAMIC) {
882 883
				val     = tep_read_number(scripting_context->pevent,
							  data + offset, len);
884 885
				offset  = val;
				len     = offset >> 16;
886
				offset &= 0xffff;
887
			}
888
			if (field->flags & TEP_FIELD_IS_STRING &&
889
			    is_printable_array(data + offset, len)) {
890
				obj = _PyUnicode_FromString((char *) data + offset);
891 892
			} else {
				obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
893
				field->flags &= ~TEP_FIELD_IS_STRING;
894
			}
895
		} else { /* FIELD_IS_NUMERIC */
896
			obj = get_field_numeric_entry(event, field, data);
897
		}
898
		if (!dict)
899 900
			PyTuple_SetItem(t, n++, obj);
		else
901
			pydict_set_item_string_decref(dict, field->name, obj);
902

903
	}
904

905
	if (dict)
906
		PyTuple_SetItem(t, n++, dict);
907

908 909 910 911 912 913 914 915
	if (get_argument_count(handler) == (int) n + 1) {
		all_entries_dict = get_perf_sample_dict(sample, evsel, al,
			callchain);
		PyTuple_SetItem(t, n++,	all_entries_dict);
	} else {
		Py_DECREF(callchain);
	}

916 917 918
	if (_PyTuple_Resize(&t, n) == -1)
		Py_FatalError("error resizing Python tuple");

919
	if (!dict)
920
		call_object(handler, t, handler_name);
921
	else
922
		call_object(handler, t, default_handler_name);
923 924 925 926

	Py_DECREF(t);
}

927 928 929 930 931 932 933 934 935 936 937 938 939
static PyObject *tuple_new(unsigned int sz)
{
	PyObject *t;

	t = PyTuple_New(sz);
	if (!t)
		Py_FatalError("couldn't create Python tuple");
	return t;
}

static int tuple_set_u64(PyObject *t, unsigned int pos, u64 val)
{
#if BITS_PER_LONG == 64
940
	return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
941 942 943 944 945 946 947 948
#endif
#if BITS_PER_LONG == 32
	return PyTuple_SetItem(t, pos, PyLong_FromLongLong(val));
#endif
}

static int tuple_set_s32(PyObject *t, unsigned int pos, s32 val)
{
949
	return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
950 951 952 953
}

static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
{
954
	return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
955 956
}

957 958 959 960 961 962
static int tuple_set_bytes(PyObject *t, unsigned int pos, void *bytes,
			   unsigned int sz)
{
	return PyTuple_SetItem(t, pos, _PyBytes_FromStringAndSize(bytes, sz));
}

963
static int python_export_evsel(struct db_export *dbe, struct evsel *evsel)
964 965 966 967 968 969 970
{
	struct tables *tables = container_of(dbe, struct tables, dbe);
	PyObject *t;

	t = tuple_new(2);

	tuple_set_u64(t, 0, evsel->db_id);
971
	tuple_set_string(t, 1, evsel__name(evsel));
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019

	call_object(tables->evsel_handler, t, "evsel_table");

	Py_DECREF(t);

	return 0;
}

static int python_export_machine(struct db_export *dbe,
				 struct machine *machine)
{
	struct tables *tables = container_of(dbe, struct tables, dbe);
	PyObject *t;

	t = tuple_new(3);

	tuple_set_u64(t, 0, machine->db_id);
	tuple_set_s32(t, 1, machine->pid);
	tuple_set_string(t, 2, machine->root_dir ? machine->root_dir : "");

	call_object(tables->machine_handler, t, "machine_table");

	Py_DECREF(t);

	return 0;
}

static int python_export_thread(struct db_export *dbe, struct thread *thread,
				u64 main_thread_db_id, struct machine *machine)
{
	struct tables *tables = container_of(dbe, struct tables, dbe);
	PyObject *t;

	t = tuple_new(5);

	tuple_set_u64(t, 0, thread->db_id);
	tuple_set_u64(t, 1, machine->db_id);
	tuple_set_u64(t, 2, main_thread_db_id);
	tuple_set_s32(t, 3, thread->pid_);
	tuple_set_s32(t, 4, thread->tid);

	call_object(tables->thread_handler, t, "thread_table");

	Py_DECREF(t);

	return 0;
}

1020 1021
static int python_export_comm(struct db_export *dbe, struct comm *comm,
			      struct thread *thread)
1022 1023 1024 1025
{
	struct tables *tables = container_of(dbe, struct tables, dbe);
	PyObject *t;

1026
	t = tuple_new(5);
1027 1028 1029

	tuple_set_u64(t, 0, comm->db_id);
	tuple_set_string(t, 1, comm__str(comm));
1030 1031 1032
	tuple_set_u64(t, 2, thread->db_id);
	tuple_set_u64(t, 3, comm->start);
	tuple_set_s32(t, 4, comm->exec);
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063

	call_object(tables->comm_handler, t, "comm_table");

	Py_DECREF(t);

	return 0;
}

static int python_export_comm_thread(struct db_export *dbe, u64 db_id,
				     struct comm *comm, struct thread *thread)
{
	struct tables *tables = container_of(dbe, struct tables, dbe);
	PyObject *t;

	t = tuple_new(3);

	tuple_set_u64(t, 0, db_id);
	tuple_set_u64(t, 1, comm->db_id);
	tuple_set_u64(t, 2, thread->db_id);

	call_object(tables->comm_thread_handler, t, "comm_thread_table");

	Py_DECREF(t);

	return 0;
}

static int python_export_dso(struct db_export *dbe, struct dso *dso,
			     struct machine *machine)
{
	struct tables *tables = container_of(dbe, struct tables, dbe);
1064
	char sbuild_id[SBUILD_ID_SIZE];
1065 1066
	PyObject *t;

1067
	build_id__sprintf(&dso->bid, sbuild_id);
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106

	t = tuple_new(5);

	tuple_set_u64(t, 0, dso->db_id);
	tuple_set_u64(t, 1, machine->db_id);
	tuple_set_string(t, 2, dso->short_name);
	tuple_set_string(t, 3, dso->long_name);
	tuple_set_string(t, 4, sbuild_id);

	call_object(tables->dso_handler, t, "dso_table");

	Py_DECREF(t);

	return 0;
}

static int python_export_symbol(struct db_export *dbe, struct symbol *sym,
				struct dso *dso)
{
	struct tables *tables = container_of(dbe, struct tables, dbe);
	u64 *sym_db_id = symbol__priv(sym);
	PyObject *t;

	t = tuple_new(6);

	tuple_set_u64(t, 0, *sym_db_id);
	tuple_set_u64(t, 1, dso->db_id);
	tuple_set_u64(t, 2, sym->start);
	tuple_set_u64(t, 3, sym->end);
	tuple_set_s32(t, 4, sym->binding);
	tuple_set_string(t, 5, sym->name);

	call_object(tables->symbol_handler, t, "symbol_table");

	Py_DECREF(t);

	return 0;
}

1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
static int python_export_branch_type(struct db_export *dbe, u32 branch_type,
				     const char *name)
{
	struct tables *tables = container_of(dbe, struct tables, dbe);
	PyObject *t;

	t = tuple_new(2);

	tuple_set_s32(t, 0, branch_type);
	tuple_set_string(t, 1, name);

	call_object(tables->branch_type_handler, t, "branch_type_table");

	Py_DECREF(t);

	return 0;
}

1125 1126
static void python_export_sample_table(struct db_export *dbe,
				       struct export_sample *es)
1127 1128 1129 1130
{
	struct tables *tables = container_of(dbe, struct tables, dbe);
	PyObject *t;

1131
	t = tuple_new(24);
1132 1133 1134

	tuple_set_u64(t, 0, es->db_id);
	tuple_set_u64(t, 1, es->evsel->db_id);
1135
	tuple_set_u64(t, 2, es->al->maps->machine->db_id);
1136
	tuple_set_u64(t, 3, es->al->thread->db_id);
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
	tuple_set_u64(t, 4, es->comm_db_id);
	tuple_set_u64(t, 5, es->dso_db_id);
	tuple_set_u64(t, 6, es->sym_db_id);
	tuple_set_u64(t, 7, es->offset);
	tuple_set_u64(t, 8, es->sample->ip);
	tuple_set_u64(t, 9, es->sample->time);
	tuple_set_s32(t, 10, es->sample->cpu);
	tuple_set_u64(t, 11, es->addr_dso_db_id);
	tuple_set_u64(t, 12, es->addr_sym_db_id);
	tuple_set_u64(t, 13, es->addr_offset);
	tuple_set_u64(t, 14, es->sample->addr);
	tuple_set_u64(t, 15, es->sample->period);
	tuple_set_u64(t, 16, es->sample->weight);
	tuple_set_u64(t, 17, es->sample->transaction);
	tuple_set_u64(t, 18, es->sample->data_src);
1152 1153
	tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
	tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
1154
	tuple_set_u64(t, 21, es->call_path_id);
1155 1156
	tuple_set_u64(t, 22, es->sample->insn_cnt);
	tuple_set_u64(t, 23, es->sample->cyc_cnt);
1157 1158 1159 1160

	call_object(tables->sample_handler, t, "sample_table");

	Py_DECREF(t);
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
}

static void python_export_synth(struct db_export *dbe, struct export_sample *es)
{
	struct tables *tables = container_of(dbe, struct tables, dbe);
	PyObject *t;

	t = tuple_new(3);

	tuple_set_u64(t, 0, es->db_id);
1171
	tuple_set_u64(t, 1, es->evsel->core.attr.config);
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
	tuple_set_bytes(t, 2, es->sample->raw_data, es->sample->raw_size);

	call_object(tables->synth_handler, t, "synth_data");

	Py_DECREF(t);
}

static int python_export_sample(struct db_export *dbe,
				struct export_sample *es)
{
	struct tables *tables = container_of(dbe, struct tables, dbe);

	python_export_sample_table(dbe, es);

1186
	if (es->evsel->core.attr.type == PERF_TYPE_SYNTH && tables->synth_handler)
1187
		python_export_synth(dbe, es);
1188 1189 1190 1191

	return 0;
}

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
static int python_export_call_path(struct db_export *dbe, struct call_path *cp)
{
	struct tables *tables = container_of(dbe, struct tables, dbe);
	PyObject *t;
	u64 parent_db_id, sym_db_id;

	parent_db_id = cp->parent ? cp->parent->db_id : 0;
	sym_db_id = cp->sym ? *(u64 *)symbol__priv(cp->sym) : 0;

	t = tuple_new(4);

	tuple_set_u64(t, 0, cp->db_id);
	tuple_set_u64(t, 1, parent_db_id);
	tuple_set_u64(t, 2, sym_db_id);
	tuple_set_u64(t, 3, cp->ip);

	call_object(tables->call_path_handler, t, "call_path_table");

	Py_DECREF(t);

	return 0;
}

static int python_export_call_return(struct db_export *dbe,
				     struct call_return *cr)
{
	struct tables *tables = container_of(dbe, struct tables, dbe);
	u64 comm_db_id = cr->comm ? cr->comm->db_id : 0;
	PyObject *t;

1222
	t = tuple_new(14);
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234

	tuple_set_u64(t, 0, cr->db_id);
	tuple_set_u64(t, 1, cr->thread->db_id);
	tuple_set_u64(t, 2, comm_db_id);
	tuple_set_u64(t, 3, cr->cp->db_id);
	tuple_set_u64(t, 4, cr->call_time);
	tuple_set_u64(t, 5, cr->return_time);
	tuple_set_u64(t, 6, cr->branch_count);
	tuple_set_u64(t, 7, cr->call_ref);
	tuple_set_u64(t, 8, cr->return_ref);
	tuple_set_u64(t, 9, cr->cp->parent->db_id);
	tuple_set_s32(t, 10, cr->flags);
1235
	tuple_set_u64(t, 11, cr->parent_db_id);
1236 1237
	tuple_set_u64(t, 12, cr->insn_count);
	tuple_set_u64(t, 13, cr->cyc_count);
1238 1239 1240 1241 1242 1243 1244 1245

	call_object(tables->call_return_handler, t, "call_return_table");

	Py_DECREF(t);

	return 0;
}

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
static int 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)
{
	struct tables *tables = container_of(dbe, struct tables, dbe);
	PyObject *t;

	t = tuple_new(9);

	tuple_set_u64(t, 0, db_id);
	tuple_set_u64(t, 1, machine->db_id);
	tuple_set_u64(t, 2, sample->time);
	tuple_set_s32(t, 3, sample->cpu);
	tuple_set_u64(t, 4, th_out_id);
	tuple_set_u64(t, 5, comm_out_id);
	tuple_set_u64(t, 6, th_in_id);
	tuple_set_u64(t, 7, comm_in_id);
	tuple_set_s32(t, 8, flags);

	call_object(tables->context_switch_handler, t, "context_switch");

	Py_DECREF(t);

	return 0;
}

1274 1275
static int python_process_call_return(struct call_return *cr, u64 *parent_db_id,
				      void *data)
1276 1277 1278
{
	struct db_export *dbe = data;

1279
	return db_export__call_return(dbe, cr, parent_db_id);
1280 1281
}

1282
static void python_process_general_event(struct perf_sample *sample,
1283
					 struct evsel *evsel,
1284
					 struct addr_location *al)
1285
{
1286
	PyObject *handler, *t, *dict, *callchain;
1287 1288 1289
	static char handler_name[64];
	unsigned n = 0;

1290 1291 1292 1293 1294 1295
	snprintf(handler_name, sizeof(handler_name), "%s", "process_event");

	handler = get_handler(handler_name);
	if (!handler)
		return;

1296 1297
	/*
	 * Use the MAX_FIELDS to make the function expandable, though
1298
	 * currently there is only one item for the tuple.
1299
	 */
1300 1301 1302 1303
	t = PyTuple_New(MAX_FIELDS);
	if (!t)
		Py_FatalError("couldn't create Python tuple");

1304 1305
	/* ip unwinding */
	callchain = python_process_callchain(sample, evsel, al);
1306
	dict = get_perf_sample_dict(sample, evsel, al, callchain);
1307

1308
	PyTuple_SetItem(t, n++, dict);
1309 1310 1311
	if (_PyTuple_Resize(&t, n) == -1)
		Py_FatalError("error resizing Python tuple");

1312
	call_object(handler, t, handler_name);
1313

1314 1315 1316
	Py_DECREF(t);
}

1317
static void python_process_event(union perf_event *event,
1318
				 struct perf_sample *sample,
1319
				 struct evsel *evsel,
1320
				 struct addr_location *al)
1321
{
1322 1323
	struct tables *tables = &tables_global;

1324
	switch (evsel->core.attr.type) {
1325
	case PERF_TYPE_TRACEPOINT:
1326
		python_process_tracepoint(sample, evsel, al);
1327 1328 1329
		break;
	/* Reserve for future process_hw/sw/raw APIs */
	default:
1330
		if (tables->db_export_mode)
1331
			db_export__sample(&tables->dbe, event, sample, evsel, al);
1332
		else
1333
			python_process_general_event(sample, evsel, al);
1334 1335 1336
	}
}

1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
static void python_process_switch(union perf_event *event,
				  struct perf_sample *sample,
				  struct machine *machine)
{
	struct tables *tables = &tables_global;

	if (tables->db_export_mode)
		db_export__switch(&tables->dbe, event, sample, machine);
}

1347
static void get_handler_name(char *str, size_t size,
1348
			     struct evsel *evsel)
1349 1350 1351
{
	char *p = str;

1352
	scnprintf(str, size, "stat__%s", evsel__name(evsel));
1353 1354 1355 1356 1357 1358 1359 1360

	while ((p = strchr(p, ':'))) {
		*p = '_';
		p++;
	}
}

static void
1361
process_stat(struct evsel *counter, int cpu, int thread, u64 tstamp,
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
	     struct perf_counts_values *count)
{
	PyObject *handler, *t;
	static char handler_name[256];
	int n = 0;

	t = PyTuple_New(MAX_FIELDS);
	if (!t)
		Py_FatalError("couldn't create Python tuple");

	get_handler_name(handler_name, sizeof(handler_name),
			 counter);

	handler = get_handler(handler_name);
	if (!handler) {
		pr_debug("can't find python handler %s\n", handler_name);
		return;
	}

1381 1382
	PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
	PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397

	tuple_set_u64(t, n++, tstamp);
	tuple_set_u64(t, n++, count->val);
	tuple_set_u64(t, n++, count->ena);
	tuple_set_u64(t, n++, count->run);

	if (_PyTuple_Resize(&t, n) == -1)
		Py_FatalError("error resizing Python tuple");

	call_object(handler, t, handler_name);

	Py_DECREF(t);
}

static void python_process_stat(struct perf_stat_config *config,
1398
				struct evsel *counter, u64 tstamp)
1399
{
1400
	struct perf_thread_map *threads = counter->core.threads;
1401
	struct perf_cpu_map *cpus = counter->core.cpus;
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
	int cpu, thread;

	if (config->aggr_mode == AGGR_GLOBAL) {
		process_stat(counter, -1, -1, tstamp,
			     &counter->counts->aggr);
		return;
	}

	for (thread = 0; thread < threads->nr; thread++) {
		for (cpu = 0; cpu < cpus->nr; cpu++) {
			process_stat(counter, cpus->map[cpu],
1413
				     perf_thread_map__pid(threads, thread), tstamp,
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
				     perf_counts(counter->counts, cpu, thread));
		}
	}
}

static void python_process_stat_interval(u64 tstamp)
{
	PyObject *handler, *t;
	static const char handler_name[] = "stat__interval";
	int n = 0;

	t = PyTuple_New(MAX_FIELDS);
	if (!t)
		Py_FatalError("couldn't create Python tuple");

	handler = get_handler(handler_name);
	if (!handler) {
		pr_debug("can't find python handler %s\n", handler_name);
		return;
	}

	tuple_set_u64(t, n++, tstamp);

	if (_PyTuple_Resize(&t, n) == -1)
		Py_FatalError("error resizing Python tuple");

	call_object(handler, t, handler_name);

	Py_DECREF(t);
}

1445 1446 1447 1448 1449 1450 1451 1452
static int run_start_sub(void)
{
	main_module = PyImport_AddModule("__main__");
	if (main_module == NULL)
		return -1;
	Py_INCREF(main_module);

	main_dict = PyModule_GetDict(main_module);
1453
	if (main_dict == NULL)
1454 1455 1456
		goto error;
	Py_INCREF(main_dict);

1457
	try_call_object("trace_begin", NULL);
1458

1459
	return 0;
1460 1461 1462 1463

error:
	Py_XDECREF(main_dict);
	Py_XDECREF(main_module);
1464
	return -1;
1465 1466
}

1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
#define SET_TABLE_HANDLER_(name, handler_name, table_name) do {		\
	tables->handler_name = get_handler(#table_name);		\
	if (tables->handler_name)					\
		tables->dbe.export_ ## name = python_export_ ## name;	\
} while (0)

#define SET_TABLE_HANDLER(name) \
	SET_TABLE_HANDLER_(name, name ## _handler, name ## _table)

static void set_table_handlers(struct tables *tables)
{
	const char *perf_db_export_mode = "perf_db_export_mode";
1479
	const char *perf_db_export_calls = "perf_db_export_calls";
1480 1481
	const char *perf_db_export_callchains = "perf_db_export_callchains";
	PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
1482
	bool export_calls = false;
1483
	bool export_callchains = false;
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
	int ret;

	memset(tables, 0, sizeof(struct tables));
	if (db_export__init(&tables->dbe))
		Py_FatalError("failed to initialize export");

	db_export_mode = PyDict_GetItemString(main_dict, perf_db_export_mode);
	if (!db_export_mode)
		return;

	ret = PyObject_IsTrue(db_export_mode);
	if (ret == -1)
		handler_call_die(perf_db_export_mode);
	if (!ret)
		return;

1500
	/* handle export calls */
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
	tables->dbe.crp = NULL;
	db_export_calls = PyDict_GetItemString(main_dict, perf_db_export_calls);
	if (db_export_calls) {
		ret = PyObject_IsTrue(db_export_calls);
		if (ret == -1)
			handler_call_die(perf_db_export_calls);
		export_calls = !!ret;
	}

	if (export_calls) {
		tables->dbe.crp =
			call_return_processor__new(python_process_call_return,
						   &tables->dbe);
		if (!tables->dbe.crp)
			Py_FatalError("failed to create calls processor");
	}

1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
	/* handle export callchains */
	tables->dbe.cpr = NULL;
	db_export_callchains = PyDict_GetItemString(main_dict,
						    perf_db_export_callchains);
	if (db_export_callchains) {
		ret = PyObject_IsTrue(db_export_callchains);
		if (ret == -1)
			handler_call_die(perf_db_export_callchains);
		export_callchains = !!ret;
	}

	if (export_callchains) {
		/*
		 * Attempt to use the call path root from the call return
		 * processor, if the call return processor is in use. Otherwise,
		 * we allocate a new call path root. This prevents exporting
1534
		 * duplicate call path ids when both are in use simultaneously.
1535 1536 1537 1538 1539 1540 1541
		 */
		if (tables->dbe.crp)
			tables->dbe.cpr = tables->dbe.crp->cpr;
		else
			tables->dbe.cpr = call_path_root__new();

		if (!tables->dbe.cpr)
1542
			Py_FatalError("failed to create call path root");
1543 1544
	}

1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
	tables->db_export_mode = true;
	/*
	 * Reserve per symbol space for symbol->db_id via symbol__priv()
	 */
	symbol_conf.priv_size = sizeof(u64);

	SET_TABLE_HANDLER(evsel);
	SET_TABLE_HANDLER(machine);
	SET_TABLE_HANDLER(thread);
	SET_TABLE_HANDLER(comm);
	SET_TABLE_HANDLER(comm_thread);
	SET_TABLE_HANDLER(dso);
	SET_TABLE_HANDLER(symbol);
1558
	SET_TABLE_HANDLER(branch_type);
1559
	SET_TABLE_HANDLER(sample);
1560 1561
	SET_TABLE_HANDLER(call_path);
	SET_TABLE_HANDLER(call_return);
1562
	SET_TABLE_HANDLER(context_switch);
1563 1564 1565 1566 1567 1568 1569 1570

	/*
	 * Synthesized events are samples but with architecture-specific data
	 * stored in sample->raw_data. They are exported via
	 * python_export_sample() and consequently do not need a separate export
	 * callback.
	 */
	tables->synth_handler = get_handler("synth_data");
1571 1572
}

1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
#if PY_MAJOR_VERSION < 3
static void _free_command_line(const char **command_line, int num)
{
	free(command_line);
}
#else
static void _free_command_line(wchar_t **command_line, int num)
{
	int i;
	for (i = 0; i < num; i++)
		PyMem_RawFree(command_line[i]);
	free(command_line);
}
#endif


1589 1590 1591 1592 1593
/*
 * Start trace script
 */
static int python_start_script(const char *script, int argc, const char **argv)
{
1594
	struct tables *tables = &tables_global;
1595
#if PY_MAJOR_VERSION < 3
1596
	const char **command_line;
1597 1598 1599
#else
	wchar_t **command_line;
#endif
1600 1601 1602 1603 1604
	/*
	 * Use a non-const name variable to cope with python 2.6's
	 * PyImport_AppendInittab prototype
	 */
	char buf[PATH_MAX], name[19] = "perf_trace_context";
1605 1606 1607
	int i, err = 0;
	FILE *fp;

1608
#if PY_MAJOR_VERSION < 3
1609 1610 1611 1612
	command_line = malloc((argc + 1) * sizeof(const char *));
	command_line[0] = script;
	for (i = 1; i < argc + 1; i++)
		command_line[i] = argv[i - 1];
1613
	PyImport_AppendInittab(name, initperf_trace_context);
1614 1615 1616 1617 1618
#else
	command_line = malloc((argc + 1) * sizeof(wchar_t *));
	command_line[0] = Py_DecodeLocale(script, NULL);
	for (i = 1; i < argc + 1; i++)
		command_line[i] = Py_DecodeLocale(argv[i - 1], NULL);
1619
	PyImport_AppendInittab(name, PyInit_perf_trace_context);
1620
#endif
1621 1622
	Py_Initialize();

1623
#if PY_MAJOR_VERSION < 3
1624
	PySys_SetArgv(argc + 1, (char **)command_line);
1625 1626 1627
#else
	PySys_SetArgv(argc + 1, command_line);
#endif
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648

	fp = fopen(script, "r");
	if (!fp) {
		sprintf(buf, "Can't open python script \"%s\"", script);
		perror(buf);
		err = -1;
		goto error;
	}

	err = PyRun_SimpleFile(fp, script);
	if (err) {
		fprintf(stderr, "Error running python script %s\n", script);
		goto error;
	}

	err = run_start_sub();
	if (err) {
		fprintf(stderr, "Error starting python script %s\n", script);
		goto error;
	}

1649 1650
	set_table_handlers(tables);

1651 1652 1653 1654 1655 1656
	if (tables->db_export_mode) {
		err = db_export__branch_types(&tables->dbe);
		if (err)
			goto error;
	}

1657
	_free_command_line(command_line, argc + 1);
1658

1659 1660 1661
	return err;
error:
	Py_Finalize();
1662
	_free_command_line(command_line, argc + 1);
1663 1664 1665 1666

	return err;
}

1667 1668
static int python_flush_script(void)
{
1669
	return 0;
1670 1671
}

1672 1673 1674 1675 1676
/*
 * Stop trace script
 */
static int python_stop_script(void)
{
1677 1678
	struct tables *tables = &tables_global;

1679
	try_call_object("trace_end", NULL);
1680

1681 1682
	db_export__exit(&tables->dbe);

1683 1684 1685 1686
	Py_XDECREF(main_dict);
	Py_XDECREF(main_module);
	Py_Finalize();

1687
	return 0;
1688 1689
}

1690
static int python_generate_script(struct tep_handle *pevent, const char *outfile)
1691
{
1692 1693
	int i, not_first, count, nr_events;
	struct tep_event **all_events;
1694
	struct tep_event *event = NULL;
1695
	struct tep_format_field *f;
1696 1697 1698 1699 1700 1701 1702 1703 1704
	char fname[PATH_MAX];
	FILE *ofp;

	sprintf(fname, "%s.py", outfile);
	ofp = fopen(fname, "w");
	if (ofp == NULL) {
		fprintf(stderr, "couldn't open %s\n", fname);
		return -1;
	}
1705 1706
	fprintf(ofp, "# perf script event handlers, "
		"generated by perf script -g python\n");
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722

	fprintf(ofp, "# Licensed under the terms of the GNU GPL"
		" License version 2\n\n");

	fprintf(ofp, "# The common_* event handler fields are the most useful "
		"fields common to\n");

	fprintf(ofp, "# all events.  They don't necessarily correspond to "
		"the 'common_*' fields\n");

	fprintf(ofp, "# in the format files.  Those fields not available as "
		"handler params can\n");

	fprintf(ofp, "# be retrieved using Python functions of the form "
		"common_*(context).\n");

1723
	fprintf(ofp, "# See the perf-script-python Documentation for the list "
1724 1725
		"of available functions.\n\n");

1726
	fprintf(ofp, "from __future__ import print_function\n\n");
1727 1728 1729 1730 1731 1732 1733 1734 1735
	fprintf(ofp, "import os\n");
	fprintf(ofp, "import sys\n\n");

	fprintf(ofp, "sys.path.append(os.environ['PERF_EXEC_PATH'] + \\\n");
	fprintf(ofp, "\t'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')\n");
	fprintf(ofp, "\nfrom perf_trace_context import *\n");
	fprintf(ofp, "from Core import *\n\n\n");

	fprintf(ofp, "def trace_begin():\n");
1736
	fprintf(ofp, "\tprint(\"in trace_begin\")\n\n");
1737 1738

	fprintf(ofp, "def trace_end():\n");
1739
	fprintf(ofp, "\tprint(\"in trace_end\")\n\n");
1740

1741 1742 1743 1744 1745
	nr_events = tep_get_events_count(pevent);
	all_events = tep_list_events(pevent, TEP_EVENT_SORT_ID);

	for (i = 0; all_events && i < nr_events; i++) {
		event = all_events[i];
1746 1747 1748 1749 1750 1751 1752 1753
		fprintf(ofp, "def %s__%s(", event->system, event->name);
		fprintf(ofp, "event_name, ");
		fprintf(ofp, "context, ");
		fprintf(ofp, "common_cpu,\n");
		fprintf(ofp, "\tcommon_secs, ");
		fprintf(ofp, "common_nsecs, ");
		fprintf(ofp, "common_pid, ");
		fprintf(ofp, "common_comm,\n\t");
1754
		fprintf(ofp, "common_callchain, ");
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766

		not_first = 0;
		count = 0;

		for (f = event->format.fields; f; f = f->next) {
			if (not_first++)
				fprintf(ofp, ", ");
			if (++count % 5 == 0)
				fprintf(ofp, "\n\t");

			fprintf(ofp, "%s", f->name);
		}
1767 1768 1769 1770 1771 1772
		if (not_first++)
			fprintf(ofp, ", ");
		if (++count % 5 == 0)
			fprintf(ofp, "\n\t\t");
		fprintf(ofp, "perf_sample_dict");

1773 1774 1775 1776 1777 1778
		fprintf(ofp, "):\n");

		fprintf(ofp, "\t\tprint_header(event_name, common_cpu, "
			"common_secs, common_nsecs,\n\t\t\t"
			"common_pid, common_comm)\n\n");

1779
		fprintf(ofp, "\t\tprint(\"");
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792

		not_first = 0;
		count = 0;

		for (f = event->format.fields; f; f = f->next) {
			if (not_first++)
				fprintf(ofp, ", ");
			if (count && count % 3 == 0) {
				fprintf(ofp, "\" \\\n\t\t\"");
			}
			count++;

			fprintf(ofp, "%s=", f->name);
1793 1794 1795 1796
			if (f->flags & TEP_FIELD_IS_STRING ||
			    f->flags & TEP_FIELD_IS_FLAG ||
			    f->flags & TEP_FIELD_IS_ARRAY ||
			    f->flags & TEP_FIELD_IS_SYMBOLIC)
1797
				fprintf(ofp, "%%s");
1798
			else if (f->flags & TEP_FIELD_IS_SIGNED)
1799 1800 1801 1802 1803
				fprintf(ofp, "%%d");
			else
				fprintf(ofp, "%%u");
		}

1804
		fprintf(ofp, "\" %% \\\n\t\t(");
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815

		not_first = 0;
		count = 0;

		for (f = event->format.fields; f; f = f->next) {
			if (not_first++)
				fprintf(ofp, ", ");

			if (++count % 5 == 0)
				fprintf(ofp, "\n\t\t");

1816
			if (f->flags & TEP_FIELD_IS_FLAG) {
1817 1818 1819 1820 1821 1822 1823 1824 1825
				if ((count - 1) % 5 != 0) {
					fprintf(ofp, "\n\t\t");
					count = 4;
				}
				fprintf(ofp, "flag_str(\"");
				fprintf(ofp, "%s__%s\", ", event->system,
					event->name);
				fprintf(ofp, "\"%s\", %s)", f->name,
					f->name);
1826
			} else if (f->flags & TEP_FIELD_IS_SYMBOLIC) {
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
				if ((count - 1) % 5 != 0) {
					fprintf(ofp, "\n\t\t");
					count = 4;
				}
				fprintf(ofp, "symbol_str(\"");
				fprintf(ofp, "%s__%s\", ", event->system,
					event->name);
				fprintf(ofp, "\"%s\", %s)", f->name,
					f->name);
			} else
				fprintf(ofp, "%s", f->name);
		}

1840
		fprintf(ofp, "))\n\n");
1841

1842 1843
		fprintf(ofp, "\t\tprint('Sample: {'+"
			"get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
1844

1845 1846
		fprintf(ofp, "\t\tfor node in common_callchain:");
		fprintf(ofp, "\n\t\t\tif 'sym' in node:");
1847
		fprintf(ofp, "\n\t\t\t\tprint(\"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name']))");
1848
		fprintf(ofp, "\n\t\t\telse:");
1849 1850
		fprintf(ofp, "\n\t\t\t\tprint(\"\t[%%x]\" %% (node['ip']))\n\n");
		fprintf(ofp, "\t\tprint()\n\n");
1851

1852 1853 1854
	}

	fprintf(ofp, "def trace_unhandled(event_name, context, "
1855
		"event_fields_dict, perf_sample_dict):\n");
1856

1857 1858 1859
	fprintf(ofp, "\t\tprint(get_dict_as_string(event_fields_dict))\n");
	fprintf(ofp, "\t\tprint('Sample: {'+"
		"get_dict_as_string(perf_sample_dict['sample'], ', ')+'}')\n\n");
1860 1861 1862

	fprintf(ofp, "def print_header("
		"event_name, cpu, secs, nsecs, pid, comm):\n"
1863 1864
		"\tprint(\"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
		"(event_name, cpu, secs, nsecs, pid, comm), end=\"\")\n\n");
1865 1866 1867 1868

	fprintf(ofp, "def get_dict_as_string(a_dict, delimiter=' '):\n"
		"\treturn delimiter.join"
		"(['%%s=%%s'%%(k,str(v))for k,v in sorted(a_dict.items())])\n");
1869 1870 1871 1872 1873 1874 1875 1876 1877

	fclose(ofp);

	fprintf(stderr, "generated Python script: %s\n", fname);

	return 0;
}

struct scripting_ops python_scripting_ops = {
1878
	.name			= "Python",
1879
	.dirname		= "python",
1880 1881 1882 1883
	.start_script		= python_start_script,
	.flush_script		= python_flush_script,
	.stop_script		= python_stop_script,
	.process_event		= python_process_event,
1884
	.process_switch		= python_process_switch,
1885 1886 1887
	.process_stat		= python_process_stat,
	.process_stat_interval	= python_process_stat_interval,
	.generate_script	= python_generate_script,
1888
};