trace-event-python.c 39.5 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 "../../perf.h"
35
#include "../debug.h"
36
#include "../callchain.h"
37
#include "../evsel.h"
38
#include "../util.h"
39 40
#include "../event.h"
#include "../thread.h"
41 42 43
#include "../comm.h"
#include "../machine.h"
#include "../db-export.h"
44
#include "../thread-stack.h"
45
#include "../trace-event.h"
46
#include "../call-path.h"
47 48
#include "thread_map.h"
#include "cpumap.h"
49
#include "print_binary.h"
50
#include "stat.h"
51

52 53 54 55 56 57 58 59 60 61 62 63 64 65
#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))

66
PyMODINIT_FUNC initperf_trace_context(void);
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
#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
83

84
#define TRACE_EVENT_TYPE_MAX				\
85 86
	((1 << (sizeof(unsigned short) * 8)) - 1)

87
static DECLARE_BITMAP(events_defined, TRACE_EVENT_TYPE_MAX);
88 89 90 91 92 93 94 95 96 97 98

#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;

99 100 101 102 103 104 105 106 107
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;
108
	PyObject		*branch_type_handler;
109
	PyObject		*sample_handler;
110 111
	PyObject		*call_path_handler;
	PyObject		*call_return_handler;
112 113 114 115 116
	bool			db_export_mode;
};

static struct tables tables_global;

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

127 128
/*
 * Insert val into into the dictionary and decrement the reference counter.
129
 * This is necessary for dictionaries since PyDict_SetItemString() does not
130 131 132 133 134 135 136 137
 * 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);
}

138 139 140 141 142 143 144 145 146 147
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;
}

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
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) {
168
			arg_count = (int) _PyLong_AsLong(arg_count_obj);
169 170 171 172 173 174 175
			Py_DECREF(arg_count_obj);
		}
		Py_DECREF(code_obj);
	}
	return arg_count;
}

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
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);
}

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

	if (field_type == PRINT_SYMBOL)
		handler_name = "define_symbolic_value";

209
	t = PyTuple_New(4);
210 211 212 213 214
	if (!t)
		Py_FatalError("couldn't create Python tuple");

	value = eval_flag(field_value);

215 216 217 218
	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));
219

220
	try_call_object(handler_name, t);
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

	Py_DECREF(t);
}

static void define_values(enum print_arg_type field_type,
			  struct print_flag_sym *field,
			  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);
}

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

	if (field_type == PRINT_SYMBOL)
		handler_name = "define_symbolic_field";

249 250 251 252
	if (field_type == PRINT_FLAGS)
		t = PyTuple_New(3);
	else
		t = PyTuple_New(2);
253 254 255
	if (!t)
		Py_FatalError("couldn't create Python tuple");

256 257
	PyTuple_SetItem(t, n++, _PyUnicode_FromString(ev_name));
	PyTuple_SetItem(t, n++, _PyUnicode_FromString(field_name));
258
	if (field_type == PRINT_FLAGS)
259
		PyTuple_SetItem(t, n++, _PyUnicode_FromString(delim));
260

261
	try_call_object(handler_name, t);
262 263 264 265

	Py_DECREF(t);
}

266
static void define_event_symbols(struct event_format *event,
267 268 269
				 const char *ev_name,
				 struct print_arg *args)
{
270 271 272
	if (args == NULL)
		return;

273 274 275 276 277 278 279 280 281
	switch (args->type) {
	case PRINT_NULL:
		break;
	case PRINT_ATOM:
		define_value(PRINT_FLAGS, ev_name, cur_field_name, "0",
			     args->atom.atom);
		zero_flag_atom = 0;
		break;
	case PRINT_FIELD:
282
		free(cur_field_name);
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
		cur_field_name = strdup(args->field.name);
		break;
	case PRINT_FLAGS:
		define_event_symbols(event, ev_name, args->flags.field);
		define_field(PRINT_FLAGS, ev_name, cur_field_name,
			     args->flags.delim);
		define_values(PRINT_FLAGS, args->flags.flags, ev_name,
			      cur_field_name);
		break;
	case PRINT_SYMBOL:
		define_event_symbols(event, ev_name, args->symbol.field);
		define_field(PRINT_SYMBOL, ev_name, cur_field_name, NULL);
		define_values(PRINT_SYMBOL, args->symbol.symbols, ev_name,
			      cur_field_name);
		break;
298
	case PRINT_HEX:
299
	case PRINT_HEX_STR:
300 301 302
		define_event_symbols(event, ev_name, args->hex.field);
		define_event_symbols(event, ev_name, args->hex.size);
		break;
303 304 305 306 307
	case PRINT_INT_ARRAY:
		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;
308 309 310 311 312 313 314 315 316 317 318 319
	case PRINT_STRING:
		break;
	case PRINT_TYPE:
		define_event_symbols(event, ev_name, args->typecast.item);
		break;
	case PRINT_OP:
		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:
320 321 322
		/* gcc warns for these? */
	case PRINT_BSTRING:
	case PRINT_DYNAMIC_ARRAY:
