xref: /openbmc/linux/tools/perf/builtin-script.c (revision 711aab1d)
1 #include "builtin.h"
2 
3 #include "perf.h"
4 #include "util/cache.h"
5 #include "util/debug.h"
6 #include <subcmd/exec-cmd.h>
7 #include "util/header.h"
8 #include <subcmd/parse-options.h>
9 #include "util/perf_regs.h"
10 #include "util/session.h"
11 #include "util/tool.h"
12 #include "util/symbol.h"
13 #include "util/thread.h"
14 #include "util/trace-event.h"
15 #include "util/util.h"
16 #include "util/evlist.h"
17 #include "util/evsel.h"
18 #include "util/sort.h"
19 #include "util/data.h"
20 #include "util/auxtrace.h"
21 #include "util/cpumap.h"
22 #include "util/thread_map.h"
23 #include "util/stat.h"
24 #include "util/string2.h"
25 #include "util/thread-stack.h"
26 #include "util/time-utils.h"
27 #include "print_binary.h"
28 #include <linux/bitmap.h>
29 #include <linux/kernel.h>
30 #include <linux/stringify.h>
31 #include <linux/time64.h>
32 #include "asm/bug.h"
33 #include "util/mem-events.h"
34 #include "util/dump-insn.h"
35 #include <dirent.h>
36 #include <errno.h>
37 #include <inttypes.h>
38 #include <signal.h>
39 #include <sys/param.h>
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #include <unistd.h>
43 
44 #include "sane_ctype.h"
45 
46 static char const		*script_name;
47 static char const		*generate_script_lang;
48 static bool			debug_mode;
49 static u64			last_timestamp;
50 static u64			nr_unordered;
51 static bool			no_callchain;
52 static bool			latency_format;
53 static bool			system_wide;
54 static bool			print_flags;
55 static bool			nanosecs;
56 static const char		*cpu_list;
57 static DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
58 static struct perf_stat_config	stat_config;
59 static int			max_blocks;
60 
61 unsigned int scripting_max_stack = PERF_MAX_STACK_DEPTH;
62 
63 enum perf_output_field {
64 	PERF_OUTPUT_COMM            = 1U << 0,
65 	PERF_OUTPUT_TID             = 1U << 1,
66 	PERF_OUTPUT_PID             = 1U << 2,
67 	PERF_OUTPUT_TIME            = 1U << 3,
68 	PERF_OUTPUT_CPU             = 1U << 4,
69 	PERF_OUTPUT_EVNAME          = 1U << 5,
70 	PERF_OUTPUT_TRACE           = 1U << 6,
71 	PERF_OUTPUT_IP              = 1U << 7,
72 	PERF_OUTPUT_SYM             = 1U << 8,
73 	PERF_OUTPUT_DSO             = 1U << 9,
74 	PERF_OUTPUT_ADDR            = 1U << 10,
75 	PERF_OUTPUT_SYMOFFSET       = 1U << 11,
76 	PERF_OUTPUT_SRCLINE         = 1U << 12,
77 	PERF_OUTPUT_PERIOD          = 1U << 13,
78 	PERF_OUTPUT_IREGS	    = 1U << 14,
79 	PERF_OUTPUT_BRSTACK	    = 1U << 15,
80 	PERF_OUTPUT_BRSTACKSYM	    = 1U << 16,
81 	PERF_OUTPUT_DATA_SRC	    = 1U << 17,
82 	PERF_OUTPUT_WEIGHT	    = 1U << 18,
83 	PERF_OUTPUT_BPF_OUTPUT	    = 1U << 19,
84 	PERF_OUTPUT_CALLINDENT	    = 1U << 20,
85 	PERF_OUTPUT_INSN	    = 1U << 21,
86 	PERF_OUTPUT_INSNLEN	    = 1U << 22,
87 	PERF_OUTPUT_BRSTACKINSN	    = 1U << 23,
88 	PERF_OUTPUT_BRSTACKOFF	    = 1U << 24,
89 	PERF_OUTPUT_SYNTH           = 1U << 25,
90 	PERF_OUTPUT_PHYS_ADDR       = 1U << 26,
91 };
92 
93 struct output_option {
94 	const char *str;
95 	enum perf_output_field field;
96 } all_output_options[] = {
97 	{.str = "comm",  .field = PERF_OUTPUT_COMM},
98 	{.str = "tid",   .field = PERF_OUTPUT_TID},
99 	{.str = "pid",   .field = PERF_OUTPUT_PID},
100 	{.str = "time",  .field = PERF_OUTPUT_TIME},
101 	{.str = "cpu",   .field = PERF_OUTPUT_CPU},
102 	{.str = "event", .field = PERF_OUTPUT_EVNAME},
103 	{.str = "trace", .field = PERF_OUTPUT_TRACE},
104 	{.str = "ip",    .field = PERF_OUTPUT_IP},
105 	{.str = "sym",   .field = PERF_OUTPUT_SYM},
106 	{.str = "dso",   .field = PERF_OUTPUT_DSO},
107 	{.str = "addr",  .field = PERF_OUTPUT_ADDR},
108 	{.str = "symoff", .field = PERF_OUTPUT_SYMOFFSET},
109 	{.str = "srcline", .field = PERF_OUTPUT_SRCLINE},
110 	{.str = "period", .field = PERF_OUTPUT_PERIOD},
111 	{.str = "iregs", .field = PERF_OUTPUT_IREGS},
112 	{.str = "brstack", .field = PERF_OUTPUT_BRSTACK},
113 	{.str = "brstacksym", .field = PERF_OUTPUT_BRSTACKSYM},
114 	{.str = "data_src", .field = PERF_OUTPUT_DATA_SRC},
115 	{.str = "weight",   .field = PERF_OUTPUT_WEIGHT},
116 	{.str = "bpf-output",   .field = PERF_OUTPUT_BPF_OUTPUT},
117 	{.str = "callindent", .field = PERF_OUTPUT_CALLINDENT},
118 	{.str = "insn", .field = PERF_OUTPUT_INSN},
119 	{.str = "insnlen", .field = PERF_OUTPUT_INSNLEN},
120 	{.str = "brstackinsn", .field = PERF_OUTPUT_BRSTACKINSN},
121 	{.str = "brstackoff", .field = PERF_OUTPUT_BRSTACKOFF},
122 	{.str = "synth", .field = PERF_OUTPUT_SYNTH},
123 	{.str = "phys_addr", .field = PERF_OUTPUT_PHYS_ADDR},
124 };
125 
126 enum {
127 	OUTPUT_TYPE_SYNTH = PERF_TYPE_MAX,
128 	OUTPUT_TYPE_MAX
129 };
130 
131 /* default set to maintain compatibility with current format */
132 static struct {
133 	bool user_set;
134 	bool wildcard_set;
135 	unsigned int print_ip_opts;
136 	u64 fields;
137 	u64 invalid_fields;
138 } output[OUTPUT_TYPE_MAX] = {
139 
140 	[PERF_TYPE_HARDWARE] = {
141 		.user_set = false,
142 
143 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
144 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
145 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
146 			      PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
147 			      PERF_OUTPUT_PERIOD,
148 
149 		.invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
150 	},
151 
152 	[PERF_TYPE_SOFTWARE] = {
153 		.user_set = false,
154 
155 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
156 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
157 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
158 			      PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
159 			      PERF_OUTPUT_PERIOD | PERF_OUTPUT_BPF_OUTPUT,
160 
161 		.invalid_fields = PERF_OUTPUT_TRACE,
162 	},
163 
164 	[PERF_TYPE_TRACEPOINT] = {
165 		.user_set = false,
166 
167 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
168 				  PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
169 				  PERF_OUTPUT_EVNAME | PERF_OUTPUT_TRACE
170 	},
171 
172 	[PERF_TYPE_RAW] = {
173 		.user_set = false,
174 
175 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
176 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
177 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
178 			      PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
179 			      PERF_OUTPUT_PERIOD |  PERF_OUTPUT_ADDR |
180 			      PERF_OUTPUT_DATA_SRC | PERF_OUTPUT_WEIGHT |
181 			      PERF_OUTPUT_PHYS_ADDR,
182 
183 		.invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
184 	},
185 
186 	[PERF_TYPE_BREAKPOINT] = {
187 		.user_set = false,
188 
189 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
190 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
191 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
192 			      PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
193 			      PERF_OUTPUT_PERIOD,
194 
195 		.invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
196 	},
197 
198 	[OUTPUT_TYPE_SYNTH] = {
199 		.user_set = false,
200 
201 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
202 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
203 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
204 			      PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
205 			      PERF_OUTPUT_SYNTH,
206 
207 		.invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
208 	},
209 };
210 
211 static inline int output_type(unsigned int type)
212 {
213 	switch (type) {
214 	case PERF_TYPE_SYNTH:
215 		return OUTPUT_TYPE_SYNTH;
216 	default:
217 		return type;
218 	}
219 }
220 
221 static inline unsigned int attr_type(unsigned int type)
222 {
223 	switch (type) {
224 	case OUTPUT_TYPE_SYNTH:
225 		return PERF_TYPE_SYNTH;
226 	default:
227 		return type;
228 	}
229 }
230 
231 static bool output_set_by_user(void)
232 {
233 	int j;
234 	for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
235 		if (output[j].user_set)
236 			return true;
237 	}
238 	return false;
239 }
240 
241 static const char *output_field2str(enum perf_output_field field)
242 {
243 	int i, imax = ARRAY_SIZE(all_output_options);
244 	const char *str = "";
245 
246 	for (i = 0; i < imax; ++i) {
247 		if (all_output_options[i].field == field) {
248 			str = all_output_options[i].str;
249 			break;
250 		}
251 	}
252 	return str;
253 }
254 
255 #define PRINT_FIELD(x)  (output[output_type(attr->type)].fields & PERF_OUTPUT_##x)
256 
257 static int perf_evsel__do_check_stype(struct perf_evsel *evsel,
258 				      u64 sample_type, const char *sample_msg,
259 				      enum perf_output_field field,
260 				      bool allow_user_set)
261 {
262 	struct perf_event_attr *attr = &evsel->attr;
263 	int type = output_type(attr->type);
264 	const char *evname;
265 
266 	if (attr->sample_type & sample_type)
267 		return 0;
268 
269 	if (output[type].user_set) {
270 		if (allow_user_set)
271 			return 0;
272 		evname = perf_evsel__name(evsel);
273 		pr_err("Samples for '%s' event do not have %s attribute set. "
274 		       "Cannot print '%s' field.\n",
275 		       evname, sample_msg, output_field2str(field));
276 		return -1;
277 	}
278 
279 	/* user did not ask for it explicitly so remove from the default list */
280 	output[type].fields &= ~field;
281 	evname = perf_evsel__name(evsel);
282 	pr_debug("Samples for '%s' event do not have %s attribute set. "
283 		 "Skipping '%s' field.\n",
284 		 evname, sample_msg, output_field2str(field));
285 
286 	return 0;
287 }
288 
289 static int perf_evsel__check_stype(struct perf_evsel *evsel,
290 				   u64 sample_type, const char *sample_msg,
291 				   enum perf_output_field field)
292 {
293 	return perf_evsel__do_check_stype(evsel, sample_type, sample_msg, field,
294 					  false);
295 }
296 
297 static int perf_evsel__check_attr(struct perf_evsel *evsel,
298 				  struct perf_session *session)
299 {
300 	struct perf_event_attr *attr = &evsel->attr;
301 	bool allow_user_set;
302 
303 	if (perf_header__has_feat(&session->header, HEADER_STAT))
304 		return 0;
305 
306 	allow_user_set = perf_header__has_feat(&session->header,
307 					       HEADER_AUXTRACE);
308 
309 	if (PRINT_FIELD(TRACE) &&
310 		!perf_session__has_traces(session, "record -R"))
311 		return -EINVAL;
312 
313 	if (PRINT_FIELD(IP)) {
314 		if (perf_evsel__check_stype(evsel, PERF_SAMPLE_IP, "IP",
315 					    PERF_OUTPUT_IP))
316 			return -EINVAL;
317 	}
318 
319 	if (PRINT_FIELD(ADDR) &&
320 		perf_evsel__do_check_stype(evsel, PERF_SAMPLE_ADDR, "ADDR",
321 					   PERF_OUTPUT_ADDR, allow_user_set))
322 		return -EINVAL;
323 
324 	if (PRINT_FIELD(DATA_SRC) &&
325 		perf_evsel__check_stype(evsel, PERF_SAMPLE_DATA_SRC, "DATA_SRC",
326 					PERF_OUTPUT_DATA_SRC))
327 		return -EINVAL;
328 
329 	if (PRINT_FIELD(WEIGHT) &&
330 		perf_evsel__check_stype(evsel, PERF_SAMPLE_WEIGHT, "WEIGHT",
331 					PERF_OUTPUT_WEIGHT))
332 		return -EINVAL;
333 
334 	if (PRINT_FIELD(SYM) && !PRINT_FIELD(IP) && !PRINT_FIELD(ADDR)) {
335 		pr_err("Display of symbols requested but neither sample IP nor "
336 			   "sample address\nis selected. Hence, no addresses to convert "
337 		       "to symbols.\n");
338 		return -EINVAL;
339 	}
340 	if (PRINT_FIELD(SYMOFFSET) && !PRINT_FIELD(SYM)) {
341 		pr_err("Display of offsets requested but symbol is not"
342 		       "selected.\n");
343 		return -EINVAL;
344 	}
345 	if (PRINT_FIELD(DSO) && !PRINT_FIELD(IP) && !PRINT_FIELD(ADDR) &&
346 	    !PRINT_FIELD(BRSTACK) && !PRINT_FIELD(BRSTACKSYM) && !PRINT_FIELD(BRSTACKOFF)) {
347 		pr_err("Display of DSO requested but no address to convert.  Select\n"
348 		       "sample IP, sample address, brstack, brstacksym, or brstackoff.\n");
349 		return -EINVAL;
350 	}
351 	if (PRINT_FIELD(SRCLINE) && !PRINT_FIELD(IP)) {
352 		pr_err("Display of source line number requested but sample IP is not\n"
353 		       "selected. Hence, no address to lookup the source line number.\n");
354 		return -EINVAL;
355 	}
356 	if (PRINT_FIELD(BRSTACKINSN) &&
357 	    !(perf_evlist__combined_branch_type(session->evlist) &
358 	      PERF_SAMPLE_BRANCH_ANY)) {
359 		pr_err("Display of branch stack assembler requested, but non all-branch filter set\n"
360 		       "Hint: run 'perf record -b ...'\n");
361 		return -EINVAL;
362 	}
363 	if ((PRINT_FIELD(PID) || PRINT_FIELD(TID)) &&
364 		perf_evsel__check_stype(evsel, PERF_SAMPLE_TID, "TID",
365 					PERF_OUTPUT_TID|PERF_OUTPUT_PID))
366 		return -EINVAL;
367 
368 	if (PRINT_FIELD(TIME) &&
369 		perf_evsel__check_stype(evsel, PERF_SAMPLE_TIME, "TIME",
370 					PERF_OUTPUT_TIME))
371 		return -EINVAL;
372 
373 	if (PRINT_FIELD(CPU) &&
374 		perf_evsel__do_check_stype(evsel, PERF_SAMPLE_CPU, "CPU",
375 					   PERF_OUTPUT_CPU, allow_user_set))
376 		return -EINVAL;
377 
378 	if (PRINT_FIELD(PERIOD) &&
379 		perf_evsel__check_stype(evsel, PERF_SAMPLE_PERIOD, "PERIOD",
380 					PERF_OUTPUT_PERIOD))
381 		return -EINVAL;
382 
383 	if (PRINT_FIELD(IREGS) &&
384 		perf_evsel__check_stype(evsel, PERF_SAMPLE_REGS_INTR, "IREGS",
385 					PERF_OUTPUT_IREGS))
386 		return -EINVAL;
387 
388 	if (PRINT_FIELD(PHYS_ADDR) &&
389 		perf_evsel__check_stype(evsel, PERF_SAMPLE_PHYS_ADDR, "PHYS_ADDR",
390 					PERF_OUTPUT_PHYS_ADDR))
391 		return -EINVAL;
392 
393 	return 0;
394 }
395 
396 static void set_print_ip_opts(struct perf_event_attr *attr)
397 {
398 	unsigned int type = output_type(attr->type);
399 
400 	output[type].print_ip_opts = 0;
401 	if (PRINT_FIELD(IP))
402 		output[type].print_ip_opts |= EVSEL__PRINT_IP;
403 
404 	if (PRINT_FIELD(SYM))
405 		output[type].print_ip_opts |= EVSEL__PRINT_SYM;
406 
407 	if (PRINT_FIELD(DSO))
408 		output[type].print_ip_opts |= EVSEL__PRINT_DSO;
409 
410 	if (PRINT_FIELD(SYMOFFSET))
411 		output[type].print_ip_opts |= EVSEL__PRINT_SYMOFFSET;
412 
413 	if (PRINT_FIELD(SRCLINE))
414 		output[type].print_ip_opts |= EVSEL__PRINT_SRCLINE;
415 }
416 
417 /*
418  * verify all user requested events exist and the samples
419  * have the expected data
420  */
421 static int perf_session__check_output_opt(struct perf_session *session)
422 {
423 	unsigned int j;
424 	struct perf_evsel *evsel;
425 
426 	for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
427 		evsel = perf_session__find_first_evtype(session, attr_type(j));
428 
429 		/*
430 		 * even if fields is set to 0 (ie., show nothing) event must
431 		 * exist if user explicitly includes it on the command line
432 		 */
433 		if (!evsel && output[j].user_set && !output[j].wildcard_set &&
434 		    j != OUTPUT_TYPE_SYNTH) {
435 			pr_err("%s events do not exist. "
436 			       "Remove corresponding -F option to proceed.\n",
437 			       event_type(j));
438 			return -1;
439 		}
440 
441 		if (evsel && output[j].fields &&
442 			perf_evsel__check_attr(evsel, session))
443 			return -1;
444 
445 		if (evsel == NULL)
446 			continue;
447 
448 		set_print_ip_opts(&evsel->attr);
449 	}
450 
451 	if (!no_callchain) {
452 		bool use_callchain = false;
453 		bool not_pipe = false;
454 
455 		evlist__for_each_entry(session->evlist, evsel) {
456 			not_pipe = true;
457 			if (evsel->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
458 				use_callchain = true;
459 				break;
460 			}
461 		}
462 		if (not_pipe && !use_callchain)
463 			symbol_conf.use_callchain = false;
464 	}
465 
466 	/*
467 	 * set default for tracepoints to print symbols only
468 	 * if callchains are present
469 	 */
470 	if (symbol_conf.use_callchain &&
471 	    !output[PERF_TYPE_TRACEPOINT].user_set) {
472 		struct perf_event_attr *attr;
473 
474 		j = PERF_TYPE_TRACEPOINT;
475 
476 		evlist__for_each_entry(session->evlist, evsel) {
477 			if (evsel->attr.type != j)
478 				continue;
479 
480 			attr = &evsel->attr;
481 
482 			if (attr->sample_type & PERF_SAMPLE_CALLCHAIN) {
483 				output[j].fields |= PERF_OUTPUT_IP;
484 				output[j].fields |= PERF_OUTPUT_SYM;
485 				output[j].fields |= PERF_OUTPUT_DSO;
486 				set_print_ip_opts(attr);
487 				goto out;
488 			}
489 		}
490 	}
491 
492 out:
493 	return 0;
494 }
495 
496 static void print_sample_iregs(struct perf_sample *sample,
497 			  struct perf_event_attr *attr)
498 {
499 	struct regs_dump *regs = &sample->intr_regs;
500 	uint64_t mask = attr->sample_regs_intr;
501 	unsigned i = 0, r;
502 
503 	if (!regs)
504 		return;
505 
506 	for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
507 		u64 val = regs->regs[i++];
508 		printf("%5s:0x%"PRIx64" ", perf_reg_name(r), val);
509 	}
510 }
511 
512 static void print_sample_start(struct perf_sample *sample,
513 			       struct thread *thread,
514 			       struct perf_evsel *evsel)
515 {
516 	struct perf_event_attr *attr = &evsel->attr;
517 	unsigned long secs;
518 	unsigned long long nsecs;
519 
520 	if (PRINT_FIELD(COMM)) {
521 		if (latency_format)
522 			printf("%8.8s ", thread__comm_str(thread));
523 		else if (PRINT_FIELD(IP) && symbol_conf.use_callchain)
524 			printf("%s ", thread__comm_str(thread));
525 		else
526 			printf("%16s ", thread__comm_str(thread));
527 	}
528 
529 	if (PRINT_FIELD(PID) && PRINT_FIELD(TID))
530 		printf("%5d/%-5d ", sample->pid, sample->tid);
531 	else if (PRINT_FIELD(PID))
532 		printf("%5d ", sample->pid);
533 	else if (PRINT_FIELD(TID))
534 		printf("%5d ", sample->tid);
535 
536 	if (PRINT_FIELD(CPU)) {
537 		if (latency_format)
538 			printf("%3d ", sample->cpu);
539 		else
540 			printf("[%03d] ", sample->cpu);
541 	}
542 
543 	if (PRINT_FIELD(TIME)) {
544 		nsecs = sample->time;
545 		secs = nsecs / NSEC_PER_SEC;
546 		nsecs -= secs * NSEC_PER_SEC;
547 
548 		if (nanosecs)
549 			printf("%5lu.%09llu: ", secs, nsecs);
550 		else {
551 			char sample_time[32];
552 			timestamp__scnprintf_usec(sample->time, sample_time, sizeof(sample_time));
553 			printf("%12s: ", sample_time);
554 		}
555 	}
556 }
557 
558 static inline char
559 mispred_str(struct branch_entry *br)
560 {
561 	if (!(br->flags.mispred  || br->flags.predicted))
562 		return '-';
563 
564 	return br->flags.predicted ? 'P' : 'M';
565 }
566 
567 static void print_sample_brstack(struct perf_sample *sample,
568 				 struct thread *thread,
569 				 struct perf_event_attr *attr)
570 {
571 	struct branch_stack *br = sample->branch_stack;
572 	struct addr_location alf, alt;
573 	u64 i, from, to;
574 
575 	if (!(br && br->nr))
576 		return;
577 
578 	for (i = 0; i < br->nr; i++) {
579 		from = br->entries[i].from;
580 		to   = br->entries[i].to;
581 
582 		if (PRINT_FIELD(DSO)) {
583 			memset(&alf, 0, sizeof(alf));
584 			memset(&alt, 0, sizeof(alt));
585 			thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, from, &alf);
586 			thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, to, &alt);
587 		}
588 
589 		printf("0x%"PRIx64, from);
590 		if (PRINT_FIELD(DSO)) {
591 			printf("(");
592 			map__fprintf_dsoname(alf.map, stdout);
593 			printf(")");
594 		}
595 
596 		printf("/0x%"PRIx64, to);
597 		if (PRINT_FIELD(DSO)) {
598 			printf("(");
599 			map__fprintf_dsoname(alt.map, stdout);
600 			printf(")");
601 		}
602 
603 		printf("/%c/%c/%c/%d ",
604 			mispred_str( br->entries + i),
605 			br->entries[i].flags.in_tx? 'X' : '-',
606 			br->entries[i].flags.abort? 'A' : '-',
607 			br->entries[i].flags.cycles);
608 	}
609 }
610 
611 static void print_sample_brstacksym(struct perf_sample *sample,
612 				    struct thread *thread,
613 				    struct perf_event_attr *attr)
614 {
615 	struct branch_stack *br = sample->branch_stack;
616 	struct addr_location alf, alt;
617 	u64 i, from, to;
618 
619 	if (!(br && br->nr))
620 		return;
621 
622 	for (i = 0; i < br->nr; i++) {
623 
624 		memset(&alf, 0, sizeof(alf));
625 		memset(&alt, 0, sizeof(alt));
626 		from = br->entries[i].from;
627 		to   = br->entries[i].to;
628 
629 		thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, from, &alf);
630 		if (alf.map)
631 			alf.sym = map__find_symbol(alf.map, alf.addr);
632 
633 		thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, to, &alt);
634 		if (alt.map)
635 			alt.sym = map__find_symbol(alt.map, alt.addr);
636 
637 		symbol__fprintf_symname_offs(alf.sym, &alf, stdout);
638 		if (PRINT_FIELD(DSO)) {
639 			printf("(");
640 			map__fprintf_dsoname(alf.map, stdout);
641 			printf(")");
642 		}
643 		putchar('/');
644 		symbol__fprintf_symname_offs(alt.sym, &alt, stdout);
645 		if (PRINT_FIELD(DSO)) {
646 			printf("(");
647 			map__fprintf_dsoname(alt.map, stdout);
648 			printf(")");
649 		}
650 		printf("/%c/%c/%c/%d ",
651 			mispred_str( br->entries + i),
652 			br->entries[i].flags.in_tx? 'X' : '-',
653 			br->entries[i].flags.abort? 'A' : '-',
654 			br->entries[i].flags.cycles);
655 	}
656 }
657 
658 static void print_sample_brstackoff(struct perf_sample *sample,
659 				    struct thread *thread,
660 				    struct perf_event_attr *attr)
661 {
662 	struct branch_stack *br = sample->branch_stack;
663 	struct addr_location alf, alt;
664 	u64 i, from, to;
665 
666 	if (!(br && br->nr))
667 		return;
668 
669 	for (i = 0; i < br->nr; i++) {
670 
671 		memset(&alf, 0, sizeof(alf));
672 		memset(&alt, 0, sizeof(alt));
673 		from = br->entries[i].from;
674 		to   = br->entries[i].to;
675 
676 		thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, from, &alf);
677 		if (alf.map && !alf.map->dso->adjust_symbols)
678 			from = map__map_ip(alf.map, from);
679 
680 		thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, to, &alt);
681 		if (alt.map && !alt.map->dso->adjust_symbols)
682 			to = map__map_ip(alt.map, to);
683 
684 		printf("0x%"PRIx64, from);
685 		if (PRINT_FIELD(DSO)) {
686 			printf("(");
687 			map__fprintf_dsoname(alf.map, stdout);
688 			printf(")");
689 		}
690 		printf("/0x%"PRIx64, to);
691 		if (PRINT_FIELD(DSO)) {
692 			printf("(");
693 			map__fprintf_dsoname(alt.map, stdout);
694 			printf(")");
695 		}
696 		printf("/%c/%c/%c/%d ",
697 			mispred_str(br->entries + i),
698 			br->entries[i].flags.in_tx ? 'X' : '-',
699 			br->entries[i].flags.abort ? 'A' : '-',
700 			br->entries[i].flags.cycles);
701 	}
702 }
703 #define MAXBB 16384UL
704 
705 static int grab_bb(u8 *buffer, u64 start, u64 end,
706 		    struct machine *machine, struct thread *thread,
707 		    bool *is64bit, u8 *cpumode, bool last)
708 {
709 	long offset, len;
710 	struct addr_location al;
711 	bool kernel;
712 
713 	if (!start || !end)
714 		return 0;
715 
716 	kernel = machine__kernel_ip(machine, start);
717 	if (kernel)
718 		*cpumode = PERF_RECORD_MISC_KERNEL;
719 	else
720 		*cpumode = PERF_RECORD_MISC_USER;
721 
722 	/*
723 	 * Block overlaps between kernel and user.
724 	 * This can happen due to ring filtering
725 	 * On Intel CPUs the entry into the kernel is filtered,
726 	 * but the exit is not. Let the caller patch it up.
727 	 */
728 	if (kernel != machine__kernel_ip(machine, end)) {
729 		printf("\tblock %" PRIx64 "-%" PRIx64 " transfers between kernel and user\n",
730 				start, end);
731 		return -ENXIO;
732 	}
733 
734 	memset(&al, 0, sizeof(al));
735 	if (end - start > MAXBB - MAXINSN) {
736 		if (last)
737 			printf("\tbrstack does not reach to final jump (%" PRIx64 "-%" PRIx64 ")\n", start, end);
738 		else
739 			printf("\tblock %" PRIx64 "-%" PRIx64 " (%" PRIu64 ") too long to dump\n", start, end, end - start);
740 		return 0;
741 	}
742 
743 	thread__find_addr_map(thread, *cpumode, MAP__FUNCTION, start, &al);
744 	if (!al.map || !al.map->dso) {
745 		printf("\tcannot resolve %" PRIx64 "-%" PRIx64 "\n", start, end);
746 		return 0;
747 	}
748 	if (al.map->dso->data.status == DSO_DATA_STATUS_ERROR) {
749 		printf("\tcannot resolve %" PRIx64 "-%" PRIx64 "\n", start, end);
750 		return 0;
751 	}
752 
753 	/* Load maps to ensure dso->is_64_bit has been updated */
754 	map__load(al.map);
755 
756 	offset = al.map->map_ip(al.map, start);
757 	len = dso__data_read_offset(al.map->dso, machine, offset, (u8 *)buffer,
758 				    end - start + MAXINSN);
759 
760 	*is64bit = al.map->dso->is_64_bit;
761 	if (len <= 0)
762 		printf("\tcannot fetch code for block at %" PRIx64 "-%" PRIx64 "\n",
763 			start, end);
764 	return len;
765 }
766 
767 static void print_jump(uint64_t ip, struct branch_entry *en,
768 		       struct perf_insn *x, u8 *inbuf, int len,
769 		       int insn)
770 {
771 	printf("\t%016" PRIx64 "\t%-30s\t#%s%s%s%s",
772 	       ip,
773 	       dump_insn(x, ip, inbuf, len, NULL),
774 	       en->flags.predicted ? " PRED" : "",
775 	       en->flags.mispred ? " MISPRED" : "",
776 	       en->flags.in_tx ? " INTX" : "",
777 	       en->flags.abort ? " ABORT" : "");
778 	if (en->flags.cycles) {
779 		printf(" %d cycles", en->flags.cycles);
780 		if (insn)
781 			printf(" %.2f IPC", (float)insn / en->flags.cycles);
782 	}
783 	putchar('\n');
784 }
785 
786 static void print_ip_sym(struct thread *thread, u8 cpumode, int cpu,
787 			 uint64_t addr, struct symbol **lastsym,
788 			 struct perf_event_attr *attr)
789 {
790 	struct addr_location al;
791 	int off;
792 
793 	memset(&al, 0, sizeof(al));
794 
795 	thread__find_addr_map(thread, cpumode, MAP__FUNCTION, addr, &al);
796 	if (!al.map)
797 		thread__find_addr_map(thread, cpumode, MAP__VARIABLE,
798 				      addr, &al);
799 	if ((*lastsym) && al.addr >= (*lastsym)->start && al.addr < (*lastsym)->end)
800 		return;
801 
802 	al.cpu = cpu;
803 	al.sym = NULL;
804 	if (al.map)
805 		al.sym = map__find_symbol(al.map, al.addr);
806 
807 	if (!al.sym)
808 		return;
809 
810 	if (al.addr < al.sym->end)
811 		off = al.addr - al.sym->start;
812 	else
813 		off = al.addr - al.map->start - al.sym->start;
814 	printf("\t%s", al.sym->name);
815 	if (off)
816 		printf("%+d", off);
817 	putchar(':');
818 	if (PRINT_FIELD(SRCLINE))
819 		map__fprintf_srcline(al.map, al.addr, "\t", stdout);
820 	putchar('\n');
821 	*lastsym = al.sym;
822 }
823 
824 static void print_sample_brstackinsn(struct perf_sample *sample,
825 				     struct thread *thread,
826 				     struct perf_event_attr *attr,
827 				     struct machine *machine)
828 {
829 	struct branch_stack *br = sample->branch_stack;
830 	u64 start, end;
831 	int i, insn, len, nr, ilen;
832 	struct perf_insn x;
833 	u8 buffer[MAXBB];
834 	unsigned off;
835 	struct symbol *lastsym = NULL;
836 
837 	if (!(br && br->nr))
838 		return;
839 	nr = br->nr;
840 	if (max_blocks && nr > max_blocks + 1)
841 		nr = max_blocks + 1;
842 
843 	x.thread = thread;
844 	x.cpu = sample->cpu;
845 
846 	putchar('\n');
847 
848 	/* Handle first from jump, of which we don't know the entry. */
849 	len = grab_bb(buffer, br->entries[nr-1].from,
850 			br->entries[nr-1].from,
851 			machine, thread, &x.is64bit, &x.cpumode, false);
852 	if (len > 0) {
853 		print_ip_sym(thread, x.cpumode, x.cpu,
854 			     br->entries[nr - 1].from, &lastsym, attr);
855 		print_jump(br->entries[nr - 1].from, &br->entries[nr - 1],
856 			    &x, buffer, len, 0);
857 	}
858 
859 	/* Print all blocks */
860 	for (i = nr - 2; i >= 0; i--) {
861 		if (br->entries[i].from || br->entries[i].to)
862 			pr_debug("%d: %" PRIx64 "-%" PRIx64 "\n", i,
863 				 br->entries[i].from,
864 				 br->entries[i].to);
865 		start = br->entries[i + 1].to;
866 		end   = br->entries[i].from;
867 
868 		len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, false);
869 		/* Patch up missing kernel transfers due to ring filters */
870 		if (len == -ENXIO && i > 0) {
871 			end = br->entries[--i].from;
872 			pr_debug("\tpatching up to %" PRIx64 "-%" PRIx64 "\n", start, end);
873 			len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, false);
874 		}
875 		if (len <= 0)
876 			continue;
877 
878 		insn = 0;
879 		for (off = 0;; off += ilen) {
880 			uint64_t ip = start + off;
881 
882 			print_ip_sym(thread, x.cpumode, x.cpu, ip, &lastsym, attr);
883 			if (ip == end) {
884 				print_jump(ip, &br->entries[i], &x, buffer + off, len - off, insn);
885 				break;
886 			} else {
887 				printf("\t%016" PRIx64 "\t%s\n", ip,
888 					dump_insn(&x, ip, buffer + off, len - off, &ilen));
889 				if (ilen == 0)
890 					break;
891 				insn++;
892 			}
893 		}
894 	}
895 
896 	/*
897 	 * Hit the branch? In this case we are already done, and the target
898 	 * has not been executed yet.
899 	 */
900 	if (br->entries[0].from == sample->ip)
901 		return;
902 	if (br->entries[0].flags.abort)
903 		return;
904 
905 	/*
906 	 * Print final block upto sample
907 	 */
908 	start = br->entries[0].to;
909 	end = sample->ip;
910 	len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, true);
911 	print_ip_sym(thread, x.cpumode, x.cpu, start, &lastsym, attr);
912 	if (len <= 0) {
913 		/* Print at least last IP if basic block did not work */
914 		len = grab_bb(buffer, sample->ip, sample->ip,
915 			      machine, thread, &x.is64bit, &x.cpumode, false);
916 		if (len <= 0)
917 			return;
918 
919 		printf("\t%016" PRIx64 "\t%s\n", sample->ip,
920 			dump_insn(&x, sample->ip, buffer, len, NULL));
921 		return;
922 	}
923 	for (off = 0; off <= end - start; off += ilen) {
924 		printf("\t%016" PRIx64 "\t%s\n", start + off,
925 			dump_insn(&x, start + off, buffer + off, len - off, &ilen));
926 		if (ilen == 0)
927 			break;
928 	}
929 }
930 
931 static void print_sample_addr(struct perf_sample *sample,
932 			  struct thread *thread,
933 			  struct perf_event_attr *attr)
934 {
935 	struct addr_location al;
936 
937 	printf("%16" PRIx64, sample->addr);
938 
939 	if (!sample_addr_correlates_sym(attr))
940 		return;
941 
942 	thread__resolve(thread, &al, sample);
943 
944 	if (PRINT_FIELD(SYM)) {
945 		printf(" ");
946 		if (PRINT_FIELD(SYMOFFSET))
947 			symbol__fprintf_symname_offs(al.sym, &al, stdout);
948 		else
949 			symbol__fprintf_symname(al.sym, stdout);
950 	}
951 
952 	if (PRINT_FIELD(DSO)) {
953 		printf(" (");
954 		map__fprintf_dsoname(al.map, stdout);
955 		printf(")");
956 	}
957 }
958 
959 static void print_sample_callindent(struct perf_sample *sample,
960 				    struct perf_evsel *evsel,
961 				    struct thread *thread,
962 				    struct addr_location *al)
963 {
964 	struct perf_event_attr *attr = &evsel->attr;
965 	size_t depth = thread_stack__depth(thread);
966 	struct addr_location addr_al;
967 	const char *name = NULL;
968 	static int spacing;
969 	int len = 0;
970 	u64 ip = 0;
971 
972 	/*
973 	 * The 'return' has already been popped off the stack so the depth has
974 	 * to be adjusted to match the 'call'.
975 	 */
976 	if (thread->ts && sample->flags & PERF_IP_FLAG_RETURN)
977 		depth += 1;
978 
979 	if (sample->flags & (PERF_IP_FLAG_CALL | PERF_IP_FLAG_TRACE_BEGIN)) {
980 		if (sample_addr_correlates_sym(attr)) {
981 			thread__resolve(thread, &addr_al, sample);
982 			if (addr_al.sym)
983 				name = addr_al.sym->name;
984 			else
985 				ip = sample->addr;
986 		} else {
987 			ip = sample->addr;
988 		}
989 	} else if (sample->flags & (PERF_IP_FLAG_RETURN | PERF_IP_FLAG_TRACE_END)) {
990 		if (al->sym)
991 			name = al->sym->name;
992 		else
993 			ip = sample->ip;
994 	}
995 
996 	if (name)
997 		len = printf("%*s%s", (int)depth * 4, "", name);
998 	else if (ip)
999 		len = printf("%*s%16" PRIx64, (int)depth * 4, "", ip);
1000 
1001 	if (len < 0)
1002 		return;
1003 
1004 	/*
1005 	 * Try to keep the output length from changing frequently so that the
1006 	 * output lines up more nicely.
1007 	 */
1008 	if (len > spacing || (len && len < spacing - 52))
1009 		spacing = round_up(len + 4, 32);
1010 
1011 	if (len < spacing)
1012 		printf("%*s", spacing - len, "");
1013 }
1014 
1015 static void print_insn(struct perf_sample *sample,
1016 		       struct perf_event_attr *attr,
1017 		       struct thread *thread,
1018 		       struct machine *machine)
1019 {
1020 	if (PRINT_FIELD(INSNLEN))
1021 		printf(" ilen: %d", sample->insn_len);
1022 	if (PRINT_FIELD(INSN)) {
1023 		int i;
1024 
1025 		printf(" insn:");
1026 		for (i = 0; i < sample->insn_len; i++)
1027 			printf(" %02x", (unsigned char)sample->insn[i]);
1028 	}
1029 	if (PRINT_FIELD(BRSTACKINSN))
1030 		print_sample_brstackinsn(sample, thread, attr, machine);
1031 }
1032 
1033 static void print_sample_bts(struct perf_sample *sample,
1034 			     struct perf_evsel *evsel,
1035 			     struct thread *thread,
1036 			     struct addr_location *al,
1037 			     struct machine *machine)
1038 {
1039 	struct perf_event_attr *attr = &evsel->attr;
1040 	unsigned int type = output_type(attr->type);
1041 	bool print_srcline_last = false;
1042 
1043 	if (PRINT_FIELD(CALLINDENT))
1044 		print_sample_callindent(sample, evsel, thread, al);
1045 
1046 	/* print branch_from information */
1047 	if (PRINT_FIELD(IP)) {
1048 		unsigned int print_opts = output[type].print_ip_opts;
1049 		struct callchain_cursor *cursor = NULL;
1050 
1051 		if (symbol_conf.use_callchain && sample->callchain &&
1052 		    thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
1053 					      sample, NULL, NULL, scripting_max_stack) == 0)
1054 			cursor = &callchain_cursor;
1055 
1056 		if (cursor == NULL) {
1057 			putchar(' ');
1058 			if (print_opts & EVSEL__PRINT_SRCLINE) {
1059 				print_srcline_last = true;
1060 				print_opts &= ~EVSEL__PRINT_SRCLINE;
1061 			}
1062 		} else
1063 			putchar('\n');
1064 
1065 		sample__fprintf_sym(sample, al, 0, print_opts, cursor, stdout);
1066 	}
1067 
1068 	/* print branch_to information */
1069 	if (PRINT_FIELD(ADDR) ||
1070 	    ((evsel->attr.sample_type & PERF_SAMPLE_ADDR) &&
1071 	     !output[type].user_set)) {
1072 		printf(" => ");
1073 		print_sample_addr(sample, thread, attr);
1074 	}
1075 
1076 	if (print_srcline_last)
1077 		map__fprintf_srcline(al->map, al->addr, "\n  ", stdout);
1078 
1079 	print_insn(sample, attr, thread, machine);
1080 
1081 	printf("\n");
1082 }
1083 
1084 static struct {
1085 	u32 flags;
1086 	const char *name;
1087 } sample_flags[] = {
1088 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL, "call"},
1089 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN, "return"},
1090 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CONDITIONAL, "jcc"},
1091 	{PERF_IP_FLAG_BRANCH, "jmp"},
1092 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_INTERRUPT, "int"},
1093 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN | PERF_IP_FLAG_INTERRUPT, "iret"},
1094 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_SYSCALLRET, "syscall"},
1095 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN | PERF_IP_FLAG_SYSCALLRET, "sysret"},
1096 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_ASYNC, "async"},
1097 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_ASYNC |	PERF_IP_FLAG_INTERRUPT, "hw int"},
1098 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TX_ABORT, "tx abrt"},
1099 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TRACE_BEGIN, "tr strt"},
1100 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TRACE_END, "tr end"},
1101 	{0, NULL}
1102 };
1103 
1104 static void print_sample_flags(u32 flags)
1105 {
1106 	const char *chars = PERF_IP_FLAG_CHARS;
1107 	const int n = strlen(PERF_IP_FLAG_CHARS);
1108 	bool in_tx = flags & PERF_IP_FLAG_IN_TX;
1109 	const char *name = NULL;
1110 	char str[33];
1111 	int i, pos = 0;
1112 
1113 	for (i = 0; sample_flags[i].name ; i++) {
1114 		if (sample_flags[i].flags == (flags & ~PERF_IP_FLAG_IN_TX)) {
1115 			name = sample_flags[i].name;
1116 			break;
1117 		}
1118 	}
1119 
1120 	for (i = 0; i < n; i++, flags >>= 1) {
1121 		if (flags & 1)
1122 			str[pos++] = chars[i];
1123 	}
1124 	for (; i < 32; i++, flags >>= 1) {
1125 		if (flags & 1)
1126 			str[pos++] = '?';
1127 	}
1128 	str[pos] = 0;
1129 
1130 	if (name)
1131 		printf("  %-7s%4s ", name, in_tx ? "(x)" : "");
1132 	else
1133 		printf("  %-11s ", str);
1134 }
1135 
1136 struct printer_data {
1137 	int line_no;
1138 	bool hit_nul;
1139 	bool is_printable;
1140 };
1141 
1142 static void
1143 print_sample_bpf_output_printer(enum binary_printer_ops op,
1144 				unsigned int val,
1145 				void *extra)
1146 {
1147 	unsigned char ch = (unsigned char)val;
1148 	struct printer_data *printer_data = extra;
1149 
1150 	switch (op) {
1151 	case BINARY_PRINT_DATA_BEGIN:
1152 		printf("\n");
1153 		break;
1154 	case BINARY_PRINT_LINE_BEGIN:
1155 		printf("%17s", !printer_data->line_no ? "BPF output:" :
1156 						        "           ");
1157 		break;
1158 	case BINARY_PRINT_ADDR:
1159 		printf(" %04x:", val);
1160 		break;
1161 	case BINARY_PRINT_NUM_DATA:
1162 		printf(" %02x", val);
1163 		break;
1164 	case BINARY_PRINT_NUM_PAD:
1165 		printf("   ");
1166 		break;
1167 	case BINARY_PRINT_SEP:
1168 		printf("  ");
1169 		break;
1170 	case BINARY_PRINT_CHAR_DATA:
1171 		if (printer_data->hit_nul && ch)
1172 			printer_data->is_printable = false;
1173 
1174 		if (!isprint(ch)) {
1175 			printf("%c", '.');
1176 
1177 			if (!printer_data->is_printable)
1178 				break;
1179 
1180 			if (ch == '\0')
1181 				printer_data->hit_nul = true;
1182 			else
1183 				printer_data->is_printable = false;
1184 		} else {
1185 			printf("%c", ch);
1186 		}
1187 		break;
1188 	case BINARY_PRINT_CHAR_PAD:
1189 		printf(" ");
1190 		break;
1191 	case BINARY_PRINT_LINE_END:
1192 		printf("\n");
1193 		printer_data->line_no++;
1194 		break;
1195 	case BINARY_PRINT_DATA_END:
1196 	default:
1197 		break;
1198 	}
1199 }
1200 
1201 static void print_sample_bpf_output(struct perf_sample *sample)
1202 {
1203 	unsigned int nr_bytes = sample->raw_size;
1204 	struct printer_data printer_data = {0, false, true};
1205 
1206 	print_binary(sample->raw_data, nr_bytes, 8,
1207 		     print_sample_bpf_output_printer, &printer_data);
1208 
1209 	if (printer_data.is_printable && printer_data.hit_nul)
1210 		printf("%17s \"%s\"\n", "BPF string:",
1211 		       (char *)(sample->raw_data));
1212 }
1213 
1214 static void print_sample_spacing(int len, int spacing)
1215 {
1216 	if (len > 0 && len < spacing)
1217 		printf("%*s", spacing - len, "");
1218 }
1219 
1220 static void print_sample_pt_spacing(int len)
1221 {
1222 	print_sample_spacing(len, 34);
1223 }
1224 
1225 static void print_sample_synth_ptwrite(struct perf_sample *sample)
1226 {
1227 	struct perf_synth_intel_ptwrite *data = perf_sample__synth_ptr(sample);
1228 	int len;
1229 
1230 	if (perf_sample__bad_synth_size(sample, *data))
1231 		return;
1232 
1233 	len = printf(" IP: %u payload: %#" PRIx64 " ",
1234 		     data->ip, le64_to_cpu(data->payload));
1235 	print_sample_pt_spacing(len);
1236 }
1237 
1238 static void print_sample_synth_mwait(struct perf_sample *sample)
1239 {
1240 	struct perf_synth_intel_mwait *data = perf_sample__synth_ptr(sample);
1241 	int len;
1242 
1243 	if (perf_sample__bad_synth_size(sample, *data))
1244 		return;
1245 
1246 	len = printf(" hints: %#x extensions: %#x ",
1247 		     data->hints, data->extensions);
1248 	print_sample_pt_spacing(len);
1249 }
1250 
1251 static void print_sample_synth_pwre(struct perf_sample *sample)
1252 {
1253 	struct perf_synth_intel_pwre *data = perf_sample__synth_ptr(sample);
1254 	int len;
1255 
1256 	if (perf_sample__bad_synth_size(sample, *data))
1257 		return;
1258 
1259 	len = printf(" hw: %u cstate: %u sub-cstate: %u ",
1260 		     data->hw, data->cstate, data->subcstate);
1261 	print_sample_pt_spacing(len);
1262 }
1263 
1264 static void print_sample_synth_exstop(struct perf_sample *sample)
1265 {
1266 	struct perf_synth_intel_exstop *data = perf_sample__synth_ptr(sample);
1267 	int len;
1268 
1269 	if (perf_sample__bad_synth_size(sample, *data))
1270 		return;
1271 
1272 	len = printf(" IP: %u ", data->ip);
1273 	print_sample_pt_spacing(len);
1274 }
1275 
1276 static void print_sample_synth_pwrx(struct perf_sample *sample)
1277 {
1278 	struct perf_synth_intel_pwrx *data = perf_sample__synth_ptr(sample);
1279 	int len;
1280 
1281 	if (perf_sample__bad_synth_size(sample, *data))
1282 		return;
1283 
1284 	len = printf(" deepest cstate: %u last cstate: %u wake reason: %#x ",
1285 		     data->deepest_cstate, data->last_cstate,
1286 		     data->wake_reason);
1287 	print_sample_pt_spacing(len);
1288 }
1289 
1290 static void print_sample_synth_cbr(struct perf_sample *sample)
1291 {
1292 	struct perf_synth_intel_cbr *data = perf_sample__synth_ptr(sample);
1293 	unsigned int percent, freq;
1294 	int len;
1295 
1296 	if (perf_sample__bad_synth_size(sample, *data))
1297 		return;
1298 
1299 	freq = (le32_to_cpu(data->freq) + 500) / 1000;
1300 	len = printf(" cbr: %2u freq: %4u MHz ", data->cbr, freq);
1301 	if (data->max_nonturbo) {
1302 		percent = (5 + (1000 * data->cbr) / data->max_nonturbo) / 10;
1303 		len += printf("(%3u%%) ", percent);
1304 	}
1305 	print_sample_pt_spacing(len);
1306 }
1307 
1308 static void print_sample_synth(struct perf_sample *sample,
1309 			       struct perf_evsel *evsel)
1310 {
1311 	switch (evsel->attr.config) {
1312 	case PERF_SYNTH_INTEL_PTWRITE:
1313 		print_sample_synth_ptwrite(sample);
1314 		break;
1315 	case PERF_SYNTH_INTEL_MWAIT:
1316 		print_sample_synth_mwait(sample);
1317 		break;
1318 	case PERF_SYNTH_INTEL_PWRE:
1319 		print_sample_synth_pwre(sample);
1320 		break;
1321 	case PERF_SYNTH_INTEL_EXSTOP:
1322 		print_sample_synth_exstop(sample);
1323 		break;
1324 	case PERF_SYNTH_INTEL_PWRX:
1325 		print_sample_synth_pwrx(sample);
1326 		break;
1327 	case PERF_SYNTH_INTEL_CBR:
1328 		print_sample_synth_cbr(sample);
1329 		break;
1330 	default:
1331 		break;
1332 	}
1333 }
1334 
1335 struct perf_script {
1336 	struct perf_tool	tool;
1337 	struct perf_session	*session;
1338 	bool			show_task_events;
1339 	bool			show_mmap_events;
1340 	bool			show_switch_events;
1341 	bool			show_namespace_events;
1342 	bool			allocated;
1343 	struct cpu_map		*cpus;
1344 	struct thread_map	*threads;
1345 	int			name_width;
1346 	const char              *time_str;
1347 	struct perf_time_interval ptime;
1348 };
1349 
1350 static int perf_evlist__max_name_len(struct perf_evlist *evlist)
1351 {
1352 	struct perf_evsel *evsel;
1353 	int max = 0;
1354 
1355 	evlist__for_each_entry(evlist, evsel) {
1356 		int len = strlen(perf_evsel__name(evsel));
1357 
1358 		max = MAX(len, max);
1359 	}
1360 
1361 	return max;
1362 }
1363 
1364 static size_t data_src__printf(u64 data_src)
1365 {
1366 	struct mem_info mi = { .data_src.val = data_src };
1367 	char decode[100];
1368 	char out[100];
1369 	static int maxlen;
1370 	int len;
1371 
1372 	perf_script__meminfo_scnprintf(decode, 100, &mi);
1373 
1374 	len = scnprintf(out, 100, "%16" PRIx64 " %s", data_src, decode);
1375 	if (maxlen < len)
1376 		maxlen = len;
1377 
1378 	return printf("%-*s", maxlen, out);
1379 }
1380 
1381 static void process_event(struct perf_script *script,
1382 			  struct perf_sample *sample, struct perf_evsel *evsel,
1383 			  struct addr_location *al,
1384 			  struct machine *machine)
1385 {
1386 	struct thread *thread = al->thread;
1387 	struct perf_event_attr *attr = &evsel->attr;
1388 	unsigned int type = output_type(attr->type);
1389 
1390 	if (output[type].fields == 0)
1391 		return;
1392 
1393 	print_sample_start(sample, thread, evsel);
1394 
1395 	if (PRINT_FIELD(PERIOD))
1396 		printf("%10" PRIu64 " ", sample->period);
1397 
1398 	if (PRINT_FIELD(EVNAME)) {
1399 		const char *evname = perf_evsel__name(evsel);
1400 
1401 		if (!script->name_width)
1402 			script->name_width = perf_evlist__max_name_len(script->session->evlist);
1403 
1404 		printf("%*s: ", script->name_width,
1405 		       evname ? evname : "[unknown]");
1406 	}
1407 
1408 	if (print_flags)
1409 		print_sample_flags(sample->flags);
1410 
1411 	if (is_bts_event(attr)) {
1412 		print_sample_bts(sample, evsel, thread, al, machine);
1413 		return;
1414 	}
1415 
1416 	if (PRINT_FIELD(TRACE))
1417 		event_format__print(evsel->tp_format, sample->cpu,
1418 				    sample->raw_data, sample->raw_size);
1419 
1420 	if (attr->type == PERF_TYPE_SYNTH && PRINT_FIELD(SYNTH))
1421 		print_sample_synth(sample, evsel);
1422 
1423 	if (PRINT_FIELD(ADDR))
1424 		print_sample_addr(sample, thread, attr);
1425 
1426 	if (PRINT_FIELD(DATA_SRC))
1427 		data_src__printf(sample->data_src);
1428 
1429 	if (PRINT_FIELD(WEIGHT))
1430 		printf("%16" PRIu64, sample->weight);
1431 
1432 	if (PRINT_FIELD(IP)) {
1433 		struct callchain_cursor *cursor = NULL;
1434 
1435 		if (symbol_conf.use_callchain && sample->callchain &&
1436 		    thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
1437 					      sample, NULL, NULL, scripting_max_stack) == 0)
1438 			cursor = &callchain_cursor;
1439 
1440 		putchar(cursor ? '\n' : ' ');
1441 		sample__fprintf_sym(sample, al, 0, output[type].print_ip_opts, cursor, stdout);
1442 	}
1443 
1444 	if (PRINT_FIELD(IREGS))
1445 		print_sample_iregs(sample, attr);
1446 
1447 	if (PRINT_FIELD(BRSTACK))
1448 		print_sample_brstack(sample, thread, attr);
1449 	else if (PRINT_FIELD(BRSTACKSYM))
1450 		print_sample_brstacksym(sample, thread, attr);
1451 	else if (PRINT_FIELD(BRSTACKOFF))
1452 		print_sample_brstackoff(sample, thread, attr);
1453 
1454 	if (perf_evsel__is_bpf_output(evsel) && PRINT_FIELD(BPF_OUTPUT))
1455 		print_sample_bpf_output(sample);
1456 	print_insn(sample, attr, thread, machine);
1457 
1458 	if (PRINT_FIELD(PHYS_ADDR))
1459 		printf("%16" PRIx64, sample->phys_addr);
1460 	printf("\n");
1461 }
1462 
1463 static struct scripting_ops	*scripting_ops;
1464 
1465 static void __process_stat(struct perf_evsel *counter, u64 tstamp)
1466 {
1467 	int nthreads = thread_map__nr(counter->threads);
1468 	int ncpus = perf_evsel__nr_cpus(counter);
1469 	int cpu, thread;
1470 	static int header_printed;
1471 
1472 	if (counter->system_wide)
1473 		nthreads = 1;
1474 
1475 	if (!header_printed) {
1476 		printf("%3s %8s %15s %15s %15s %15s %s\n",
1477 		       "CPU", "THREAD", "VAL", "ENA", "RUN", "TIME", "EVENT");
1478 		header_printed = 1;
1479 	}
1480 
1481 	for (thread = 0; thread < nthreads; thread++) {
1482 		for (cpu = 0; cpu < ncpus; cpu++) {
1483 			struct perf_counts_values *counts;
1484 
1485 			counts = perf_counts(counter->counts, cpu, thread);
1486 
1487 			printf("%3d %8d %15" PRIu64 " %15" PRIu64 " %15" PRIu64 " %15" PRIu64 " %s\n",
1488 				counter->cpus->map[cpu],
1489 				thread_map__pid(counter->threads, thread),
1490 				counts->val,
1491 				counts->ena,
1492 				counts->run,
1493 				tstamp,
1494 				perf_evsel__name(counter));
1495 		}
1496 	}
1497 }
1498 
1499 static void process_stat(struct perf_evsel *counter, u64 tstamp)
1500 {
1501 	if (scripting_ops && scripting_ops->process_stat)
1502 		scripting_ops->process_stat(&stat_config, counter, tstamp);
1503 	else
1504 		__process_stat(counter, tstamp);
1505 }
1506 
1507 static void process_stat_interval(u64 tstamp)
1508 {
1509 	if (scripting_ops && scripting_ops->process_stat_interval)
1510 		scripting_ops->process_stat_interval(tstamp);
1511 }
1512 
1513 static void setup_scripting(void)
1514 {
1515 	setup_perl_scripting();
1516 	setup_python_scripting();
1517 }
1518 
1519 static int flush_scripting(void)
1520 {
1521 	return scripting_ops ? scripting_ops->flush_script() : 0;
1522 }
1523 
1524 static int cleanup_scripting(void)
1525 {
1526 	pr_debug("\nperf script stopped\n");
1527 
1528 	return scripting_ops ? scripting_ops->stop_script() : 0;
1529 }
1530 
1531 static int process_sample_event(struct perf_tool *tool,
1532 				union perf_event *event,
1533 				struct perf_sample *sample,
1534 				struct perf_evsel *evsel,
1535 				struct machine *machine)
1536 {
1537 	struct perf_script *scr = container_of(tool, struct perf_script, tool);
1538 	struct addr_location al;
1539 
1540 	if (perf_time__skip_sample(&scr->ptime, sample->time))
1541 		return 0;
1542 
1543 	if (debug_mode) {
1544 		if (sample->time < last_timestamp) {
1545 			pr_err("Samples misordered, previous: %" PRIu64
1546 				" this: %" PRIu64 "\n", last_timestamp,
1547 				sample->time);
1548 			nr_unordered++;
1549 		}
1550 		last_timestamp = sample->time;
1551 		return 0;
1552 	}
1553 
1554 	if (machine__resolve(machine, &al, sample) < 0) {
1555 		pr_err("problem processing %d event, skipping it.\n",
1556 		       event->header.type);
1557 		return -1;
1558 	}
1559 
1560 	if (al.filtered)
1561 		goto out_put;
1562 
1563 	if (cpu_list && !test_bit(sample->cpu, cpu_bitmap))
1564 		goto out_put;
1565 
1566 	if (scripting_ops)
1567 		scripting_ops->process_event(event, sample, evsel, &al);
1568 	else
1569 		process_event(scr, sample, evsel, &al, machine);
1570 
1571 out_put:
1572 	addr_location__put(&al);
1573 	return 0;
1574 }
1575 
1576 static int process_attr(struct perf_tool *tool, union perf_event *event,
1577 			struct perf_evlist **pevlist)
1578 {
1579 	struct perf_script *scr = container_of(tool, struct perf_script, tool);
1580 	struct perf_evlist *evlist;
1581 	struct perf_evsel *evsel, *pos;
1582 	int err;
1583 
1584 	err = perf_event__process_attr(tool, event, pevlist);
1585 	if (err)
1586 		return err;
1587 
1588 	evlist = *pevlist;
1589 	evsel = perf_evlist__last(*pevlist);
1590 
1591 	if (evsel->attr.type >= PERF_TYPE_MAX &&
1592 	    evsel->attr.type != PERF_TYPE_SYNTH)
1593 		return 0;
1594 
1595 	evlist__for_each_entry(evlist, pos) {
1596 		if (pos->attr.type == evsel->attr.type && pos != evsel)
1597 			return 0;
1598 	}
1599 
1600 	set_print_ip_opts(&evsel->attr);
1601 
1602 	if (evsel->attr.sample_type)
1603 		err = perf_evsel__check_attr(evsel, scr->session);
1604 
1605 	return err;
1606 }
1607 
1608 static int process_comm_event(struct perf_tool *tool,
1609 			      union perf_event *event,
1610 			      struct perf_sample *sample,
1611 			      struct machine *machine)
1612 {
1613 	struct thread *thread;
1614 	struct perf_script *script = container_of(tool, struct perf_script, tool);
1615 	struct perf_session *session = script->session;
1616 	struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1617 	int ret = -1;
1618 
1619 	thread = machine__findnew_thread(machine, event->comm.pid, event->comm.tid);
1620 	if (thread == NULL) {
1621 		pr_debug("problem processing COMM event, skipping it.\n");
1622 		return -1;
1623 	}
1624 
1625 	if (perf_event__process_comm(tool, event, sample, machine) < 0)
1626 		goto out;
1627 
1628 	if (!evsel->attr.sample_id_all) {
1629 		sample->cpu = 0;
1630 		sample->time = 0;
1631 		sample->tid = event->comm.tid;
1632 		sample->pid = event->comm.pid;
1633 	}
1634 	print_sample_start(sample, thread, evsel);
1635 	perf_event__fprintf(event, stdout);
1636 	ret = 0;
1637 out:
1638 	thread__put(thread);
1639 	return ret;
1640 }
1641 
1642 static int process_namespaces_event(struct perf_tool *tool,
1643 				    union perf_event *event,
1644 				    struct perf_sample *sample,
1645 				    struct machine *machine)
1646 {
1647 	struct thread *thread;
1648 	struct perf_script *script = container_of(tool, struct perf_script, tool);
1649 	struct perf_session *session = script->session;
1650 	struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1651 	int ret = -1;
1652 
1653 	thread = machine__findnew_thread(machine, event->namespaces.pid,
1654 					 event->namespaces.tid);
1655 	if (thread == NULL) {
1656 		pr_debug("problem processing NAMESPACES event, skipping it.\n");
1657 		return -1;
1658 	}
1659 
1660 	if (perf_event__process_namespaces(tool, event, sample, machine) < 0)
1661 		goto out;
1662 
1663 	if (!evsel->attr.sample_id_all) {
1664 		sample->cpu = 0;
1665 		sample->time = 0;
1666 		sample->tid = event->namespaces.tid;
1667 		sample->pid = event->namespaces.pid;
1668 	}
1669 	print_sample_start(sample, thread, evsel);
1670 	perf_event__fprintf(event, stdout);
1671 	ret = 0;
1672 out:
1673 	thread__put(thread);
1674 	return ret;
1675 }
1676 
1677 static int process_fork_event(struct perf_tool *tool,
1678 			      union perf_event *event,
1679 			      struct perf_sample *sample,
1680 			      struct machine *machine)
1681 {
1682 	struct thread *thread;
1683 	struct perf_script *script = container_of(tool, struct perf_script, tool);
1684 	struct perf_session *session = script->session;
1685 	struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1686 
1687 	if (perf_event__process_fork(tool, event, sample, machine) < 0)
1688 		return -1;
1689 
1690 	thread = machine__findnew_thread(machine, event->fork.pid, event->fork.tid);
1691 	if (thread == NULL) {
1692 		pr_debug("problem processing FORK event, skipping it.\n");
1693 		return -1;
1694 	}
1695 
1696 	if (!evsel->attr.sample_id_all) {
1697 		sample->cpu = 0;
1698 		sample->time = event->fork.time;
1699 		sample->tid = event->fork.tid;
1700 		sample->pid = event->fork.pid;
1701 	}
1702 	print_sample_start(sample, thread, evsel);
1703 	perf_event__fprintf(event, stdout);
1704 	thread__put(thread);
1705 
1706 	return 0;
1707 }
1708 static int process_exit_event(struct perf_tool *tool,
1709 			      union perf_event *event,
1710 			      struct perf_sample *sample,
1711 			      struct machine *machine)
1712 {
1713 	int err = 0;
1714 	struct thread *thread;
1715 	struct perf_script *script = container_of(tool, struct perf_script, tool);
1716 	struct perf_session *session = script->session;
1717 	struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1718 
1719 	thread = machine__findnew_thread(machine, event->fork.pid, event->fork.tid);
1720 	if (thread == NULL) {
1721 		pr_debug("problem processing EXIT event, skipping it.\n");
1722 		return -1;
1723 	}
1724 
1725 	if (!evsel->attr.sample_id_all) {
1726 		sample->cpu = 0;
1727 		sample->time = 0;
1728 		sample->tid = event->fork.tid;
1729 		sample->pid = event->fork.pid;
1730 	}
1731 	print_sample_start(sample, thread, evsel);
1732 	perf_event__fprintf(event, stdout);
1733 
1734 	if (perf_event__process_exit(tool, event, sample, machine) < 0)
1735 		err = -1;
1736 
1737 	thread__put(thread);
1738 	return err;
1739 }
1740 
1741 static int process_mmap_event(struct perf_tool *tool,
1742 			      union perf_event *event,
1743 			      struct perf_sample *sample,
1744 			      struct machine *machine)
1745 {
1746 	struct thread *thread;
1747 	struct perf_script *script = container_of(tool, struct perf_script, tool);
1748 	struct perf_session *session = script->session;
1749 	struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1750 
1751 	if (perf_event__process_mmap(tool, event, sample, machine) < 0)
1752 		return -1;
1753 
1754 	thread = machine__findnew_thread(machine, event->mmap.pid, event->mmap.tid);
1755 	if (thread == NULL) {
1756 		pr_debug("problem processing MMAP event, skipping it.\n");
1757 		return -1;
1758 	}
1759 
1760 	if (!evsel->attr.sample_id_all) {
1761 		sample->cpu = 0;
1762 		sample->time = 0;
1763 		sample->tid = event->mmap.tid;
1764 		sample->pid = event->mmap.pid;
1765 	}
1766 	print_sample_start(sample, thread, evsel);
1767 	perf_event__fprintf(event, stdout);
1768 	thread__put(thread);
1769 	return 0;
1770 }
1771 
1772 static int process_mmap2_event(struct perf_tool *tool,
1773 			      union perf_event *event,
1774 			      struct perf_sample *sample,
1775 			      struct machine *machine)
1776 {
1777 	struct thread *thread;
1778 	struct perf_script *script = container_of(tool, struct perf_script, tool);
1779 	struct perf_session *session = script->session;
1780 	struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1781 
1782 	if (perf_event__process_mmap2(tool, event, sample, machine) < 0)
1783 		return -1;
1784 
1785 	thread = machine__findnew_thread(machine, event->mmap2.pid, event->mmap2.tid);
1786 	if (thread == NULL) {
1787 		pr_debug("problem processing MMAP2 event, skipping it.\n");
1788 		return -1;
1789 	}
1790 
1791 	if (!evsel->attr.sample_id_all) {
1792 		sample->cpu = 0;
1793 		sample->time = 0;
1794 		sample->tid = event->mmap2.tid;
1795 		sample->pid = event->mmap2.pid;
1796 	}
1797 	print_sample_start(sample, thread, evsel);
1798 	perf_event__fprintf(event, stdout);
1799 	thread__put(thread);
1800 	return 0;
1801 }
1802 
1803 static int process_switch_event(struct perf_tool *tool,
1804 				union perf_event *event,
1805 				struct perf_sample *sample,
1806 				struct machine *machine)
1807 {
1808 	struct thread *thread;
1809 	struct perf_script *script = container_of(tool, struct perf_script, tool);
1810 	struct perf_session *session = script->session;
1811 	struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1812 
1813 	if (perf_event__process_switch(tool, event, sample, machine) < 0)
1814 		return -1;
1815 
1816 	thread = machine__findnew_thread(machine, sample->pid,
1817 					 sample->tid);
1818 	if (thread == NULL) {
1819 		pr_debug("problem processing SWITCH event, skipping it.\n");
1820 		return -1;
1821 	}
1822 
1823 	print_sample_start(sample, thread, evsel);
1824 	perf_event__fprintf(event, stdout);
1825 	thread__put(thread);
1826 	return 0;
1827 }
1828 
1829 static void sig_handler(int sig __maybe_unused)
1830 {
1831 	session_done = 1;
1832 }
1833 
1834 static int __cmd_script(struct perf_script *script)
1835 {
1836 	int ret;
1837 
1838 	signal(SIGINT, sig_handler);
1839 
1840 	/* override event processing functions */
1841 	if (script->show_task_events) {
1842 		script->tool.comm = process_comm_event;
1843 		script->tool.fork = process_fork_event;
1844 		script->tool.exit = process_exit_event;
1845 	}
1846 	if (script->show_mmap_events) {
1847 		script->tool.mmap = process_mmap_event;
1848 		script->tool.mmap2 = process_mmap2_event;
1849 	}
1850 	if (script->show_switch_events)
1851 		script->tool.context_switch = process_switch_event;
1852 	if (script->show_namespace_events)
1853 		script->tool.namespaces = process_namespaces_event;
1854 
1855 	ret = perf_session__process_events(script->session);
1856 
1857 	if (debug_mode)
1858 		pr_err("Misordered timestamps: %" PRIu64 "\n", nr_unordered);
1859 
1860 	return ret;
1861 }
1862 
1863 struct script_spec {
1864 	struct list_head	node;
1865 	struct scripting_ops	*ops;
1866 	char			spec[0];
1867 };
1868 
1869 static LIST_HEAD(script_specs);
1870 
1871 static struct script_spec *script_spec__new(const char *spec,
1872 					    struct scripting_ops *ops)
1873 {
1874 	struct script_spec *s = malloc(sizeof(*s) + strlen(spec) + 1);
1875 
1876 	if (s != NULL) {
1877 		strcpy(s->spec, spec);
1878 		s->ops = ops;
1879 	}
1880 
1881 	return s;
1882 }
1883 
1884 static void script_spec__add(struct script_spec *s)
1885 {
1886 	list_add_tail(&s->node, &script_specs);
1887 }
1888 
1889 static struct script_spec *script_spec__find(const char *spec)
1890 {
1891 	struct script_spec *s;
1892 
1893 	list_for_each_entry(s, &script_specs, node)
1894 		if (strcasecmp(s->spec, spec) == 0)
1895 			return s;
1896 	return NULL;
1897 }
1898 
1899 int script_spec_register(const char *spec, struct scripting_ops *ops)
1900 {
1901 	struct script_spec *s;
1902 
1903 	s = script_spec__find(spec);
1904 	if (s)
1905 		return -1;
1906 
1907 	s = script_spec__new(spec, ops);
1908 	if (!s)
1909 		return -1;
1910 	else
1911 		script_spec__add(s);
1912 
1913 	return 0;
1914 }
1915 
1916 static struct scripting_ops *script_spec__lookup(const char *spec)
1917 {
1918 	struct script_spec *s = script_spec__find(spec);
1919 	if (!s)
1920 		return NULL;
1921 
1922 	return s->ops;
1923 }
1924 
1925 static void list_available_languages(void)
1926 {
1927 	struct script_spec *s;
1928 
1929 	fprintf(stderr, "\n");
1930 	fprintf(stderr, "Scripting language extensions (used in "
1931 		"perf script -s [spec:]script.[spec]):\n\n");
1932 
1933 	list_for_each_entry(s, &script_specs, node)
1934 		fprintf(stderr, "  %-42s [%s]\n", s->spec, s->ops->name);
1935 
1936 	fprintf(stderr, "\n");
1937 }
1938 
1939 static int parse_scriptname(const struct option *opt __maybe_unused,
1940 			    const char *str, int unset __maybe_unused)
1941 {
1942 	char spec[PATH_MAX];
1943 	const char *script, *ext;
1944 	int len;
1945 
1946 	if (strcmp(str, "lang") == 0) {
1947 		list_available_languages();
1948 		exit(0);
1949 	}
1950 
1951 	script = strchr(str, ':');
1952 	if (script) {
1953 		len = script - str;
1954 		if (len >= PATH_MAX) {
1955 			fprintf(stderr, "invalid language specifier");
1956 			return -1;
1957 		}
1958 		strncpy(spec, str, len);
1959 		spec[len] = '\0';
1960 		scripting_ops = script_spec__lookup(spec);
1961 		if (!scripting_ops) {
1962 			fprintf(stderr, "invalid language specifier");
1963 			return -1;
1964 		}
1965 		script++;
1966 	} else {
1967 		script = str;
1968 		ext = strrchr(script, '.');
1969 		if (!ext) {
1970 			fprintf(stderr, "invalid script extension");
1971 			return -1;
1972 		}
1973 		scripting_ops = script_spec__lookup(++ext);
1974 		if (!scripting_ops) {
1975 			fprintf(stderr, "invalid script extension");
1976 			return -1;
1977 		}
1978 	}
1979 
1980 	script_name = strdup(script);
1981 
1982 	return 0;
1983 }
1984 
1985 static int parse_output_fields(const struct option *opt __maybe_unused,
1986 			    const char *arg, int unset __maybe_unused)
1987 {
1988 	char *tok, *strtok_saveptr = NULL;
1989 	int i, imax = ARRAY_SIZE(all_output_options);
1990 	int j;
1991 	int rc = 0;
1992 	char *str = strdup(arg);
1993 	int type = -1;
1994 	enum { DEFAULT, SET, ADD, REMOVE } change = DEFAULT;
1995 
1996 	if (!str)
1997 		return -ENOMEM;
1998 
1999 	/* first word can state for which event type the user is specifying
2000 	 * the fields. If no type exists, the specified fields apply to all
2001 	 * event types found in the file minus the invalid fields for a type.
2002 	 */
2003 	tok = strchr(str, ':');
2004 	if (tok) {
2005 		*tok = '\0';
2006 		tok++;
2007 		if (!strcmp(str, "hw"))
2008 			type = PERF_TYPE_HARDWARE;
2009 		else if (!strcmp(str, "sw"))
2010 			type = PERF_TYPE_SOFTWARE;
2011 		else if (!strcmp(str, "trace"))
2012 			type = PERF_TYPE_TRACEPOINT;
2013 		else if (!strcmp(str, "raw"))
2014 			type = PERF_TYPE_RAW;
2015 		else if (!strcmp(str, "break"))
2016 			type = PERF_TYPE_BREAKPOINT;
2017 		else if (!strcmp(str, "synth"))
2018 			type = OUTPUT_TYPE_SYNTH;
2019 		else {
2020 			fprintf(stderr, "Invalid event type in field string.\n");
2021 			rc = -EINVAL;
2022 			goto out;
2023 		}
2024 
2025 		if (output[type].user_set)
2026 			pr_warning("Overriding previous field request for %s events.\n",
2027 				   event_type(type));
2028 
2029 		output[type].fields = 0;
2030 		output[type].user_set = true;
2031 		output[type].wildcard_set = false;
2032 
2033 	} else {
2034 		tok = str;
2035 		if (strlen(str) == 0) {
2036 			fprintf(stderr,
2037 				"Cannot set fields to 'none' for all event types.\n");
2038 			rc = -EINVAL;
2039 			goto out;
2040 		}
2041 
2042 		/* Don't override defaults for +- */
2043 		if (strchr(str, '+') || strchr(str, '-'))
2044 			goto parse;
2045 
2046 		if (output_set_by_user())
2047 			pr_warning("Overriding previous field request for all events.\n");
2048 
2049 		for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
2050 			output[j].fields = 0;
2051 			output[j].user_set = true;
2052 			output[j].wildcard_set = true;
2053 		}
2054 	}
2055 
2056 parse:
2057 	for (tok = strtok_r(tok, ",", &strtok_saveptr); tok; tok = strtok_r(NULL, ",", &strtok_saveptr)) {
2058 		if (*tok == '+') {
2059 			if (change == SET)
2060 				goto out_badmix;
2061 			change = ADD;
2062 			tok++;
2063 		} else if (*tok == '-') {
2064 			if (change == SET)
2065 				goto out_badmix;
2066 			change = REMOVE;
2067 			tok++;
2068 		} else {
2069 			if (change != SET && change != DEFAULT)
2070 				goto out_badmix;
2071 			change = SET;
2072 		}
2073 
2074 		for (i = 0; i < imax; ++i) {
2075 			if (strcmp(tok, all_output_options[i].str) == 0)
2076 				break;
2077 		}
2078 		if (i == imax && strcmp(tok, "flags") == 0) {
2079 			print_flags = change == REMOVE ? false : true;
2080 			continue;
2081 		}
2082 		if (i == imax) {
2083 			fprintf(stderr, "Invalid field requested.\n");
2084 			rc = -EINVAL;
2085 			goto out;
2086 		}
2087 
2088 		if (type == -1) {
2089 			/* add user option to all events types for
2090 			 * which it is valid
2091 			 */
2092 			for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
2093 				if (output[j].invalid_fields & all_output_options[i].field) {
2094 					pr_warning("\'%s\' not valid for %s events. Ignoring.\n",
2095 						   all_output_options[i].str, event_type(j));
2096 				} else {
2097 					if (change == REMOVE)
2098 						output[j].fields &= ~all_output_options[i].field;
2099 					else
2100 						output[j].fields |= all_output_options[i].field;
2101 				}
2102 			}
2103 		} else {
2104 			if (output[type].invalid_fields & all_output_options[i].field) {
2105 				fprintf(stderr, "\'%s\' not valid for %s events.\n",
2106 					 all_output_options[i].str, event_type(type));
2107 
2108 				rc = -EINVAL;
2109 				goto out;
2110 			}
2111 			output[type].fields |= all_output_options[i].field;
2112 		}
2113 	}
2114 
2115 	if (type >= 0) {
2116 		if (output[type].fields == 0) {
2117 			pr_debug("No fields requested for %s type. "
2118 				 "Events will not be displayed.\n", event_type(type));
2119 		}
2120 	}
2121 	goto out;
2122 
2123 out_badmix:
2124 	fprintf(stderr, "Cannot mix +-field with overridden fields\n");
2125 	rc = -EINVAL;
2126 out:
2127 	free(str);
2128 	return rc;
2129 }
2130 
2131 /* Helper function for filesystems that return a dent->d_type DT_UNKNOWN */
2132 static int is_directory(const char *base_path, const struct dirent *dent)
2133 {
2134 	char path[PATH_MAX];
2135 	struct stat st;
2136 
2137 	sprintf(path, "%s/%s", base_path, dent->d_name);
2138 	if (stat(path, &st))
2139 		return 0;
2140 
2141 	return S_ISDIR(st.st_mode);
2142 }
2143 
2144 #define for_each_lang(scripts_path, scripts_dir, lang_dirent)		\
2145 	while ((lang_dirent = readdir(scripts_dir)) != NULL)		\
2146 		if ((lang_dirent->d_type == DT_DIR ||			\
2147 		     (lang_dirent->d_type == DT_UNKNOWN &&		\
2148 		      is_directory(scripts_path, lang_dirent))) &&	\
2149 		    (strcmp(lang_dirent->d_name, ".")) &&		\
2150 		    (strcmp(lang_dirent->d_name, "..")))
2151 
2152 #define for_each_script(lang_path, lang_dir, script_dirent)		\
2153 	while ((script_dirent = readdir(lang_dir)) != NULL)		\
2154 		if (script_dirent->d_type != DT_DIR &&			\
2155 		    (script_dirent->d_type != DT_UNKNOWN ||		\
2156 		     !is_directory(lang_path, script_dirent)))
2157 
2158 
2159 #define RECORD_SUFFIX			"-record"
2160 #define REPORT_SUFFIX			"-report"
2161 
2162 struct script_desc {
2163 	struct list_head	node;
2164 	char			*name;
2165 	char			*half_liner;
2166 	char			*args;
2167 };
2168 
2169 static LIST_HEAD(script_descs);
2170 
2171 static struct script_desc *script_desc__new(const char *name)
2172 {
2173 	struct script_desc *s = zalloc(sizeof(*s));
2174 
2175 	if (s != NULL && name)
2176 		s->name = strdup(name);
2177 
2178 	return s;
2179 }
2180 
2181 static void script_desc__delete(struct script_desc *s)
2182 {
2183 	zfree(&s->name);
2184 	zfree(&s->half_liner);
2185 	zfree(&s->args);
2186 	free(s);
2187 }
2188 
2189 static void script_desc__add(struct script_desc *s)
2190 {
2191 	list_add_tail(&s->node, &script_descs);
2192 }
2193 
2194 static struct script_desc *script_desc__find(const char *name)
2195 {
2196 	struct script_desc *s;
2197 
2198 	list_for_each_entry(s, &script_descs, node)
2199 		if (strcasecmp(s->name, name) == 0)
2200 			return s;
2201 	return NULL;
2202 }
2203 
2204 static struct script_desc *script_desc__findnew(const char *name)
2205 {
2206 	struct script_desc *s = script_desc__find(name);
2207 
2208 	if (s)
2209 		return s;
2210 
2211 	s = script_desc__new(name);
2212 	if (!s)
2213 		return NULL;
2214 
2215 	script_desc__add(s);
2216 
2217 	return s;
2218 }
2219 
2220 static const char *ends_with(const char *str, const char *suffix)
2221 {
2222 	size_t suffix_len = strlen(suffix);
2223 	const char *p = str;
2224 
2225 	if (strlen(str) > suffix_len) {
2226 		p = str + strlen(str) - suffix_len;
2227 		if (!strncmp(p, suffix, suffix_len))
2228 			return p;
2229 	}
2230 
2231 	return NULL;
2232 }
2233 
2234 static int read_script_info(struct script_desc *desc, const char *filename)
2235 {
2236 	char line[BUFSIZ], *p;
2237 	FILE *fp;
2238 
2239 	fp = fopen(filename, "r");
2240 	if (!fp)
2241 		return -1;
2242 
2243 	while (fgets(line, sizeof(line), fp)) {
2244 		p = ltrim(line);
2245 		if (strlen(p) == 0)
2246 			continue;
2247 		if (*p != '#')
2248 			continue;
2249 		p++;
2250 		if (strlen(p) && *p == '!')
2251 			continue;
2252 
2253 		p = ltrim(p);
2254 		if (strlen(p) && p[strlen(p) - 1] == '\n')
2255 			p[strlen(p) - 1] = '\0';
2256 
2257 		if (!strncmp(p, "description:", strlen("description:"))) {
2258 			p += strlen("description:");
2259 			desc->half_liner = strdup(ltrim(p));
2260 			continue;
2261 		}
2262 
2263 		if (!strncmp(p, "args:", strlen("args:"))) {
2264 			p += strlen("args:");
2265 			desc->args = strdup(ltrim(p));
2266 			continue;
2267 		}
2268 	}
2269 
2270 	fclose(fp);
2271 
2272 	return 0;
2273 }
2274 
2275 static char *get_script_root(struct dirent *script_dirent, const char *suffix)
2276 {
2277 	char *script_root, *str;
2278 
2279 	script_root = strdup(script_dirent->d_name);
2280 	if (!script_root)
2281 		return NULL;
2282 
2283 	str = (char *)ends_with(script_root, suffix);
2284 	if (!str) {
2285 		free(script_root);
2286 		return NULL;
2287 	}
2288 
2289 	*str = '\0';
2290 	return script_root;
2291 }
2292 
2293 static int list_available_scripts(const struct option *opt __maybe_unused,
2294 				  const char *s __maybe_unused,
2295 				  int unset __maybe_unused)
2296 {
2297 	struct dirent *script_dirent, *lang_dirent;
2298 	char scripts_path[MAXPATHLEN];
2299 	DIR *scripts_dir, *lang_dir;
2300 	char script_path[MAXPATHLEN];
2301 	char lang_path[MAXPATHLEN];
2302 	struct script_desc *desc;
2303 	char first_half[BUFSIZ];
2304 	char *script_root;
2305 
2306 	snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2307 
2308 	scripts_dir = opendir(scripts_path);
2309 	if (!scripts_dir) {
2310 		fprintf(stdout,
2311 			"open(%s) failed.\n"
2312 			"Check \"PERF_EXEC_PATH\" env to set scripts dir.\n",
2313 			scripts_path);
2314 		exit(-1);
2315 	}
2316 
2317 	for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2318 		snprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
2319 			 lang_dirent->d_name);
2320 		lang_dir = opendir(lang_path);
2321 		if (!lang_dir)
2322 			continue;
2323 
2324 		for_each_script(lang_path, lang_dir, script_dirent) {
2325 			script_root = get_script_root(script_dirent, REPORT_SUFFIX);
2326 			if (script_root) {
2327 				desc = script_desc__findnew(script_root);
2328 				snprintf(script_path, MAXPATHLEN, "%s/%s",
2329 					 lang_path, script_dirent->d_name);
2330 				read_script_info(desc, script_path);
2331 				free(script_root);
2332 			}
2333 		}
2334 	}
2335 
2336 	fprintf(stdout, "List of available trace scripts:\n");
2337 	list_for_each_entry(desc, &script_descs, node) {
2338 		sprintf(first_half, "%s %s", desc->name,
2339 			desc->args ? desc->args : "");
2340 		fprintf(stdout, "  %-36s %s\n", first_half,
2341 			desc->half_liner ? desc->half_liner : "");
2342 	}
2343 
2344 	exit(0);
2345 }
2346 
2347 /*
2348  * Some scripts specify the required events in their "xxx-record" file,
2349  * this function will check if the events in perf.data match those
2350  * mentioned in the "xxx-record".
2351  *
2352  * Fixme: All existing "xxx-record" are all in good formats "-e event ",
2353  * which is covered well now. And new parsing code should be added to
2354  * cover the future complexing formats like event groups etc.
2355  */
2356 static int check_ev_match(char *dir_name, char *scriptname,
2357 			struct perf_session *session)
2358 {
2359 	char filename[MAXPATHLEN], evname[128];
2360 	char line[BUFSIZ], *p;
2361 	struct perf_evsel *pos;
2362 	int match, len;
2363 	FILE *fp;
2364 
2365 	sprintf(filename, "%s/bin/%s-record", dir_name, scriptname);
2366 
2367 	fp = fopen(filename, "r");
2368 	if (!fp)
2369 		return -1;
2370 
2371 	while (fgets(line, sizeof(line), fp)) {
2372 		p = ltrim(line);
2373 		if (*p == '#')
2374 			continue;
2375 
2376 		while (strlen(p)) {
2377 			p = strstr(p, "-e");
2378 			if (!p)
2379 				break;
2380 
2381 			p += 2;
2382 			p = ltrim(p);
2383 			len = strcspn(p, " \t");
2384 			if (!len)
2385 				break;
2386 
2387 			snprintf(evname, len + 1, "%s", p);
2388 
2389 			match = 0;
2390 			evlist__for_each_entry(session->evlist, pos) {
2391 				if (!strcmp(perf_evsel__name(pos), evname)) {
2392 					match = 1;
2393 					break;
2394 				}
2395 			}
2396 
2397 			if (!match) {
2398 				fclose(fp);
2399 				return -1;
2400 			}
2401 		}
2402 	}
2403 
2404 	fclose(fp);
2405 	return 0;
2406 }
2407 
2408 /*
2409  * Return -1 if none is found, otherwise the actual scripts number.
2410  *
2411  * Currently the only user of this function is the script browser, which
2412  * will list all statically runnable scripts, select one, execute it and
2413  * show the output in a perf browser.
2414  */
2415 int find_scripts(char **scripts_array, char **scripts_path_array)
2416 {
2417 	struct dirent *script_dirent, *lang_dirent;
2418 	char scripts_path[MAXPATHLEN], lang_path[MAXPATHLEN];
2419 	DIR *scripts_dir, *lang_dir;
2420 	struct perf_session *session;
2421 	struct perf_data_file file = {
2422 		.path = input_name,
2423 		.mode = PERF_DATA_MODE_READ,
2424 	};
2425 	char *temp;
2426 	int i = 0;
2427 
2428 	session = perf_session__new(&file, false, NULL);
2429 	if (!session)
2430 		return -1;
2431 
2432 	snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2433 
2434 	scripts_dir = opendir(scripts_path);
2435 	if (!scripts_dir) {
2436 		perf_session__delete(session);
2437 		return -1;
2438 	}
2439 
2440 	for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2441 		snprintf(lang_path, MAXPATHLEN, "%s/%s", scripts_path,
2442 			 lang_dirent->d_name);
2443 #ifdef NO_LIBPERL
2444 		if (strstr(lang_path, "perl"))
2445 			continue;
2446 #endif
2447 #ifdef NO_LIBPYTHON
2448 		if (strstr(lang_path, "python"))
2449 			continue;
2450 #endif
2451 
2452 		lang_dir = opendir(lang_path);
2453 		if (!lang_dir)
2454 			continue;
2455 
2456 		for_each_script(lang_path, lang_dir, script_dirent) {
2457 			/* Skip those real time scripts: xxxtop.p[yl] */
2458 			if (strstr(script_dirent->d_name, "top."))
2459 				continue;
2460 			sprintf(scripts_path_array[i], "%s/%s", lang_path,
2461 				script_dirent->d_name);
2462 			temp = strchr(script_dirent->d_name, '.');
2463 			snprintf(scripts_array[i],
2464 				(temp - script_dirent->d_name) + 1,
2465 				"%s", script_dirent->d_name);
2466 
2467 			if (check_ev_match(lang_path,
2468 					scripts_array[i], session))
2469 				continue;
2470 
2471 			i++;
2472 		}
2473 		closedir(lang_dir);
2474 	}
2475 
2476 	closedir(scripts_dir);
2477 	perf_session__delete(session);
2478 	return i;
2479 }
2480 
2481 static char *get_script_path(const char *script_root, const char *suffix)
2482 {
2483 	struct dirent *script_dirent, *lang_dirent;
2484 	char scripts_path[MAXPATHLEN];
2485 	char script_path[MAXPATHLEN];
2486 	DIR *scripts_dir, *lang_dir;
2487 	char lang_path[MAXPATHLEN];
2488 	char *__script_root;
2489 
2490 	snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2491 
2492 	scripts_dir = opendir(scripts_path);
2493 	if (!scripts_dir)
2494 		return NULL;
2495 
2496 	for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2497 		snprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
2498 			 lang_dirent->d_name);
2499 		lang_dir = opendir(lang_path);
2500 		if (!lang_dir)
2501 			continue;
2502 
2503 		for_each_script(lang_path, lang_dir, script_dirent) {
2504 			__script_root = get_script_root(script_dirent, suffix);
2505 			if (__script_root && !strcmp(script_root, __script_root)) {
2506 				free(__script_root);
2507 				closedir(lang_dir);
2508 				closedir(scripts_dir);
2509 				snprintf(script_path, MAXPATHLEN, "%s/%s",
2510 					 lang_path, script_dirent->d_name);
2511 				return strdup(script_path);
2512 			}
2513 			free(__script_root);
2514 		}
2515 		closedir(lang_dir);
2516 	}
2517 	closedir(scripts_dir);
2518 
2519 	return NULL;
2520 }
2521 
2522 static bool is_top_script(const char *script_path)
2523 {
2524 	return ends_with(script_path, "top") == NULL ? false : true;
2525 }
2526 
2527 static int has_required_arg(char *script_path)
2528 {
2529 	struct script_desc *desc;
2530 	int n_args = 0;
2531 	char *p;
2532 
2533 	desc = script_desc__new(NULL);
2534 
2535 	if (read_script_info(desc, script_path))
2536 		goto out;
2537 
2538 	if (!desc->args)
2539 		goto out;
2540 
2541 	for (p = desc->args; *p; p++)
2542 		if (*p == '<')
2543 			n_args++;
2544 out:
2545 	script_desc__delete(desc);
2546 
2547 	return n_args;
2548 }
2549 
2550 static int have_cmd(int argc, const char **argv)
2551 {
2552 	char **__argv = malloc(sizeof(const char *) * argc);
2553 
2554 	if (!__argv) {
2555 		pr_err("malloc failed\n");
2556 		return -1;
2557 	}
2558 
2559 	memcpy(__argv, argv, sizeof(const char *) * argc);
2560 	argc = parse_options(argc, (const char **)__argv, record_options,
2561 			     NULL, PARSE_OPT_STOP_AT_NON_OPTION);
2562 	free(__argv);
2563 
2564 	system_wide = (argc == 0);
2565 
2566 	return 0;
2567 }
2568 
2569 static void script__setup_sample_type(struct perf_script *script)
2570 {
2571 	struct perf_session *session = script->session;
2572 	u64 sample_type = perf_evlist__combined_sample_type(session->evlist);
2573 
2574 	if (symbol_conf.use_callchain || symbol_conf.cumulate_callchain) {
2575 		if ((sample_type & PERF_SAMPLE_REGS_USER) &&
2576 		    (sample_type & PERF_SAMPLE_STACK_USER))
2577 			callchain_param.record_mode = CALLCHAIN_DWARF;
2578 		else if (sample_type & PERF_SAMPLE_BRANCH_STACK)
2579 			callchain_param.record_mode = CALLCHAIN_LBR;
2580 		else
2581 			callchain_param.record_mode = CALLCHAIN_FP;
2582 	}
2583 }
2584 
2585 static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
2586 				    union perf_event *event,
2587 				    struct perf_session *session)
2588 {
2589 	struct stat_round_event *round = &event->stat_round;
2590 	struct perf_evsel *counter;
2591 
2592 	evlist__for_each_entry(session->evlist, counter) {
2593 		perf_stat_process_counter(&stat_config, counter);
2594 		process_stat(counter, round->time);
2595 	}
2596 
2597 	process_stat_interval(round->time);
2598 	return 0;
2599 }
2600 
2601 static int process_stat_config_event(struct perf_tool *tool __maybe_unused,
2602 				     union perf_event *event,
2603 				     struct perf_session *session __maybe_unused)
2604 {
2605 	perf_event__read_stat_config(&stat_config, &event->stat_config);
2606 	return 0;
2607 }
2608 
2609 static int set_maps(struct perf_script *script)
2610 {
2611 	struct perf_evlist *evlist = script->session->evlist;
2612 
2613 	if (!script->cpus || !script->threads)
2614 		return 0;
2615 
2616 	if (WARN_ONCE(script->allocated, "stats double allocation\n"))
2617 		return -EINVAL;
2618 
2619 	perf_evlist__set_maps(evlist, script->cpus, script->threads);
2620 
2621 	if (perf_evlist__alloc_stats(evlist, true))
2622 		return -ENOMEM;
2623 
2624 	script->allocated = true;
2625 	return 0;
2626 }
2627 
2628 static
2629 int process_thread_map_event(struct perf_tool *tool,
2630 			     union perf_event *event,
2631 			     struct perf_session *session __maybe_unused)
2632 {
2633 	struct perf_script *script = container_of(tool, struct perf_script, tool);
2634 
2635 	if (script->threads) {
2636 		pr_warning("Extra thread map event, ignoring.\n");
2637 		return 0;
2638 	}
2639 
2640 	script->threads = thread_map__new_event(&event->thread_map);
2641 	if (!script->threads)
2642 		return -ENOMEM;
2643 
2644 	return set_maps(script);
2645 }
2646 
2647 static
2648 int process_cpu_map_event(struct perf_tool *tool __maybe_unused,
2649 			  union perf_event *event,
2650 			  struct perf_session *session __maybe_unused)
2651 {
2652 	struct perf_script *script = container_of(tool, struct perf_script, tool);
2653 
2654 	if (script->cpus) {
2655 		pr_warning("Extra cpu map event, ignoring.\n");
2656 		return 0;
2657 	}
2658 
2659 	script->cpus = cpu_map__new_data(&event->cpu_map.data);
2660 	if (!script->cpus)
2661 		return -ENOMEM;
2662 
2663 	return set_maps(script);
2664 }
2665 
2666 int cmd_script(int argc, const char **argv)
2667 {
2668 	bool show_full_info = false;
2669 	bool header = false;
2670 	bool header_only = false;
2671 	bool script_started = false;
2672 	char *rec_script_path = NULL;
2673 	char *rep_script_path = NULL;
2674 	struct perf_session *session;
2675 	struct itrace_synth_opts itrace_synth_opts = { .set = false, };
2676 	char *script_path = NULL;
2677 	const char **__argv;
2678 	int i, j, err = 0;
2679 	struct perf_script script = {
2680 		.tool = {
2681 			.sample		 = process_sample_event,
2682 			.mmap		 = perf_event__process_mmap,
2683 			.mmap2		 = perf_event__process_mmap2,
2684 			.comm		 = perf_event__process_comm,
2685 			.namespaces	 = perf_event__process_namespaces,
2686 			.exit		 = perf_event__process_exit,
2687 			.fork		 = perf_event__process_fork,
2688 			.attr		 = process_attr,
2689 			.event_update   = perf_event__process_event_update,
2690 			.tracing_data	 = perf_event__process_tracing_data,
2691 			.feature	 = perf_event__process_feature,
2692 			.build_id	 = perf_event__process_build_id,
2693 			.id_index	 = perf_event__process_id_index,
2694 			.auxtrace_info	 = perf_event__process_auxtrace_info,
2695 			.auxtrace	 = perf_event__process_auxtrace,
2696 			.auxtrace_error	 = perf_event__process_auxtrace_error,
2697 			.stat		 = perf_event__process_stat_event,
2698 			.stat_round	 = process_stat_round_event,
2699 			.stat_config	 = process_stat_config_event,
2700 			.thread_map	 = process_thread_map_event,
2701 			.cpu_map	 = process_cpu_map_event,
2702 			.ordered_events	 = true,
2703 			.ordering_requires_timestamps = true,
2704 		},
2705 	};
2706 	struct perf_data_file file = {
2707 		.mode = PERF_DATA_MODE_READ,
2708 	};
2709 	const struct option options[] = {
2710 	OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
2711 		    "dump raw trace in ASCII"),
2712 	OPT_INCR('v', "verbose", &verbose,
2713 		 "be more verbose (show symbol address, etc)"),
2714 	OPT_BOOLEAN('L', "Latency", &latency_format,
2715 		    "show latency attributes (irqs/preemption disabled, etc)"),
2716 	OPT_CALLBACK_NOOPT('l', "list", NULL, NULL, "list available scripts",
2717 			   list_available_scripts),
2718 	OPT_CALLBACK('s', "script", NULL, "name",
2719 		     "script file name (lang:script name, script name, or *)",
2720 		     parse_scriptname),
2721 	OPT_STRING('g', "gen-script", &generate_script_lang, "lang",
2722 		   "generate perf-script.xx script in specified language"),
2723 	OPT_STRING('i', "input", &input_name, "file", "input file name"),
2724 	OPT_BOOLEAN('d', "debug-mode", &debug_mode,
2725 		   "do various checks like samples ordering and lost events"),
2726 	OPT_BOOLEAN(0, "header", &header, "Show data header."),
2727 	OPT_BOOLEAN(0, "header-only", &header_only, "Show only data header."),
2728 	OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
2729 		   "file", "vmlinux pathname"),
2730 	OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
2731 		   "file", "kallsyms pathname"),
2732 	OPT_BOOLEAN('G', "hide-call-graph", &no_callchain,
2733 		    "When printing symbols do not display call chain"),
2734 	OPT_CALLBACK(0, "symfs", NULL, "directory",
2735 		     "Look for files with symbols relative to this directory",
2736 		     symbol__config_symfs),
2737 	OPT_CALLBACK('F', "fields", NULL, "str",
2738 		     "comma separated output fields prepend with 'type:'. "
2739 		     "+field to add and -field to remove."
2740 		     "Valid types: hw,sw,trace,raw,synth. "
2741 		     "Fields: comm,tid,pid,time,cpu,event,trace,ip,sym,dso,"
2742 		     "addr,symoff,period,iregs,brstack,brstacksym,flags,"
2743 		     "bpf-output,callindent,insn,insnlen,brstackinsn,synth,phys_addr",
2744 		     parse_output_fields),
2745 	OPT_BOOLEAN('a', "all-cpus", &system_wide,
2746 		    "system-wide collection from all CPUs"),
2747 	OPT_STRING('S', "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
2748 		   "only consider these symbols"),
2749 	OPT_STRING(0, "stop-bt", &symbol_conf.bt_stop_list_str, "symbol[,symbol...]",
2750 		   "Stop display of callgraph at these symbols"),
2751 	OPT_STRING('C', "cpu", &cpu_list, "cpu", "list of cpus to profile"),
2752 	OPT_STRING('c', "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
2753 		   "only display events for these comms"),
2754 	OPT_STRING(0, "pid", &symbol_conf.pid_list_str, "pid[,pid...]",
2755 		   "only consider symbols in these pids"),
2756 	OPT_STRING(0, "tid", &symbol_conf.tid_list_str, "tid[,tid...]",
2757 		   "only consider symbols in these tids"),
2758 	OPT_UINTEGER(0, "max-stack", &scripting_max_stack,
2759 		     "Set the maximum stack depth when parsing the callchain, "
2760 		     "anything beyond the specified depth will be ignored. "
2761 		     "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
2762 	OPT_BOOLEAN('I', "show-info", &show_full_info,
2763 		    "display extended information from perf.data file"),
2764 	OPT_BOOLEAN('\0', "show-kernel-path", &symbol_conf.show_kernel_path,
2765 		    "Show the path of [kernel.kallsyms]"),
2766 	OPT_BOOLEAN('\0', "show-task-events", &script.show_task_events,
2767 		    "Show the fork/comm/exit events"),
2768 	OPT_BOOLEAN('\0', "show-mmap-events", &script.show_mmap_events,
2769 		    "Show the mmap events"),
2770 	OPT_BOOLEAN('\0', "show-switch-events", &script.show_switch_events,
2771 		    "Show context switch events (if recorded)"),
2772 	OPT_BOOLEAN('\0', "show-namespace-events", &script.show_namespace_events,
2773 		    "Show namespace events (if recorded)"),
2774 	OPT_BOOLEAN('f', "force", &symbol_conf.force, "don't complain, do it"),
2775 	OPT_INTEGER(0, "max-blocks", &max_blocks,
2776 		    "Maximum number of code blocks to dump with brstackinsn"),
2777 	OPT_BOOLEAN(0, "ns", &nanosecs,
2778 		    "Use 9 decimal places when displaying time"),
2779 	OPT_CALLBACK_OPTARG(0, "itrace", &itrace_synth_opts, NULL, "opts",
2780 			    "Instruction Tracing options",
2781 			    itrace_parse_synth_opts),
2782 	OPT_BOOLEAN(0, "full-source-path", &srcline_full_filename,
2783 			"Show full source file name path for source lines"),
2784 	OPT_BOOLEAN(0, "demangle", &symbol_conf.demangle,
2785 			"Enable symbol demangling"),
2786 	OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel,
2787 			"Enable kernel symbol demangling"),
2788 	OPT_STRING(0, "time", &script.time_str, "str",
2789 		   "Time span of interest (start,stop)"),
2790 	OPT_BOOLEAN(0, "inline", &symbol_conf.inline_name,
2791 		    "Show inline function"),
2792 	OPT_END()
2793 	};
2794 	const char * const script_subcommands[] = { "record", "report", NULL };
2795 	const char *script_usage[] = {
2796 		"perf script [<options>]",
2797 		"perf script [<options>] record <script> [<record-options>] <command>",
2798 		"perf script [<options>] report <script> [script-args]",
2799 		"perf script [<options>] <script> [<record-options>] <command>",
2800 		"perf script [<options>] <top-script> [script-args]",
2801 		NULL
2802 	};
2803 
2804 	setup_scripting();
2805 
2806 	argc = parse_options_subcommand(argc, argv, options, script_subcommands, script_usage,
2807 			     PARSE_OPT_STOP_AT_NON_OPTION);
2808 
2809 	file.path = input_name;
2810 	file.force = symbol_conf.force;
2811 
2812 	if (argc > 1 && !strncmp(argv[0], "rec", strlen("rec"))) {
2813 		rec_script_path = get_script_path(argv[1], RECORD_SUFFIX);
2814 		if (!rec_script_path)
2815 			return cmd_record(argc, argv);
2816 	}
2817 
2818 	if (argc > 1 && !strncmp(argv[0], "rep", strlen("rep"))) {
2819 		rep_script_path = get_script_path(argv[1], REPORT_SUFFIX);
2820 		if (!rep_script_path) {
2821 			fprintf(stderr,
2822 				"Please specify a valid report script"
2823 				"(see 'perf script -l' for listing)\n");
2824 			return -1;
2825 		}
2826 	}
2827 
2828 	if (itrace_synth_opts.callchain &&
2829 	    itrace_synth_opts.callchain_sz > scripting_max_stack)
2830 		scripting_max_stack = itrace_synth_opts.callchain_sz;
2831 
2832 	/* make sure PERF_EXEC_PATH is set for scripts */
2833 	set_argv_exec_path(get_argv_exec_path());
2834 
2835 	if (argc && !script_name && !rec_script_path && !rep_script_path) {
2836 		int live_pipe[2];
2837 		int rep_args;
2838 		pid_t pid;
2839 
2840 		rec_script_path = get_script_path(argv[0], RECORD_SUFFIX);
2841 		rep_script_path = get_script_path(argv[0], REPORT_SUFFIX);
2842 
2843 		if (!rec_script_path && !rep_script_path) {
2844 			usage_with_options_msg(script_usage, options,
2845 				"Couldn't find script `%s'\n\n See perf"
2846 				" script -l for available scripts.\n", argv[0]);
2847 		}
2848 
2849 		if (is_top_script(argv[0])) {
2850 			rep_args = argc - 1;
2851 		} else {
2852 			int rec_args;
2853 
2854 			rep_args = has_required_arg(rep_script_path);
2855 			rec_args = (argc - 1) - rep_args;
2856 			if (rec_args < 0) {
2857 				usage_with_options_msg(script_usage, options,
2858 					"`%s' script requires options."
2859 					"\n\n See perf script -l for available "
2860 					"scripts and options.\n", argv[0]);
2861 			}
2862 		}
2863 
2864 		if (pipe(live_pipe) < 0) {
2865 			perror("failed to create pipe");
2866 			return -1;
2867 		}
2868 
2869 		pid = fork();
2870 		if (pid < 0) {
2871 			perror("failed to fork");
2872 			return -1;
2873 		}
2874 
2875 		if (!pid) {
2876 			j = 0;
2877 
2878 			dup2(live_pipe[1], 1);
2879 			close(live_pipe[0]);
2880 
2881 			if (is_top_script(argv[0])) {
2882 				system_wide = true;
2883 			} else if (!system_wide) {
2884 				if (have_cmd(argc - rep_args, &argv[rep_args]) != 0) {
2885 					err = -1;
2886 					goto out;
2887 				}
2888 			}
2889 
2890 			__argv = malloc((argc + 6) * sizeof(const char *));
2891 			if (!__argv) {
2892 				pr_err("malloc failed\n");
2893 				err = -ENOMEM;
2894 				goto out;
2895 			}
2896 
2897 			__argv[j++] = "/bin/sh";
2898 			__argv[j++] = rec_script_path;
2899 			if (system_wide)
2900 				__argv[j++] = "-a";
2901 			__argv[j++] = "-q";
2902 			__argv[j++] = "-o";
2903 			__argv[j++] = "-";
2904 			for (i = rep_args + 1; i < argc; i++)
2905 				__argv[j++] = argv[i];
2906 			__argv[j++] = NULL;
2907 
2908 			execvp("/bin/sh", (char **)__argv);
2909 			free(__argv);
2910 			exit(-1);
2911 		}
2912 
2913 		dup2(live_pipe[0], 0);
2914 		close(live_pipe[1]);
2915 
2916 		__argv = malloc((argc + 4) * sizeof(const char *));
2917 		if (!__argv) {
2918 			pr_err("malloc failed\n");
2919 			err = -ENOMEM;
2920 			goto out;
2921 		}
2922 
2923 		j = 0;
2924 		__argv[j++] = "/bin/sh";
2925 		__argv[j++] = rep_script_path;
2926 		for (i = 1; i < rep_args + 1; i++)
2927 			__argv[j++] = argv[i];
2928 		__argv[j++] = "-i";
2929 		__argv[j++] = "-";
2930 		__argv[j++] = NULL;
2931 
2932 		execvp("/bin/sh", (char **)__argv);
2933 		free(__argv);
2934 		exit(-1);
2935 	}
2936 
2937 	if (rec_script_path)
2938 		script_path = rec_script_path;
2939 	if (rep_script_path)
2940 		script_path = rep_script_path;
2941 
2942 	if (script_path) {
2943 		j = 0;
2944 
2945 		if (!rec_script_path)
2946 			system_wide = false;
2947 		else if (!system_wide) {
2948 			if (have_cmd(argc - 1, &argv[1]) != 0) {
2949 				err = -1;
2950 				goto out;
2951 			}
2952 		}
2953 
2954 		__argv = malloc((argc + 2) * sizeof(const char *));
2955 		if (!__argv) {
2956 			pr_err("malloc failed\n");
2957 			err = -ENOMEM;
2958 			goto out;
2959 		}
2960 
2961 		__argv[j++] = "/bin/sh";
2962 		__argv[j++] = script_path;
2963 		if (system_wide)
2964 			__argv[j++] = "-a";
2965 		for (i = 2; i < argc; i++)
2966 			__argv[j++] = argv[i];
2967 		__argv[j++] = NULL;
2968 
2969 		execvp("/bin/sh", (char **)__argv);
2970 		free(__argv);
2971 		exit(-1);
2972 	}
2973 
2974 	if (!script_name)
2975 		setup_pager();
2976 
2977 	session = perf_session__new(&file, false, &script.tool);
2978 	if (session == NULL)
2979 		return -1;
2980 
2981 	if (header || header_only) {
2982 		script.tool.show_feat_hdr = SHOW_FEAT_HEADER;
2983 		perf_session__fprintf_info(session, stdout, show_full_info);
2984 		if (header_only)
2985 			goto out_delete;
2986 	}
2987 	if (show_full_info)
2988 		script.tool.show_feat_hdr = SHOW_FEAT_HEADER_FULL_INFO;
2989 
2990 	if (symbol__init(&session->header.env) < 0)
2991 		goto out_delete;
2992 
2993 	script.session = session;
2994 	script__setup_sample_type(&script);
2995 
2996 	if (output[PERF_TYPE_HARDWARE].fields & PERF_OUTPUT_CALLINDENT)
2997 		itrace_synth_opts.thread_stack = true;
2998 
2999 	session->itrace_synth_opts = &itrace_synth_opts;
3000 
3001 	if (cpu_list) {
3002 		err = perf_session__cpu_bitmap(session, cpu_list, cpu_bitmap);
3003 		if (err < 0)
3004 			goto out_delete;
3005 		itrace_synth_opts.cpu_bitmap = cpu_bitmap;
3006 	}
3007 
3008 	if (!no_callchain)
3009 		symbol_conf.use_callchain = true;
3010 	else
3011 		symbol_conf.use_callchain = false;
3012 
3013 	if (session->tevent.pevent &&
3014 	    pevent_set_function_resolver(session->tevent.pevent,
3015 					 machine__resolve_kernel_addr,
3016 					 &session->machines.host) < 0) {
3017 		pr_err("%s: failed to set libtraceevent function resolver\n", __func__);
3018 		return -1;
3019 	}
3020 
3021 	if (generate_script_lang) {
3022 		struct stat perf_stat;
3023 		int input;
3024 
3025 		if (output_set_by_user()) {
3026 			fprintf(stderr,
3027 				"custom fields not supported for generated scripts");
3028 			err = -EINVAL;
3029 			goto out_delete;
3030 		}
3031 
3032 		input = open(file.path, O_RDONLY);	/* input_name */
3033 		if (input < 0) {
3034 			err = -errno;
3035 			perror("failed to open file");
3036 			goto out_delete;
3037 		}
3038 
3039 		err = fstat(input, &perf_stat);
3040 		if (err < 0) {
3041 			perror("failed to stat file");
3042 			goto out_delete;
3043 		}
3044 
3045 		if (!perf_stat.st_size) {
3046 			fprintf(stderr, "zero-sized file, nothing to do!\n");
3047 			goto out_delete;
3048 		}
3049 
3050 		scripting_ops = script_spec__lookup(generate_script_lang);
3051 		if (!scripting_ops) {
3052 			fprintf(stderr, "invalid language specifier");
3053 			err = -ENOENT;
3054 			goto out_delete;
3055 		}
3056 
3057 		err = scripting_ops->generate_script(session->tevent.pevent,
3058 						     "perf-script");
3059 		goto out_delete;
3060 	}
3061 
3062 	if (script_name) {
3063 		err = scripting_ops->start_script(script_name, argc, argv);
3064 		if (err)
3065 			goto out_delete;
3066 		pr_debug("perf script started with script %s\n\n", script_name);
3067 		script_started = true;
3068 	}
3069 
3070 
3071 	err = perf_session__check_output_opt(session);
3072 	if (err < 0)
3073 		goto out_delete;
3074 
3075 	/* needs to be parsed after looking up reference time */
3076 	if (perf_time__parse_str(&script.ptime, script.time_str) != 0) {
3077 		pr_err("Invalid time string\n");
3078 		return -EINVAL;
3079 	}
3080 
3081 	err = __cmd_script(&script);
3082 
3083 	flush_scripting();
3084 
3085 out_delete:
3086 	perf_evlist__free_stats(session->evlist);
3087 	perf_session__delete(session);
3088 
3089 	if (script_started)
3090 		cleanup_scripting();
3091 out:
3092 	return err;
3093 }
3094