323
	case PRINT_DYNAMIC_ARRAY_LEN:
324
	case PRINT_FUNC:
325
	case PRINT_BITMASK:
326 327 328 329 330 331 332 333
		/* we should warn... */
		return;
	}

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

334 335 336
static PyObject *get_field_numeric_entry(struct event_format *event,
		struct format_field *field, void *data)
{
337
	bool is_array = field->flags & FIELD_IS_ARRAY;
338
	PyObject *obj = NULL, *list = NULL;
339
	unsigned long long val;
340
	unsigned int item_size, n_items, i;
341

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

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

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

375 376 377 378 379 380 381 382 383 384 385 386 387 388

static PyObject *python_process_callchain(struct perf_sample *sample,
					 struct perf_evsel *evsel,
					 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;

389
	if (thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
390
				      sample, NULL, NULL,
391
				      scripting_max_stack) != 0) {
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
		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));

		if (node->sym) {
			PyObject *pysym  = PyDict_New();
			if (!pysym)
				Py_FatalError("couldn't create Python dictionary");
			pydict_set_item_string_decref(pysym, "start",
					PyLong_FromUnsignedLongLong(node->sym->start));
			pydict_set_item_string_decref(pysym, "end",
					PyLong_FromUnsignedLongLong(node->sym->end));
			pydict_set_item_string_decref(pysym, "binding",
422
					_PyLong_FromLong(node->sym->binding));
423
			pydict_set_item_string_decref(pysym, "name",
424
					_PyUnicode_FromStringAndSize(node->sym->name,
425 426 427 428 429 430 431
							node->sym->namelen));
			pydict_set_item_string_decref(pyelem, "sym", pysym);
		}

		if (node->map) {
			struct map *map = node->map;
			const char *dsoname = "[unknown]";
432
			if (map && map->dso) {
433 434
				if (symbol_conf.show_kernel_path && map->dso->long_name)
					dsoname = map->dso->long_name;
435
				else
436 437 438
					dsoname = map->dso->name;
			}
			pydict_set_item_string_decref(pyelem, "dso",
439
					_PyUnicode_FromString(dsoname));
440 441 442 443 444 445 446 447 448 449 450
		}

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

exit:
	return pylist;
}

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
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,
					 struct perf_evsel *evsel)
{
	u64 read_format = evsel->attr.read_format;
	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);
}

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
static PyObject *get_perf_sample_dict(struct perf_sample *sample,
					 struct perf_evsel *evsel,
					 struct addr_location *al,
					 PyObject *callchain)
{
	PyObject *dict, *dict_sample;

	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");

516 517
	pydict_set_item_string_decref(dict, "ev_name", _PyUnicode_FromString(perf_evsel__name(evsel)));
	pydict_set_item_string_decref(dict, "attr", _PyUnicode_FromStringAndSize(
518 519 520
			(const char *)&evsel->attr, sizeof(evsel->attr)));

	pydict_set_item_string_decref(dict_sample, "pid",
521
			_PyLong_FromLong(sample->pid));
522
	pydict_set_item_string_decref(dict_sample, "tid",
523
			_PyLong_FromLong(sample->tid));
524
	pydict_set_item_string_decref(dict_sample, "cpu",
525
			_PyLong_FromLong(sample->cpu));
526 527 528 529 530 531
	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));
532 533
	pydict_set_item_string_decref(dict_sample, "phys_addr",
			PyLong_FromUnsignedLongLong(sample->phys_addr));
534
	set_sample_read_in_dict(dict_sample, sample, evsel);
535 536
	pydict_set_item_string_decref(dict, "sample", dict_sample);

537
	pydict_set_item_string_decref(dict, "raw_buf", _PyBytes_FromStringAndSize(
538 539
			(const char *)sample->raw_data, sample->raw_size));
	pydict_set_item_string_decref(dict, "comm",
540
			_PyUnicode_FromString(thread__comm_str(al->thread)));
541 542
	if (al->map) {
		pydict_set_item_string_decref(dict, "dso",
543
			_PyUnicode_FromString(al->map->dso->name));
544 545 546
	}
	if (al->sym) {
		pydict_set_item_string_decref(dict, "symbol",
547
			_PyUnicode_FromString(al->sym->name));
548 549 550 551 552 553 554
	}

	pydict_set_item_string_decref(dict, "callchain", callchain);

	return dict;
}

555 556 557
static void python_process_tracepoint(struct perf_sample *sample,
				      struct perf_evsel *evsel,
				      struct addr_location *al)
558
{
559
	struct event_format *event = evsel->tp_format;
560
	PyObject *handler, *context, *t, *obj = NULL, *callchain;
561
	PyObject *dict = NULL, *all_entries_dict = NULL;
562 563 564 565 566
	static char handler_name[256];
	struct format_field *field;
	unsigned long s, ns;
	unsigned n = 0;
	int pid;
567 568 569
	int cpu = sample->cpu;
	void *data = sample->raw_data;
	unsigned long long nsecs = sample->time;
570
	const char *comm = thread__comm_str(al->thread);
571
	const char *default_handler_name = "trace_unhandled";
572

573 574 575 576 577
	if (!event) {
		snprintf(handler_name, sizeof(handler_name),
			 "ug! no event found for type %" PRIu64, (u64)evsel->attr.config);
		Py_FatalError(handler_name);
	}
578

579
	pid = raw_field_value(event, "common_pid", data);
580 581 582

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

583 584 585
	if (!test_and_set_bit(event->id, events_defined))
		define_event_symbols(event, handler_name, event->print_fmt.args);

586
	handler = get_handler(handler_name);
587
	if (!handler) {
588 589 590
		handler = get_handler(default_handler_name);
		if (!handler)
			return;
591 592 593 594
		dict = PyDict_New();
		if (!dict)
			Py_FatalError("couldn't create Python dict");
	}
595 596 597 598 599 600

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


601 602
	s = nsecs / NSEC_PER_SEC;
	ns = nsecs - s * NSEC_PER_SEC;
603 604

	scripting_context->event_data = data;
605
	scripting_context->pevent = evsel->tp_format->pevent;
606

607
	context = _PyCapsule_New(scripting_context, NULL, NULL);
608

609
	PyTuple_SetItem(t, n++, _PyUnicode_FromString(handler_name));
K
Kyle McMartin 已提交
610
	PyTuple_SetItem(t, n++, context);
611

612 613
	/* ip unwinding */
	callchain = python_process_callchain(sample, evsel, al);
614 615
	/* Need an additional reference for the perf_sample dict */
	Py_INCREF(callchain);
616

617
	if (!dict) {
618 619 620 621 622
		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));
623
		PyTuple_SetItem(t, n++, callchain);
624
	} else {
625 626 627 628 629
		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));
630
		pydict_set_item_string_decref(dict, "common_callchain", callchain);
631
	}
632
	for (field = event->format.fields; field; field = field->next) {
633 634 635 636 637 638
		unsigned int offset, len;
		unsigned long long val;

		if (field->flags & FIELD_IS_ARRAY) {
			offset = field->offset;
			len    = field->size;
639
			if (field->flags & FIELD_IS_DYNAMIC) {
640 641 642 643
				val     = pevent_read_number(scripting_context->pevent,
							     data + offset, len);
				offset  = val;
				len     = offset >> 16;
644
				offset &= 0xffff;
645 646 647
			}
			if (field->flags & FIELD_IS_STRING &&
			    is_printable_array(data + offset, len)) {
648
				obj = _PyUnicode_FromString((char *) data + offset);
649 650 651 652
			} else {
				obj = PyByteArray_FromStringAndSize((const char *) data + offset, len);
				field->flags &= ~FIELD_IS_STRING;
			}
653
		} else { /* FIELD_IS_NUMERIC */
654
			obj = get_field_numeric_entry(event, field, data);
655
		}
656
		if (!dict)
657 658
			PyTuple_SetItem(t, n++, obj);
		else
659
			pydict_set_item_string_decref(dict, field->name, obj);
660

661
	}
662

663
	if (dict)
664
		PyTuple_SetItem(t, n++, dict);
665

666 667 668 669 670 671 672 673
	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);
	}

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

677
	if (!dict) {
678
		call_object(handler, t, handler_name);
679
	} else {
680
		call_object(handler, t, default_handler_name);
681
		Py_DECREF(dict);
682 683
	}

684
	Py_XDECREF(all_entries_dict);
685 686 687
	Py_DECREF(t);
}

688 689 690 691 692 693 694 695 696 697 698 699 700
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
701
	return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
702 703 704 705 706 707 708 709
#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)
{
710
	return PyTuple_SetItem(t, pos, _PyLong_FromLong(val));
711 712 713 714
}

static int tuple_set_string(PyObject *t, unsigned int pos, const char *s)
{
715
	return PyTuple_SetItem(t, pos, _PyUnicode_FromString(s));
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
}

static int python_export_evsel(struct db_export *dbe, struct perf_evsel *evsel)
{
	struct tables *tables = container_of(dbe, struct tables, dbe);
	PyObject *t;

	t = tuple_new(2);

	tuple_set_u64(t, 0, evsel->db_id);
	tuple_set_string(t, 1, perf_evsel__name(evsel));

	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;
}

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

	t = tuple_new(2);

	tuple_set_u64(t, 0, comm->db_id);
	tuple_set_string(t, 1, comm__str(comm));

	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);
815
	char sbuild_id[SBUILD_ID_SIZE];
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
	PyObject *t;

	build_id__sprintf(dso->build_id, sizeof(dso->build_id), sbuild_id);

	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;
}

858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
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;
}

876 877 878 879 880 881
static int python_export_sample(struct db_export *dbe,
				struct export_sample *es)
{
	struct tables *tables = container_of(dbe, struct tables, dbe);
	PyObject *t;

882
	t = tuple_new(22);
883 884 885 886

	tuple_set_u64(t, 0, es->db_id);
	tuple_set_u64(t, 1, es->evsel->db_id);
	tuple_set_u64(t, 2, es->al->machine->db_id);
887
	tuple_set_u64(t, 3, es->al->thread->db_id);
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
	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);
903 904
	tuple_set_s32(t, 19, es->sample->flags & PERF_BRANCH_MASK);
	tuple_set_s32(t, 20, !!(es->sample->flags & PERF_IP_FLAG_IN_TX));
905
	tuple_set_u64(t, 21, es->call_path_id);
906 907 908 909 910 911 912 913

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

	Py_DECREF(t);

	return 0;
}

914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
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;

	t = tuple_new(11);

	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);

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

	Py_DECREF(t);

	return 0;
}

static int python_process_call_return(struct call_return *cr, void *data)
{
	struct db_export *dbe = data;

	return db_export__call_return(dbe, cr);
}

972
static void python_process_general_event(struct perf_sample *sample,
973
					 struct perf_evsel *evsel,
974
					 struct addr_location *al)
975
{
976
	PyObject *handler, *t, *dict, *callchain;
977 978 979
	static char handler_name[64];
	unsigned n = 0;

980 981 982 983 984 985
	snprintf(handler_name, sizeof(handler_name), "%s", "process_event");

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

986 987
	/*
	 * Use the MAX_FIELDS to make the function expandable, though
988
	 * currently there is only one item for the tuple.
989
	 */
990 991 992 993
	t = PyTuple_New(MAX_FIELDS);
	if (!t)
		Py_FatalError("couldn't create Python tuple");

994 995
	/* ip unwinding */
	callchain = python_process_callchain(sample, evsel, al);
996
	dict = get_perf_sample_dict(sample, evsel, al, callchain);
997

998
	PyTuple_SetItem(t, n++, dict);
999 1000 1001
	if (_PyTuple_Resize(&t, n) == -1)
		Py_FatalError("error resizing Python tuple");

1002
	call_object(handler, t, handler_name);
1003

1004
	Py_DECREF(dict);
1005 1006 1007
	Py_DECREF(t);
}

1008
static void python_process_event(union perf_event *event,
1009 1010
				 struct perf_sample *sample,
				 struct perf_evsel *evsel,
1011
				 struct addr_location *al)
1012
{
1013 1014
	struct tables *tables = &tables_global;

1015 1016
	switch (evsel->attr.type) {
	case PERF_TYPE_TRACEPOINT:
1017
		python_process_tracepoint(sample, evsel, al);
1018 1019 1020
		break;
	/* Reserve for future process_hw/sw/raw APIs */
	default:
1021
		if (tables->db_export_mode)
1022
			db_export__sample(&tables->dbe, event, sample, evsel, al);
1023
		else
1024
			python_process_general_event(sample, evsel, al);
1025 1026 1027
	}
}

1028 1029 1030 1031 1032 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
static void get_handler_name(char *str, size_t size,
			     struct perf_evsel *evsel)
{
	char *p = str;

	scnprintf(str, size, "stat__%s", perf_evsel__name(evsel));

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

static void
process_stat(struct perf_evsel *counter, int cpu, int thread, u64 tstamp,
	     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;
	}

1062 1063
	PyTuple_SetItem(t, n++, _PyLong_FromLong(cpu));
	PyTuple_SetItem(t, n++, _PyLong_FromLong(thread));
1064 1065 1066 1067 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 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125

	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,
				struct perf_evsel *counter, u64 tstamp)
{
	struct thread_map *threads = counter->threads;
	struct cpu_map *cpus = counter->cpus;
	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],
				     thread_map__pid(threads, thread), tstamp,
				     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);
}

1126 1127 1128 1129 1130 1131 1132 1133
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);
1134
	if (main_dict == NULL)
1135 1136 1137
		goto error;
	Py_INCREF(main_dict);

1138
	try_call_object("trace_begin", NULL);
1139

1140
	return 0;
1141 1142 1143 1144

error:
	Py_XDECREF(main_dict);
	Py_XDECREF(main_module);
1145
	return -1;
1146 1147
}

1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
#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";
1160
	const char *perf_db_export_calls = "perf_db_export_calls";
1161 1162
	const char *perf_db_export_callchains = "perf_db_export_callchains";
	PyObject *db_export_mode, *db_export_calls, *db_export_callchains;
1163
	bool export_calls = false;
1164
	bool export_callchains = false;
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
	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;

1181
	/* handle export calls */
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
	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");
	}

1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
	/* 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
		 * duplicate call path ids when both are in use simultaniously.
		 */
		if (tables->dbe.crp)
			tables->dbe.cpr = tables->dbe.crp->cpr;
		else
			tables->dbe.cpr = call_path_root__new();

		if (!tables->dbe.cpr)
1223
			Py_FatalError("failed to create call path root");
1224 1225
	}

1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
	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);
1239
	SET_TABLE_HANDLER(branch_type);
1240
	SET_TABLE_HANDLER(sample);
1241 1242
	SET_TABLE_HANDLER(call_path);
	SET_TABLE_HANDLER(call_return);
1243 1244
}

1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
#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


1261 1262 1263 1264 1265
/*
 * Start trace script
 */
static int python_start_script(const char *script, int argc, const char **argv)
{
1266
	struct tables *tables = &tables_global;
1267
#if PY_MAJOR_VERSION < 3
1268
	const char **command_line;
1269 1270 1271
#else
	wchar_t **command_line;
#endif
1272 1273 1274 1275
	char buf[PATH_MAX];
	int i, err = 0;
	FILE *fp;

1276
#if PY_MAJOR_VERSION < 3
1277 1278 1279 1280
	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];
1281 1282 1283 1284 1285 1286
#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);
#endif
1287 1288 1289

	Py_Initialize();

1290
#if PY_MAJOR_VERSION < 3
1291 1292
	initperf_trace_context();
	PySys_SetArgv(argc + 1, (char **)command_line);
1293 1294 1295 1296
#else
	PyInit_perf_trace_context();
	PySys_SetArgv(argc + 1, command_line);
#endif
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317

	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;
	}

1318 1319
	set_table_handlers(tables);

1320 1321 1322 1323 1324 1325
	if (tables->db_export_mode) {
		err = db_export__branch_types(&tables->dbe);
		if (err)
			goto error;
	}

1326
	_free_command_line(command_line, argc + 1);
1327

1328 1329 1330
	return err;
error:
	Py_Finalize();
1331
	_free_command_line(command_line, argc + 1);
1332 1333 1334 1335

	return err;
}

1336 1337
static int python_flush_script(void)
{
1338 1339 1340
	struct tables *tables = &tables_global;

	return db_export__flush(&tables->dbe);
1341 1342
}

1343 1344 1345 1346 1347
/*
 * Stop trace script
 */
static int python_stop_script(void)
{
1348 1349
	struct tables *tables = &tables_global;

1350
	try_call_object("trace_end", NULL);
1351

1352 1353
	db_export__exit(&tables->dbe);

1354 1355 1356 1357
	Py_XDECREF(main_dict);
	Py_XDECREF(main_module);
	Py_Finalize();

1358
	return 0;
1359 1360
}

1361
static int python_generate_script(struct pevent *pevent, const char *outfile)
1362
{
1363
	struct event_format *event = NULL;
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
	struct format_field *f;
	char fname[PATH_MAX];
	int not_first, count;
	FILE *ofp;

	sprintf(fname, "%s.py", outfile);
	ofp = fopen(fname, "w");
	if (ofp == NULL) {
		fprintf(stderr, "couldn't open %s\n", fname);
		return -1;
	}
1375 1376
	fprintf(ofp, "# perf script event handlers, "
		"generated by perf script -g python\n");
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392

	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");

1393
	fprintf(ofp, "# See the perf-script-python Documentation for the list "
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
		"of available functions.\n\n");

	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");
	fprintf(ofp, "\tprint \"in trace_begin\"\n\n");

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

1410
	while ((event = trace_find_next_event(pevent, event))) {
1411 1412 1413 1414 1415 1416 1417 1418
		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");
1419
		fprintf(ofp, "common_callchain, ");
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431

		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);
		}
1432 1433 1434 1435 1436 1437
		if (not_first++)
			fprintf(ofp, ", ");
		if (++count % 5 == 0)
			fprintf(ofp, "\n\t\t");
		fprintf(ofp, "perf_sample_dict");

1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
		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");

		fprintf(ofp, "\t\tprint \"");

		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);
			if (f->flags & FIELD_IS_STRING ||
			    f->flags & FIELD_IS_FLAG ||
1460
			    f->flags & FIELD_IS_ARRAY ||
1461 1462 1463 1464 1465 1466 1467 1468
			    f->flags & FIELD_IS_SYMBOLIC)
				fprintf(ofp, "%%s");
			else if (f->flags & FIELD_IS_SIGNED)
				fprintf(ofp, "%%d");
			else
				fprintf(ofp, "%%u");
		}

1469
		fprintf(ofp, "\" %% \\\n\t\t(");
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504

		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");

			if (f->flags & FIELD_IS_FLAG) {
				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);
			} else if (f->flags & FIELD_IS_SYMBOLIC) {
				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);
		}

1505 1506
		fprintf(ofp, ")\n\n");

1507 1508 1509
		fprintf(ofp, "\t\tprint 'Sample: {'+"
			"get_dict_as_string(perf_sample_dict['sample'], ', ')+'}'\n\n");

1510 1511 1512 1513 1514 1515 1516
		fprintf(ofp, "\t\tfor node in common_callchain:");
		fprintf(ofp, "\n\t\t\tif 'sym' in node:");
		fprintf(ofp, "\n\t\t\t\tprint \"\\t[%%x] %%s\" %% (node['ip'], node['sym']['name'])");
		fprintf(ofp, "\n\t\t\telse:");
		fprintf(ofp, "\n\t\t\t\tprint \"\t[%%x]\" %% (node['ip'])\n\n");
		fprintf(ofp, "\t\tprint \"\\n\"\n\n");

1517 1518 1519
	}

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

1522 1523 1524
	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");
1525 1526 1527 1528

	fprintf(ofp, "def print_header("
		"event_name, cpu, secs, nsecs, pid, comm):\n"
		"\tprint \"%%-20s %%5u %%05u.%%09u %%8u %%-20s \" %% \\\n\t"
1529 1530 1531 1532 1533
		"(event_name, cpu, secs, nsecs, pid, comm),\n\n");

	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");
1534 1535 1536 1537 1538 1539 1540 1541 1542

	fclose(ofp);

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

	return 0;
}

struct scripting_ops python_scripting_ops = {
1543 1544 1545 1546 1547 1548 1549 1550
	.name			= "Python",
	.start_script		= python_start_script,
	.flush_script		= python_flush_script,
	.stop_script		= python_stop_script,
	.process_event		= python_process_event,
	.process_stat		= python_process_stat,
	.process_stat_interval	= python_process_stat_interval,
	.generate_script	= python_generate_script,
1551
};