xref: /linux/tools/perf/builtin-script.c (revision 42fc2e9ef9603a7948aaa4ffd8dfb94b30294ad8)
1 // SPDX-License-Identifier: GPL-2.0
2 #include "builtin.h"
3 
4 #include "perf.h"
5 #include "util/cache.h"
6 #include "util/debug.h"
7 #include <subcmd/exec-cmd.h>
8 #include "util/header.h"
9 #include <subcmd/parse-options.h>
10 #include "util/perf_regs.h"
11 #include "util/session.h"
12 #include "util/tool.h"
13 #include "util/map.h"
14 #include "util/symbol.h"
15 #include "util/thread.h"
16 #include "util/trace-event.h"
17 #include "util/evlist.h"
18 #include "util/evsel.h"
19 #include "util/evswitch.h"
20 #include "util/sort.h"
21 #include "util/data.h"
22 #include "util/auxtrace.h"
23 #include "util/cpumap.h"
24 #include "util/thread_map.h"
25 #include "util/stat.h"
26 #include "util/color.h"
27 #include "util/string2.h"
28 #include "util/thread-stack.h"
29 #include "util/time-utils.h"
30 #include "util/path.h"
31 #include "print_binary.h"
32 #include "archinsn.h"
33 #include <linux/bitmap.h>
34 #include <linux/kernel.h>
35 #include <linux/stringify.h>
36 #include <linux/time64.h>
37 #include <linux/zalloc.h>
38 #include <sys/utsname.h>
39 #include "asm/bug.h"
40 #include "util/mem-events.h"
41 #include "util/dump-insn.h"
42 #include <dirent.h>
43 #include <errno.h>
44 #include <inttypes.h>
45 #include <signal.h>
46 #include <sys/param.h>
47 #include <sys/types.h>
48 #include <sys/stat.h>
49 #include <fcntl.h>
50 #include <unistd.h>
51 #include <subcmd/pager.h>
52 #include <perf/evlist.h>
53 
54 #include <linux/ctype.h>
55 
56 static char const		*script_name;
57 static char const		*generate_script_lang;
58 static bool			reltime;
59 static u64			initial_time;
60 static bool			debug_mode;
61 static u64			last_timestamp;
62 static u64			nr_unordered;
63 static bool			no_callchain;
64 static bool			latency_format;
65 static bool			system_wide;
66 static bool			print_flags;
67 static const char		*cpu_list;
68 static DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
69 static struct perf_stat_config	stat_config;
70 static int			max_blocks;
71 static bool			native_arch;
72 
73 unsigned int scripting_max_stack = PERF_MAX_STACK_DEPTH;
74 
75 enum perf_output_field {
76 	PERF_OUTPUT_COMM            = 1U << 0,
77 	PERF_OUTPUT_TID             = 1U << 1,
78 	PERF_OUTPUT_PID             = 1U << 2,
79 	PERF_OUTPUT_TIME            = 1U << 3,
80 	PERF_OUTPUT_CPU             = 1U << 4,
81 	PERF_OUTPUT_EVNAME          = 1U << 5,
82 	PERF_OUTPUT_TRACE           = 1U << 6,
83 	PERF_OUTPUT_IP              = 1U << 7,
84 	PERF_OUTPUT_SYM             = 1U << 8,
85 	PERF_OUTPUT_DSO             = 1U << 9,
86 	PERF_OUTPUT_ADDR            = 1U << 10,
87 	PERF_OUTPUT_SYMOFFSET       = 1U << 11,
88 	PERF_OUTPUT_SRCLINE         = 1U << 12,
89 	PERF_OUTPUT_PERIOD          = 1U << 13,
90 	PERF_OUTPUT_IREGS	    = 1U << 14,
91 	PERF_OUTPUT_BRSTACK	    = 1U << 15,
92 	PERF_OUTPUT_BRSTACKSYM	    = 1U << 16,
93 	PERF_OUTPUT_DATA_SRC	    = 1U << 17,
94 	PERF_OUTPUT_WEIGHT	    = 1U << 18,
95 	PERF_OUTPUT_BPF_OUTPUT	    = 1U << 19,
96 	PERF_OUTPUT_CALLINDENT	    = 1U << 20,
97 	PERF_OUTPUT_INSN	    = 1U << 21,
98 	PERF_OUTPUT_INSNLEN	    = 1U << 22,
99 	PERF_OUTPUT_BRSTACKINSN	    = 1U << 23,
100 	PERF_OUTPUT_BRSTACKOFF	    = 1U << 24,
101 	PERF_OUTPUT_SYNTH           = 1U << 25,
102 	PERF_OUTPUT_PHYS_ADDR       = 1U << 26,
103 	PERF_OUTPUT_UREGS	    = 1U << 27,
104 	PERF_OUTPUT_METRIC	    = 1U << 28,
105 	PERF_OUTPUT_MISC            = 1U << 29,
106 	PERF_OUTPUT_SRCCODE	    = 1U << 30,
107 	PERF_OUTPUT_IPC             = 1U << 31,
108 };
109 
110 struct output_option {
111 	const char *str;
112 	enum perf_output_field field;
113 } all_output_options[] = {
114 	{.str = "comm",  .field = PERF_OUTPUT_COMM},
115 	{.str = "tid",   .field = PERF_OUTPUT_TID},
116 	{.str = "pid",   .field = PERF_OUTPUT_PID},
117 	{.str = "time",  .field = PERF_OUTPUT_TIME},
118 	{.str = "cpu",   .field = PERF_OUTPUT_CPU},
119 	{.str = "event", .field = PERF_OUTPUT_EVNAME},
120 	{.str = "trace", .field = PERF_OUTPUT_TRACE},
121 	{.str = "ip",    .field = PERF_OUTPUT_IP},
122 	{.str = "sym",   .field = PERF_OUTPUT_SYM},
123 	{.str = "dso",   .field = PERF_OUTPUT_DSO},
124 	{.str = "addr",  .field = PERF_OUTPUT_ADDR},
125 	{.str = "symoff", .field = PERF_OUTPUT_SYMOFFSET},
126 	{.str = "srcline", .field = PERF_OUTPUT_SRCLINE},
127 	{.str = "period", .field = PERF_OUTPUT_PERIOD},
128 	{.str = "iregs", .field = PERF_OUTPUT_IREGS},
129 	{.str = "uregs", .field = PERF_OUTPUT_UREGS},
130 	{.str = "brstack", .field = PERF_OUTPUT_BRSTACK},
131 	{.str = "brstacksym", .field = PERF_OUTPUT_BRSTACKSYM},
132 	{.str = "data_src", .field = PERF_OUTPUT_DATA_SRC},
133 	{.str = "weight",   .field = PERF_OUTPUT_WEIGHT},
134 	{.str = "bpf-output",   .field = PERF_OUTPUT_BPF_OUTPUT},
135 	{.str = "callindent", .field = PERF_OUTPUT_CALLINDENT},
136 	{.str = "insn", .field = PERF_OUTPUT_INSN},
137 	{.str = "insnlen", .field = PERF_OUTPUT_INSNLEN},
138 	{.str = "brstackinsn", .field = PERF_OUTPUT_BRSTACKINSN},
139 	{.str = "brstackoff", .field = PERF_OUTPUT_BRSTACKOFF},
140 	{.str = "synth", .field = PERF_OUTPUT_SYNTH},
141 	{.str = "phys_addr", .field = PERF_OUTPUT_PHYS_ADDR},
142 	{.str = "metric", .field = PERF_OUTPUT_METRIC},
143 	{.str = "misc", .field = PERF_OUTPUT_MISC},
144 	{.str = "srccode", .field = PERF_OUTPUT_SRCCODE},
145 	{.str = "ipc", .field = PERF_OUTPUT_IPC},
146 };
147 
148 enum {
149 	OUTPUT_TYPE_SYNTH = PERF_TYPE_MAX,
150 	OUTPUT_TYPE_MAX
151 };
152 
153 /* default set to maintain compatibility with current format */
154 static struct {
155 	bool user_set;
156 	bool wildcard_set;
157 	unsigned int print_ip_opts;
158 	u64 fields;
159 	u64 invalid_fields;
160 	u64 user_set_fields;
161 } output[OUTPUT_TYPE_MAX] = {
162 
163 	[PERF_TYPE_HARDWARE] = {
164 		.user_set = false,
165 
166 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
167 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
168 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
169 			      PERF_OUTPUT_SYM | PERF_OUTPUT_SYMOFFSET |
170 			      PERF_OUTPUT_DSO | PERF_OUTPUT_PERIOD,
171 
172 		.invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
173 	},
174 
175 	[PERF_TYPE_SOFTWARE] = {
176 		.user_set = false,
177 
178 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
179 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
180 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
181 			      PERF_OUTPUT_SYM | PERF_OUTPUT_SYMOFFSET |
182 			      PERF_OUTPUT_DSO | PERF_OUTPUT_PERIOD |
183 			      PERF_OUTPUT_BPF_OUTPUT,
184 
185 		.invalid_fields = PERF_OUTPUT_TRACE,
186 	},
187 
188 	[PERF_TYPE_TRACEPOINT] = {
189 		.user_set = false,
190 
191 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
192 				  PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
193 				  PERF_OUTPUT_EVNAME | PERF_OUTPUT_TRACE
194 	},
195 
196 	[PERF_TYPE_HW_CACHE] = {
197 		.user_set = false,
198 
199 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
200 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
201 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
202 			      PERF_OUTPUT_SYM | PERF_OUTPUT_SYMOFFSET |
203 			      PERF_OUTPUT_DSO | PERF_OUTPUT_PERIOD,
204 
205 		.invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
206 	},
207 
208 	[PERF_TYPE_RAW] = {
209 		.user_set = false,
210 
211 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
212 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
213 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
214 			      PERF_OUTPUT_SYM | PERF_OUTPUT_SYMOFFSET |
215 			      PERF_OUTPUT_DSO | PERF_OUTPUT_PERIOD |
216 			      PERF_OUTPUT_ADDR | PERF_OUTPUT_DATA_SRC |
217 			      PERF_OUTPUT_WEIGHT | PERF_OUTPUT_PHYS_ADDR,
218 
219 		.invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
220 	},
221 
222 	[PERF_TYPE_BREAKPOINT] = {
223 		.user_set = false,
224 
225 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
226 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
227 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
228 			      PERF_OUTPUT_SYM | PERF_OUTPUT_SYMOFFSET |
229 			      PERF_OUTPUT_DSO | PERF_OUTPUT_PERIOD,
230 
231 		.invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
232 	},
233 
234 	[OUTPUT_TYPE_SYNTH] = {
235 		.user_set = false,
236 
237 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
238 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
239 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
240 			      PERF_OUTPUT_SYM | PERF_OUTPUT_SYMOFFSET |
241 			      PERF_OUTPUT_DSO | PERF_OUTPUT_SYNTH,
242 
243 		.invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
244 	},
245 };
246 
247 struct evsel_script {
248        char *filename;
249        FILE *fp;
250        u64  samples;
251        /* For metric output */
252        u64  val;
253        int  gnum;
254 };
255 
256 static inline struct evsel_script *evsel_script(struct evsel *evsel)
257 {
258 	return (struct evsel_script *)evsel->priv;
259 }
260 
261 static struct evsel_script *perf_evsel_script__new(struct evsel *evsel,
262 							struct perf_data *data)
263 {
264 	struct evsel_script *es = zalloc(sizeof(*es));
265 
266 	if (es != NULL) {
267 		if (asprintf(&es->filename, "%s.%s.dump", data->file.path, perf_evsel__name(evsel)) < 0)
268 			goto out_free;
269 		es->fp = fopen(es->filename, "w");
270 		if (es->fp == NULL)
271 			goto out_free_filename;
272 	}
273 
274 	return es;
275 out_free_filename:
276 	zfree(&es->filename);
277 out_free:
278 	free(es);
279 	return NULL;
280 }
281 
282 static void perf_evsel_script__delete(struct evsel_script *es)
283 {
284 	zfree(&es->filename);
285 	fclose(es->fp);
286 	es->fp = NULL;
287 	free(es);
288 }
289 
290 static int perf_evsel_script__fprintf(struct evsel_script *es, FILE *fp)
291 {
292 	struct stat st;
293 
294 	fstat(fileno(es->fp), &st);
295 	return fprintf(fp, "[ perf script: Wrote %.3f MB %s (%" PRIu64 " samples) ]\n",
296 		       st.st_size / 1024.0 / 1024.0, es->filename, es->samples);
297 }
298 
299 static inline int output_type(unsigned int type)
300 {
301 	switch (type) {
302 	case PERF_TYPE_SYNTH:
303 		return OUTPUT_TYPE_SYNTH;
304 	default:
305 		return type;
306 	}
307 }
308 
309 static inline unsigned int attr_type(unsigned int type)
310 {
311 	switch (type) {
312 	case OUTPUT_TYPE_SYNTH:
313 		return PERF_TYPE_SYNTH;
314 	default:
315 		return type;
316 	}
317 }
318 
319 static bool output_set_by_user(void)
320 {
321 	int j;
322 	for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
323 		if (output[j].user_set)
324 			return true;
325 	}
326 	return false;
327 }
328 
329 static const char *output_field2str(enum perf_output_field field)
330 {
331 	int i, imax = ARRAY_SIZE(all_output_options);
332 	const char *str = "";
333 
334 	for (i = 0; i < imax; ++i) {
335 		if (all_output_options[i].field == field) {
336 			str = all_output_options[i].str;
337 			break;
338 		}
339 	}
340 	return str;
341 }
342 
343 #define PRINT_FIELD(x)  (output[output_type(attr->type)].fields & PERF_OUTPUT_##x)
344 
345 static int perf_evsel__do_check_stype(struct evsel *evsel,
346 				      u64 sample_type, const char *sample_msg,
347 				      enum perf_output_field field,
348 				      bool allow_user_set)
349 {
350 	struct perf_event_attr *attr = &evsel->core.attr;
351 	int type = output_type(attr->type);
352 	const char *evname;
353 
354 	if (attr->sample_type & sample_type)
355 		return 0;
356 
357 	if (output[type].user_set_fields & field) {
358 		if (allow_user_set)
359 			return 0;
360 		evname = perf_evsel__name(evsel);
361 		pr_err("Samples for '%s' event do not have %s attribute set. "
362 		       "Cannot print '%s' field.\n",
363 		       evname, sample_msg, output_field2str(field));
364 		return -1;
365 	}
366 
367 	/* user did not ask for it explicitly so remove from the default list */
368 	output[type].fields &= ~field;
369 	evname = perf_evsel__name(evsel);
370 	pr_debug("Samples for '%s' event do not have %s attribute set. "
371 		 "Skipping '%s' field.\n",
372 		 evname, sample_msg, output_field2str(field));
373 
374 	return 0;
375 }
376 
377 static int perf_evsel__check_stype(struct evsel *evsel,
378 				   u64 sample_type, const char *sample_msg,
379 				   enum perf_output_field field)
380 {
381 	return perf_evsel__do_check_stype(evsel, sample_type, sample_msg, field,
382 					  false);
383 }
384 
385 static int perf_evsel__check_attr(struct evsel *evsel,
386 				  struct perf_session *session)
387 {
388 	struct perf_event_attr *attr = &evsel->core.attr;
389 	bool allow_user_set;
390 
391 	if (perf_header__has_feat(&session->header, HEADER_STAT))
392 		return 0;
393 
394 	allow_user_set = perf_header__has_feat(&session->header,
395 					       HEADER_AUXTRACE);
396 
397 	if (PRINT_FIELD(TRACE) &&
398 		!perf_session__has_traces(session, "record -R"))
399 		return -EINVAL;
400 
401 	if (PRINT_FIELD(IP)) {
402 		if (perf_evsel__check_stype(evsel, PERF_SAMPLE_IP, "IP",
403 					    PERF_OUTPUT_IP))
404 			return -EINVAL;
405 	}
406 
407 	if (PRINT_FIELD(ADDR) &&
408 		perf_evsel__do_check_stype(evsel, PERF_SAMPLE_ADDR, "ADDR",
409 					   PERF_OUTPUT_ADDR, allow_user_set))
410 		return -EINVAL;
411 
412 	if (PRINT_FIELD(DATA_SRC) &&
413 		perf_evsel__check_stype(evsel, PERF_SAMPLE_DATA_SRC, "DATA_SRC",
414 					PERF_OUTPUT_DATA_SRC))
415 		return -EINVAL;
416 
417 	if (PRINT_FIELD(WEIGHT) &&
418 		perf_evsel__check_stype(evsel, PERF_SAMPLE_WEIGHT, "WEIGHT",
419 					PERF_OUTPUT_WEIGHT))
420 		return -EINVAL;
421 
422 	if (PRINT_FIELD(SYM) &&
423 		!(evsel->core.attr.sample_type & (PERF_SAMPLE_IP|PERF_SAMPLE_ADDR))) {
424 		pr_err("Display of symbols requested but neither sample IP nor "
425 			   "sample address\navailable. Hence, no addresses to convert "
426 		       "to symbols.\n");
427 		return -EINVAL;
428 	}
429 	if (PRINT_FIELD(SYMOFFSET) && !PRINT_FIELD(SYM)) {
430 		pr_err("Display of offsets requested but symbol is not"
431 		       "selected.\n");
432 		return -EINVAL;
433 	}
434 	if (PRINT_FIELD(DSO) &&
435 		!(evsel->core.attr.sample_type & (PERF_SAMPLE_IP|PERF_SAMPLE_ADDR))) {
436 		pr_err("Display of DSO requested but no address to convert.\n");
437 		return -EINVAL;
438 	}
439 	if ((PRINT_FIELD(SRCLINE) || PRINT_FIELD(SRCCODE)) && !PRINT_FIELD(IP)) {
440 		pr_err("Display of source line number requested but sample IP is not\n"
441 		       "selected. Hence, no address to lookup the source line number.\n");
442 		return -EINVAL;
443 	}
444 	if (PRINT_FIELD(BRSTACKINSN) &&
445 	    !(perf_evlist__combined_branch_type(session->evlist) &
446 	      PERF_SAMPLE_BRANCH_ANY)) {
447 		pr_err("Display of branch stack assembler requested, but non all-branch filter set\n"
448 		       "Hint: run 'perf record -b ...'\n");
449 		return -EINVAL;
450 	}
451 	if ((PRINT_FIELD(PID) || PRINT_FIELD(TID)) &&
452 		perf_evsel__check_stype(evsel, PERF_SAMPLE_TID, "TID",
453 					PERF_OUTPUT_TID|PERF_OUTPUT_PID))
454 		return -EINVAL;
455 
456 	if (PRINT_FIELD(TIME) &&
457 		perf_evsel__check_stype(evsel, PERF_SAMPLE_TIME, "TIME",
458 					PERF_OUTPUT_TIME))
459 		return -EINVAL;
460 
461 	if (PRINT_FIELD(CPU) &&
462 		perf_evsel__do_check_stype(evsel, PERF_SAMPLE_CPU, "CPU",
463 					   PERF_OUTPUT_CPU, allow_user_set))
464 		return -EINVAL;
465 
466 	if (PRINT_FIELD(IREGS) &&
467 		perf_evsel__check_stype(evsel, PERF_SAMPLE_REGS_INTR, "IREGS",
468 					PERF_OUTPUT_IREGS))
469 		return -EINVAL;
470 
471 	if (PRINT_FIELD(UREGS) &&
472 		perf_evsel__check_stype(evsel, PERF_SAMPLE_REGS_USER, "UREGS",
473 					PERF_OUTPUT_UREGS))
474 		return -EINVAL;
475 
476 	if (PRINT_FIELD(PHYS_ADDR) &&
477 		perf_evsel__check_stype(evsel, PERF_SAMPLE_PHYS_ADDR, "PHYS_ADDR",
478 					PERF_OUTPUT_PHYS_ADDR))
479 		return -EINVAL;
480 
481 	return 0;
482 }
483 
484 static void set_print_ip_opts(struct perf_event_attr *attr)
485 {
486 	unsigned int type = output_type(attr->type);
487 
488 	output[type].print_ip_opts = 0;
489 	if (PRINT_FIELD(IP))
490 		output[type].print_ip_opts |= EVSEL__PRINT_IP;
491 
492 	if (PRINT_FIELD(SYM))
493 		output[type].print_ip_opts |= EVSEL__PRINT_SYM;
494 
495 	if (PRINT_FIELD(DSO))
496 		output[type].print_ip_opts |= EVSEL__PRINT_DSO;
497 
498 	if (PRINT_FIELD(SYMOFFSET))
499 		output[type].print_ip_opts |= EVSEL__PRINT_SYMOFFSET;
500 
501 	if (PRINT_FIELD(SRCLINE))
502 		output[type].print_ip_opts |= EVSEL__PRINT_SRCLINE;
503 }
504 
505 /*
506  * verify all user requested events exist and the samples
507  * have the expected data
508  */
509 static int perf_session__check_output_opt(struct perf_session *session)
510 {
511 	unsigned int j;
512 	struct evsel *evsel;
513 
514 	for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
515 		evsel = perf_session__find_first_evtype(session, attr_type(j));
516 
517 		/*
518 		 * even if fields is set to 0 (ie., show nothing) event must
519 		 * exist if user explicitly includes it on the command line
520 		 */
521 		if (!evsel && output[j].user_set && !output[j].wildcard_set &&
522 		    j != OUTPUT_TYPE_SYNTH) {
523 			pr_err("%s events do not exist. "
524 			       "Remove corresponding -F option to proceed.\n",
525 			       event_type(j));
526 			return -1;
527 		}
528 
529 		if (evsel && output[j].fields &&
530 			perf_evsel__check_attr(evsel, session))
531 			return -1;
532 
533 		if (evsel == NULL)
534 			continue;
535 
536 		set_print_ip_opts(&evsel->core.attr);
537 	}
538 
539 	if (!no_callchain) {
540 		bool use_callchain = false;
541 		bool not_pipe = false;
542 
543 		evlist__for_each_entry(session->evlist, evsel) {
544 			not_pipe = true;
545 			if (evsel__has_callchain(evsel)) {
546 				use_callchain = true;
547 				break;
548 			}
549 		}
550 		if (not_pipe && !use_callchain)
551 			symbol_conf.use_callchain = false;
552 	}
553 
554 	/*
555 	 * set default for tracepoints to print symbols only
556 	 * if callchains are present
557 	 */
558 	if (symbol_conf.use_callchain &&
559 	    !output[PERF_TYPE_TRACEPOINT].user_set) {
560 		j = PERF_TYPE_TRACEPOINT;
561 
562 		evlist__for_each_entry(session->evlist, evsel) {
563 			if (evsel->core.attr.type != j)
564 				continue;
565 
566 			if (evsel__has_callchain(evsel)) {
567 				output[j].fields |= PERF_OUTPUT_IP;
568 				output[j].fields |= PERF_OUTPUT_SYM;
569 				output[j].fields |= PERF_OUTPUT_SYMOFFSET;
570 				output[j].fields |= PERF_OUTPUT_DSO;
571 				set_print_ip_opts(&evsel->core.attr);
572 				goto out;
573 			}
574 		}
575 	}
576 
577 out:
578 	return 0;
579 }
580 
581 static int perf_sample__fprintf_regs(struct regs_dump *regs, uint64_t mask,
582 				     FILE *fp
583 )
584 {
585 	unsigned i = 0, r;
586 	int printed = 0;
587 
588 	if (!regs || !regs->regs)
589 		return 0;
590 
591 	printed += fprintf(fp, " ABI:%" PRIu64 " ", regs->abi);
592 
593 	for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
594 		u64 val = regs->regs[i++];
595 		printed += fprintf(fp, "%5s:0x%"PRIx64" ", perf_reg_name(r), val);
596 	}
597 
598 	fprintf(fp, "\n");
599 
600 	return printed;
601 }
602 
603 static int perf_sample__fprintf_iregs(struct perf_sample *sample,
604 				      struct perf_event_attr *attr, FILE *fp)
605 {
606 	return perf_sample__fprintf_regs(&sample->intr_regs,
607 					 attr->sample_regs_intr, fp);
608 }
609 
610 static int perf_sample__fprintf_uregs(struct perf_sample *sample,
611 				      struct perf_event_attr *attr, FILE *fp)
612 {
613 	return perf_sample__fprintf_regs(&sample->user_regs,
614 					 attr->sample_regs_user, fp);
615 }
616 
617 static int perf_sample__fprintf_start(struct perf_sample *sample,
618 				      struct thread *thread,
619 				      struct evsel *evsel,
620 				      u32 type, FILE *fp)
621 {
622 	struct perf_event_attr *attr = &evsel->core.attr;
623 	unsigned long secs;
624 	unsigned long long nsecs;
625 	int printed = 0;
626 
627 	if (PRINT_FIELD(COMM)) {
628 		if (latency_format)
629 			printed += fprintf(fp, "%8.8s ", thread__comm_str(thread));
630 		else if (PRINT_FIELD(IP) && evsel__has_callchain(evsel) && symbol_conf.use_callchain)
631 			printed += fprintf(fp, "%s ", thread__comm_str(thread));
632 		else
633 			printed += fprintf(fp, "%16s ", thread__comm_str(thread));
634 	}
635 
636 	if (PRINT_FIELD(PID) && PRINT_FIELD(TID))
637 		printed += fprintf(fp, "%5d/%-5d ", sample->pid, sample->tid);
638 	else if (PRINT_FIELD(PID))
639 		printed += fprintf(fp, "%5d ", sample->pid);
640 	else if (PRINT_FIELD(TID))
641 		printed += fprintf(fp, "%5d ", sample->tid);
642 
643 	if (PRINT_FIELD(CPU)) {
644 		if (latency_format)
645 			printed += fprintf(fp, "%3d ", sample->cpu);
646 		else
647 			printed += fprintf(fp, "[%03d] ", sample->cpu);
648 	}
649 
650 	if (PRINT_FIELD(MISC)) {
651 		int ret = 0;
652 
653 		#define has(m) \
654 			(sample->misc & PERF_RECORD_MISC_##m) == PERF_RECORD_MISC_##m
655 
656 		if (has(KERNEL))
657 			ret += fprintf(fp, "K");
658 		if (has(USER))
659 			ret += fprintf(fp, "U");
660 		if (has(HYPERVISOR))
661 			ret += fprintf(fp, "H");
662 		if (has(GUEST_KERNEL))
663 			ret += fprintf(fp, "G");
664 		if (has(GUEST_USER))
665 			ret += fprintf(fp, "g");
666 
667 		switch (type) {
668 		case PERF_RECORD_MMAP:
669 		case PERF_RECORD_MMAP2:
670 			if (has(MMAP_DATA))
671 				ret += fprintf(fp, "M");
672 			break;
673 		case PERF_RECORD_COMM:
674 			if (has(COMM_EXEC))
675 				ret += fprintf(fp, "E");
676 			break;
677 		case PERF_RECORD_SWITCH:
678 		case PERF_RECORD_SWITCH_CPU_WIDE:
679 			if (has(SWITCH_OUT)) {
680 				ret += fprintf(fp, "S");
681 				if (sample->misc & PERF_RECORD_MISC_SWITCH_OUT_PREEMPT)
682 					ret += fprintf(fp, "p");
683 			}
684 		default:
685 			break;
686 		}
687 
688 		#undef has
689 
690 		ret += fprintf(fp, "%*s", 6 - ret, " ");
691 		printed += ret;
692 	}
693 
694 	if (PRINT_FIELD(TIME)) {
695 		u64 t = sample->time;
696 		if (reltime) {
697 			if (!initial_time)
698 				initial_time = sample->time;
699 			t = sample->time - initial_time;
700 		}
701 		nsecs = t;
702 		secs = nsecs / NSEC_PER_SEC;
703 		nsecs -= secs * NSEC_PER_SEC;
704 
705 		if (symbol_conf.nanosecs)
706 			printed += fprintf(fp, "%5lu.%09llu: ", secs, nsecs);
707 		else {
708 			char sample_time[32];
709 			timestamp__scnprintf_usec(t, sample_time, sizeof(sample_time));
710 			printed += fprintf(fp, "%12s: ", sample_time);
711 		}
712 	}
713 
714 	return printed;
715 }
716 
717 static inline char
718 mispred_str(struct branch_entry *br)
719 {
720 	if (!(br->flags.mispred  || br->flags.predicted))
721 		return '-';
722 
723 	return br->flags.predicted ? 'P' : 'M';
724 }
725 
726 static int perf_sample__fprintf_brstack(struct perf_sample *sample,
727 					struct thread *thread,
728 					struct perf_event_attr *attr, FILE *fp)
729 {
730 	struct branch_stack *br = sample->branch_stack;
731 	struct addr_location alf, alt;
732 	u64 i, from, to;
733 	int printed = 0;
734 
735 	if (!(br && br->nr))
736 		return 0;
737 
738 	for (i = 0; i < br->nr; i++) {
739 		from = br->entries[i].from;
740 		to   = br->entries[i].to;
741 
742 		if (PRINT_FIELD(DSO)) {
743 			memset(&alf, 0, sizeof(alf));
744 			memset(&alt, 0, sizeof(alt));
745 			thread__find_map_fb(thread, sample->cpumode, from, &alf);
746 			thread__find_map_fb(thread, sample->cpumode, to, &alt);
747 		}
748 
749 		printed += fprintf(fp, " 0x%"PRIx64, from);
750 		if (PRINT_FIELD(DSO)) {
751 			printed += fprintf(fp, "(");
752 			printed += map__fprintf_dsoname(alf.map, fp);
753 			printed += fprintf(fp, ")");
754 		}
755 
756 		printed += fprintf(fp, "/0x%"PRIx64, to);
757 		if (PRINT_FIELD(DSO)) {
758 			printed += fprintf(fp, "(");
759 			printed += map__fprintf_dsoname(alt.map, fp);
760 			printed += fprintf(fp, ")");
761 		}
762 
763 		printed += fprintf(fp, "/%c/%c/%c/%d ",
764 			mispred_str( br->entries + i),
765 			br->entries[i].flags.in_tx? 'X' : '-',
766 			br->entries[i].flags.abort? 'A' : '-',
767 			br->entries[i].flags.cycles);
768 	}
769 
770 	return printed;
771 }
772 
773 static int perf_sample__fprintf_brstacksym(struct perf_sample *sample,
774 					   struct thread *thread,
775 					   struct perf_event_attr *attr, FILE *fp)
776 {
777 	struct branch_stack *br = sample->branch_stack;
778 	struct addr_location alf, alt;
779 	u64 i, from, to;
780 	int printed = 0;
781 
782 	if (!(br && br->nr))
783 		return 0;
784 
785 	for (i = 0; i < br->nr; i++) {
786 
787 		memset(&alf, 0, sizeof(alf));
788 		memset(&alt, 0, sizeof(alt));
789 		from = br->entries[i].from;
790 		to   = br->entries[i].to;
791 
792 		thread__find_symbol_fb(thread, sample->cpumode, from, &alf);
793 		thread__find_symbol_fb(thread, sample->cpumode, to, &alt);
794 
795 		printed += symbol__fprintf_symname_offs(alf.sym, &alf, fp);
796 		if (PRINT_FIELD(DSO)) {
797 			printed += fprintf(fp, "(");
798 			printed += map__fprintf_dsoname(alf.map, fp);
799 			printed += fprintf(fp, ")");
800 		}
801 		printed += fprintf(fp, "%c", '/');
802 		printed += symbol__fprintf_symname_offs(alt.sym, &alt, fp);
803 		if (PRINT_FIELD(DSO)) {
804 			printed += fprintf(fp, "(");
805 			printed += map__fprintf_dsoname(alt.map, fp);
806 			printed += fprintf(fp, ")");
807 		}
808 		printed += fprintf(fp, "/%c/%c/%c/%d ",
809 			mispred_str( br->entries + i),
810 			br->entries[i].flags.in_tx? 'X' : '-',
811 			br->entries[i].flags.abort? 'A' : '-',
812 			br->entries[i].flags.cycles);
813 	}
814 
815 	return printed;
816 }
817 
818 static int perf_sample__fprintf_brstackoff(struct perf_sample *sample,
819 					   struct thread *thread,
820 					   struct perf_event_attr *attr, FILE *fp)
821 {
822 	struct branch_stack *br = sample->branch_stack;
823 	struct addr_location alf, alt;
824 	u64 i, from, to;
825 	int printed = 0;
826 
827 	if (!(br && br->nr))
828 		return 0;
829 
830 	for (i = 0; i < br->nr; i++) {
831 
832 		memset(&alf, 0, sizeof(alf));
833 		memset(&alt, 0, sizeof(alt));
834 		from = br->entries[i].from;
835 		to   = br->entries[i].to;
836 
837 		if (thread__find_map_fb(thread, sample->cpumode, from, &alf) &&
838 		    !alf.map->dso->adjust_symbols)
839 			from = map__map_ip(alf.map, from);
840 
841 		if (thread__find_map_fb(thread, sample->cpumode, to, &alt) &&
842 		    !alt.map->dso->adjust_symbols)
843 			to = map__map_ip(alt.map, to);
844 
845 		printed += fprintf(fp, " 0x%"PRIx64, from);
846 		if (PRINT_FIELD(DSO)) {
847 			printed += fprintf(fp, "(");
848 			printed += map__fprintf_dsoname(alf.map, fp);
849 			printed += fprintf(fp, ")");
850 		}
851 		printed += fprintf(fp, "/0x%"PRIx64, to);
852 		if (PRINT_FIELD(DSO)) {
853 			printed += fprintf(fp, "(");
854 			printed += map__fprintf_dsoname(alt.map, fp);
855 			printed += fprintf(fp, ")");
856 		}
857 		printed += fprintf(fp, "/%c/%c/%c/%d ",
858 			mispred_str(br->entries + i),
859 			br->entries[i].flags.in_tx ? 'X' : '-',
860 			br->entries[i].flags.abort ? 'A' : '-',
861 			br->entries[i].flags.cycles);
862 	}
863 
864 	return printed;
865 }
866 #define MAXBB 16384UL
867 
868 static int grab_bb(u8 *buffer, u64 start, u64 end,
869 		    struct machine *machine, struct thread *thread,
870 		    bool *is64bit, u8 *cpumode, bool last)
871 {
872 	long offset, len;
873 	struct addr_location al;
874 	bool kernel;
875 
876 	if (!start || !end)
877 		return 0;
878 
879 	kernel = machine__kernel_ip(machine, start);
880 	if (kernel)
881 		*cpumode = PERF_RECORD_MISC_KERNEL;
882 	else
883 		*cpumode = PERF_RECORD_MISC_USER;
884 
885 	/*
886 	 * Block overlaps between kernel and user.
887 	 * This can happen due to ring filtering
888 	 * On Intel CPUs the entry into the kernel is filtered,
889 	 * but the exit is not. Let the caller patch it up.
890 	 */
891 	if (kernel != machine__kernel_ip(machine, end)) {
892 		pr_debug("\tblock %" PRIx64 "-%" PRIx64 " transfers between kernel and user\n", start, end);
893 		return -ENXIO;
894 	}
895 
896 	memset(&al, 0, sizeof(al));
897 	if (end - start > MAXBB - MAXINSN) {
898 		if (last)
899 			pr_debug("\tbrstack does not reach to final jump (%" PRIx64 "-%" PRIx64 ")\n", start, end);
900 		else
901 			pr_debug("\tblock %" PRIx64 "-%" PRIx64 " (%" PRIu64 ") too long to dump\n", start, end, end - start);
902 		return 0;
903 	}
904 
905 	if (!thread__find_map(thread, *cpumode, start, &al) || !al.map->dso) {
906 		pr_debug("\tcannot resolve %" PRIx64 "-%" PRIx64 "\n", start, end);
907 		return 0;
908 	}
909 	if (al.map->dso->data.status == DSO_DATA_STATUS_ERROR) {
910 		pr_debug("\tcannot resolve %" PRIx64 "-%" PRIx64 "\n", start, end);
911 		return 0;
912 	}
913 
914 	/* Load maps to ensure dso->is_64_bit has been updated */
915 	map__load(al.map);
916 
917 	offset = al.map->map_ip(al.map, start);
918 	len = dso__data_read_offset(al.map->dso, machine, offset, (u8 *)buffer,
919 				    end - start + MAXINSN);
920 
921 	*is64bit = al.map->dso->is_64_bit;
922 	if (len <= 0)
923 		pr_debug("\tcannot fetch code for block at %" PRIx64 "-%" PRIx64 "\n",
924 			start, end);
925 	return len;
926 }
927 
928 static int print_srccode(struct thread *thread, u8 cpumode, uint64_t addr)
929 {
930 	struct addr_location al;
931 	int ret = 0;
932 
933 	memset(&al, 0, sizeof(al));
934 	thread__find_map(thread, cpumode, addr, &al);
935 	if (!al.map)
936 		return 0;
937 	ret = map__fprintf_srccode(al.map, al.addr, stdout,
938 		    &thread->srccode_state);
939 	if (ret)
940 		ret += printf("\n");
941 	return ret;
942 }
943 
944 static int ip__fprintf_jump(uint64_t ip, struct branch_entry *en,
945 			    struct perf_insn *x, u8 *inbuf, int len,
946 			    int insn, FILE *fp, int *total_cycles)
947 {
948 	int printed = fprintf(fp, "\t%016" PRIx64 "\t%-30s\t#%s%s%s%s", ip,
949 			      dump_insn(x, ip, inbuf, len, NULL),
950 			      en->flags.predicted ? " PRED" : "",
951 			      en->flags.mispred ? " MISPRED" : "",
952 			      en->flags.in_tx ? " INTX" : "",
953 			      en->flags.abort ? " ABORT" : "");
954 	if (en->flags.cycles) {
955 		*total_cycles += en->flags.cycles;
956 		printed += fprintf(fp, " %d cycles [%d]", en->flags.cycles, *total_cycles);
957 		if (insn)
958 			printed += fprintf(fp, " %.2f IPC", (float)insn / en->flags.cycles);
959 	}
960 	return printed + fprintf(fp, "\n");
961 }
962 
963 static int ip__fprintf_sym(uint64_t addr, struct thread *thread,
964 			   u8 cpumode, int cpu, struct symbol **lastsym,
965 			   struct perf_event_attr *attr, FILE *fp)
966 {
967 	struct addr_location al;
968 	int off, printed = 0;
969 
970 	memset(&al, 0, sizeof(al));
971 
972 	thread__find_map(thread, cpumode, addr, &al);
973 
974 	if ((*lastsym) && al.addr >= (*lastsym)->start && al.addr < (*lastsym)->end)
975 		return 0;
976 
977 	al.cpu = cpu;
978 	al.sym = NULL;
979 	if (al.map)
980 		al.sym = map__find_symbol(al.map, al.addr);
981 
982 	if (!al.sym)
983 		return 0;
984 
985 	if (al.addr < al.sym->end)
986 		off = al.addr - al.sym->start;
987 	else
988 		off = al.addr - al.map->start - al.sym->start;
989 	printed += fprintf(fp, "\t%s", al.sym->name);
990 	if (off)
991 		printed += fprintf(fp, "%+d", off);
992 	printed += fprintf(fp, ":");
993 	if (PRINT_FIELD(SRCLINE))
994 		printed += map__fprintf_srcline(al.map, al.addr, "\t", fp);
995 	printed += fprintf(fp, "\n");
996 	*lastsym = al.sym;
997 
998 	return printed;
999 }
1000 
1001 static int perf_sample__fprintf_brstackinsn(struct perf_sample *sample,
1002 					    struct thread *thread,
1003 					    struct perf_event_attr *attr,
1004 					    struct machine *machine, FILE *fp)
1005 {
1006 	struct branch_stack *br = sample->branch_stack;
1007 	u64 start, end;
1008 	int i, insn, len, nr, ilen, printed = 0;
1009 	struct perf_insn x;
1010 	u8 buffer[MAXBB];
1011 	unsigned off;
1012 	struct symbol *lastsym = NULL;
1013 	int total_cycles = 0;
1014 
1015 	if (!(br && br->nr))
1016 		return 0;
1017 	nr = br->nr;
1018 	if (max_blocks && nr > max_blocks + 1)
1019 		nr = max_blocks + 1;
1020 
1021 	x.thread = thread;
1022 	x.cpu = sample->cpu;
1023 
1024 	printed += fprintf(fp, "%c", '\n');
1025 
1026 	/* Handle first from jump, of which we don't know the entry. */
1027 	len = grab_bb(buffer, br->entries[nr-1].from,
1028 			br->entries[nr-1].from,
1029 			machine, thread, &x.is64bit, &x.cpumode, false);
1030 	if (len > 0) {
1031 		printed += ip__fprintf_sym(br->entries[nr - 1].from, thread,
1032 					   x.cpumode, x.cpu, &lastsym, attr, fp);
1033 		printed += ip__fprintf_jump(br->entries[nr - 1].from, &br->entries[nr - 1],
1034 					    &x, buffer, len, 0, fp, &total_cycles);
1035 		if (PRINT_FIELD(SRCCODE))
1036 			printed += print_srccode(thread, x.cpumode, br->entries[nr - 1].from);
1037 	}
1038 
1039 	/* Print all blocks */
1040 	for (i = nr - 2; i >= 0; i--) {
1041 		if (br->entries[i].from || br->entries[i].to)
1042 			pr_debug("%d: %" PRIx64 "-%" PRIx64 "\n", i,
1043 				 br->entries[i].from,
1044 				 br->entries[i].to);
1045 		start = br->entries[i + 1].to;
1046 		end   = br->entries[i].from;
1047 
1048 		len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, false);
1049 		/* Patch up missing kernel transfers due to ring filters */
1050 		if (len == -ENXIO && i > 0) {
1051 			end = br->entries[--i].from;
1052 			pr_debug("\tpatching up to %" PRIx64 "-%" PRIx64 "\n", start, end);
1053 			len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, false);
1054 		}
1055 		if (len <= 0)
1056 			continue;
1057 
1058 		insn = 0;
1059 		for (off = 0;; off += ilen) {
1060 			uint64_t ip = start + off;
1061 
1062 			printed += ip__fprintf_sym(ip, thread, x.cpumode, x.cpu, &lastsym, attr, fp);
1063 			if (ip == end) {
1064 				printed += ip__fprintf_jump(ip, &br->entries[i], &x, buffer + off, len - off, ++insn, fp,
1065 							    &total_cycles);
1066 				if (PRINT_FIELD(SRCCODE))
1067 					printed += print_srccode(thread, x.cpumode, ip);
1068 				break;
1069 			} else {
1070 				printed += fprintf(fp, "\t%016" PRIx64 "\t%s\n", ip,
1071 						   dump_insn(&x, ip, buffer + off, len - off, &ilen));
1072 				if (ilen == 0)
1073 					break;
1074 				if (PRINT_FIELD(SRCCODE))
1075 					print_srccode(thread, x.cpumode, ip);
1076 				insn++;
1077 			}
1078 		}
1079 	}
1080 
1081 	/*
1082 	 * Hit the branch? In this case we are already done, and the target
1083 	 * has not been executed yet.
1084 	 */
1085 	if (br->entries[0].from == sample->ip)
1086 		goto out;
1087 	if (br->entries[0].flags.abort)
1088 		goto out;
1089 
1090 	/*
1091 	 * Print final block upto sample
1092 	 *
1093 	 * Due to pipeline delays the LBRs might be missing a branch
1094 	 * or two, which can result in very large or negative blocks
1095 	 * between final branch and sample. When this happens just
1096 	 * continue walking after the last TO until we hit a branch.
1097 	 */
1098 	start = br->entries[0].to;
1099 	end = sample->ip;
1100 	if (end < start) {
1101 		/* Missing jump. Scan 128 bytes for the next branch */
1102 		end = start + 128;
1103 	}
1104 	len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, true);
1105 	printed += ip__fprintf_sym(start, thread, x.cpumode, x.cpu, &lastsym, attr, fp);
1106 	if (len <= 0) {
1107 		/* Print at least last IP if basic block did not work */
1108 		len = grab_bb(buffer, sample->ip, sample->ip,
1109 			      machine, thread, &x.is64bit, &x.cpumode, false);
1110 		if (len <= 0)
1111 			goto out;
1112 		printed += fprintf(fp, "\t%016" PRIx64 "\t%s\n", sample->ip,
1113 			dump_insn(&x, sample->ip, buffer, len, NULL));
1114 		if (PRINT_FIELD(SRCCODE))
1115 			print_srccode(thread, x.cpumode, sample->ip);
1116 		goto out;
1117 	}
1118 	for (off = 0; off <= end - start; off += ilen) {
1119 		printed += fprintf(fp, "\t%016" PRIx64 "\t%s\n", start + off,
1120 				   dump_insn(&x, start + off, buffer + off, len - off, &ilen));
1121 		if (ilen == 0)
1122 			break;
1123 		if (arch_is_branch(buffer + off, len - off, x.is64bit) && start + off != sample->ip) {
1124 			/*
1125 			 * Hit a missing branch. Just stop.
1126 			 */
1127 			printed += fprintf(fp, "\t... not reaching sample ...\n");
1128 			break;
1129 		}
1130 		if (PRINT_FIELD(SRCCODE))
1131 			print_srccode(thread, x.cpumode, start + off);
1132 	}
1133 out:
1134 	return printed;
1135 }
1136 
1137 static int perf_sample__fprintf_addr(struct perf_sample *sample,
1138 				     struct thread *thread,
1139 				     struct perf_event_attr *attr, FILE *fp)
1140 {
1141 	struct addr_location al;
1142 	int printed = fprintf(fp, "%16" PRIx64, sample->addr);
1143 
1144 	if (!sample_addr_correlates_sym(attr))
1145 		goto out;
1146 
1147 	thread__resolve(thread, &al, sample);
1148 
1149 	if (PRINT_FIELD(SYM)) {
1150 		printed += fprintf(fp, " ");
1151 		if (PRINT_FIELD(SYMOFFSET))
1152 			printed += symbol__fprintf_symname_offs(al.sym, &al, fp);
1153 		else
1154 			printed += symbol__fprintf_symname(al.sym, fp);
1155 	}
1156 
1157 	if (PRINT_FIELD(DSO)) {
1158 		printed += fprintf(fp, " (");
1159 		printed += map__fprintf_dsoname(al.map, fp);
1160 		printed += fprintf(fp, ")");
1161 	}
1162 out:
1163 	return printed;
1164 }
1165 
1166 static const char *resolve_branch_sym(struct perf_sample *sample,
1167 				      struct evsel *evsel,
1168 				      struct thread *thread,
1169 				      struct addr_location *al,
1170 				      u64 *ip)
1171 {
1172 	struct addr_location addr_al;
1173 	struct perf_event_attr *attr = &evsel->core.attr;
1174 	const char *name = NULL;
1175 
1176 	if (sample->flags & (PERF_IP_FLAG_CALL | PERF_IP_FLAG_TRACE_BEGIN)) {
1177 		if (sample_addr_correlates_sym(attr)) {
1178 			thread__resolve(thread, &addr_al, sample);
1179 			if (addr_al.sym)
1180 				name = addr_al.sym->name;
1181 			else
1182 				*ip = sample->addr;
1183 		} else {
1184 			*ip = sample->addr;
1185 		}
1186 	} else if (sample->flags & (PERF_IP_FLAG_RETURN | PERF_IP_FLAG_TRACE_END)) {
1187 		if (al->sym)
1188 			name = al->sym->name;
1189 		else
1190 			*ip = sample->ip;
1191 	}
1192 	return name;
1193 }
1194 
1195 static int perf_sample__fprintf_callindent(struct perf_sample *sample,
1196 					   struct evsel *evsel,
1197 					   struct thread *thread,
1198 					   struct addr_location *al, FILE *fp)
1199 {
1200 	struct perf_event_attr *attr = &evsel->core.attr;
1201 	size_t depth = thread_stack__depth(thread, sample->cpu);
1202 	const char *name = NULL;
1203 	static int spacing;
1204 	int len = 0;
1205 	int dlen = 0;
1206 	u64 ip = 0;
1207 
1208 	/*
1209 	 * The 'return' has already been popped off the stack so the depth has
1210 	 * to be adjusted to match the 'call'.
1211 	 */
1212 	if (thread->ts && sample->flags & PERF_IP_FLAG_RETURN)
1213 		depth += 1;
1214 
1215 	name = resolve_branch_sym(sample, evsel, thread, al, &ip);
1216 
1217 	if (PRINT_FIELD(DSO) && !(PRINT_FIELD(IP) || PRINT_FIELD(ADDR))) {
1218 		dlen += fprintf(fp, "(");
1219 		dlen += map__fprintf_dsoname(al->map, fp);
1220 		dlen += fprintf(fp, ")\t");
1221 	}
1222 
1223 	if (name)
1224 		len = fprintf(fp, "%*s%s", (int)depth * 4, "", name);
1225 	else if (ip)
1226 		len = fprintf(fp, "%*s%16" PRIx64, (int)depth * 4, "", ip);
1227 
1228 	if (len < 0)
1229 		return len;
1230 
1231 	/*
1232 	 * Try to keep the output length from changing frequently so that the
1233 	 * output lines up more nicely.
1234 	 */
1235 	if (len > spacing || (len && len < spacing - 52))
1236 		spacing = round_up(len + 4, 32);
1237 
1238 	if (len < spacing)
1239 		len += fprintf(fp, "%*s", spacing - len, "");
1240 
1241 	return len + dlen;
1242 }
1243 
1244 __weak void arch_fetch_insn(struct perf_sample *sample __maybe_unused,
1245 			    struct thread *thread __maybe_unused,
1246 			    struct machine *machine __maybe_unused)
1247 {
1248 }
1249 
1250 static int perf_sample__fprintf_insn(struct perf_sample *sample,
1251 				     struct perf_event_attr *attr,
1252 				     struct thread *thread,
1253 				     struct machine *machine, FILE *fp)
1254 {
1255 	int printed = 0;
1256 
1257 	if (sample->insn_len == 0 && native_arch)
1258 		arch_fetch_insn(sample, thread, machine);
1259 
1260 	if (PRINT_FIELD(INSNLEN))
1261 		printed += fprintf(fp, " ilen: %d", sample->insn_len);
1262 	if (PRINT_FIELD(INSN) && sample->insn_len) {
1263 		int i;
1264 
1265 		printed += fprintf(fp, " insn:");
1266 		for (i = 0; i < sample->insn_len; i++)
1267 			printed += fprintf(fp, " %02x", (unsigned char)sample->insn[i]);
1268 	}
1269 	if (PRINT_FIELD(BRSTACKINSN))
1270 		printed += perf_sample__fprintf_brstackinsn(sample, thread, attr, machine, fp);
1271 
1272 	return printed;
1273 }
1274 
1275 static int perf_sample__fprintf_ipc(struct perf_sample *sample,
1276 				    struct perf_event_attr *attr, FILE *fp)
1277 {
1278 	unsigned int ipc;
1279 
1280 	if (!PRINT_FIELD(IPC) || !sample->cyc_cnt || !sample->insn_cnt)
1281 		return 0;
1282 
1283 	ipc = (sample->insn_cnt * 100) / sample->cyc_cnt;
1284 
1285 	return fprintf(fp, " \t IPC: %u.%02u (%" PRIu64 "/%" PRIu64 ") ",
1286 		       ipc / 100, ipc % 100, sample->insn_cnt, sample->cyc_cnt);
1287 }
1288 
1289 static int perf_sample__fprintf_bts(struct perf_sample *sample,
1290 				    struct evsel *evsel,
1291 				    struct thread *thread,
1292 				    struct addr_location *al,
1293 				    struct machine *machine, FILE *fp)
1294 {
1295 	struct perf_event_attr *attr = &evsel->core.attr;
1296 	unsigned int type = output_type(attr->type);
1297 	bool print_srcline_last = false;
1298 	int printed = 0;
1299 
1300 	if (PRINT_FIELD(CALLINDENT))
1301 		printed += perf_sample__fprintf_callindent(sample, evsel, thread, al, fp);
1302 
1303 	/* print branch_from information */
1304 	if (PRINT_FIELD(IP)) {
1305 		unsigned int print_opts = output[type].print_ip_opts;
1306 		struct callchain_cursor *cursor = NULL;
1307 
1308 		if (symbol_conf.use_callchain && sample->callchain &&
1309 		    thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
1310 					      sample, NULL, NULL, scripting_max_stack) == 0)
1311 			cursor = &callchain_cursor;
1312 
1313 		if (cursor == NULL) {
1314 			printed += fprintf(fp, " ");
1315 			if (print_opts & EVSEL__PRINT_SRCLINE) {
1316 				print_srcline_last = true;
1317 				print_opts &= ~EVSEL__PRINT_SRCLINE;
1318 			}
1319 		} else
1320 			printed += fprintf(fp, "\n");
1321 
1322 		printed += sample__fprintf_sym(sample, al, 0, print_opts, cursor, fp);
1323 	}
1324 
1325 	/* print branch_to information */
1326 	if (PRINT_FIELD(ADDR) ||
1327 	    ((evsel->core.attr.sample_type & PERF_SAMPLE_ADDR) &&
1328 	     !output[type].user_set)) {
1329 		printed += fprintf(fp, " => ");
1330 		printed += perf_sample__fprintf_addr(sample, thread, attr, fp);
1331 	}
1332 
1333 	printed += perf_sample__fprintf_ipc(sample, attr, fp);
1334 
1335 	if (print_srcline_last)
1336 		printed += map__fprintf_srcline(al->map, al->addr, "\n  ", fp);
1337 
1338 	printed += perf_sample__fprintf_insn(sample, attr, thread, machine, fp);
1339 	printed += fprintf(fp, "\n");
1340 	if (PRINT_FIELD(SRCCODE)) {
1341 		int ret = map__fprintf_srccode(al->map, al->addr, stdout,
1342 					 &thread->srccode_state);
1343 		if (ret) {
1344 			printed += ret;
1345 			printed += printf("\n");
1346 		}
1347 	}
1348 	return printed;
1349 }
1350 
1351 static struct {
1352 	u32 flags;
1353 	const char *name;
1354 } sample_flags[] = {
1355 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL, "call"},
1356 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN, "return"},
1357 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CONDITIONAL, "jcc"},
1358 	{PERF_IP_FLAG_BRANCH, "jmp"},
1359 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_INTERRUPT, "int"},
1360 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN | PERF_IP_FLAG_INTERRUPT, "iret"},
1361 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_SYSCALLRET, "syscall"},
1362 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN | PERF_IP_FLAG_SYSCALLRET, "sysret"},
1363 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_ASYNC, "async"},
1364 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_ASYNC |	PERF_IP_FLAG_INTERRUPT, "hw int"},
1365 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TX_ABORT, "tx abrt"},
1366 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TRACE_BEGIN, "tr strt"},
1367 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TRACE_END, "tr end"},
1368 	{0, NULL}
1369 };
1370 
1371 static const char *sample_flags_to_name(u32 flags)
1372 {
1373 	int i;
1374 
1375 	for (i = 0; sample_flags[i].name ; i++) {
1376 		if (sample_flags[i].flags == flags)
1377 			return sample_flags[i].name;
1378 	}
1379 
1380 	return NULL;
1381 }
1382 
1383 static int perf_sample__fprintf_flags(u32 flags, FILE *fp)
1384 {
1385 	const char *chars = PERF_IP_FLAG_CHARS;
1386 	const int n = strlen(PERF_IP_FLAG_CHARS);
1387 	bool in_tx = flags & PERF_IP_FLAG_IN_TX;
1388 	const char *name = NULL;
1389 	char str[33];
1390 	int i, pos = 0;
1391 
1392 	name = sample_flags_to_name(flags & ~PERF_IP_FLAG_IN_TX);
1393 	if (name)
1394 		return fprintf(fp, "  %-15s%4s ", name, in_tx ? "(x)" : "");
1395 
1396 	if (flags & PERF_IP_FLAG_TRACE_BEGIN) {
1397 		name = sample_flags_to_name(flags & ~(PERF_IP_FLAG_IN_TX | PERF_IP_FLAG_TRACE_BEGIN));
1398 		if (name)
1399 			return fprintf(fp, "  tr strt %-7s%4s ", name, in_tx ? "(x)" : "");
1400 	}
1401 
1402 	if (flags & PERF_IP_FLAG_TRACE_END) {
1403 		name = sample_flags_to_name(flags & ~(PERF_IP_FLAG_IN_TX | PERF_IP_FLAG_TRACE_END));
1404 		if (name)
1405 			return fprintf(fp, "  tr end  %-7s%4s ", name, in_tx ? "(x)" : "");
1406 	}
1407 
1408 	for (i = 0; i < n; i++, flags >>= 1) {
1409 		if (flags & 1)
1410 			str[pos++] = chars[i];
1411 	}
1412 	for (; i < 32; i++, flags >>= 1) {
1413 		if (flags & 1)
1414 			str[pos++] = '?';
1415 	}
1416 	str[pos] = 0;
1417 
1418 	return fprintf(fp, "  %-19s ", str);
1419 }
1420 
1421 struct printer_data {
1422 	int line_no;
1423 	bool hit_nul;
1424 	bool is_printable;
1425 };
1426 
1427 static int sample__fprintf_bpf_output(enum binary_printer_ops op,
1428 				      unsigned int val,
1429 				      void *extra, FILE *fp)
1430 {
1431 	unsigned char ch = (unsigned char)val;
1432 	struct printer_data *printer_data = extra;
1433 	int printed = 0;
1434 
1435 	switch (op) {
1436 	case BINARY_PRINT_DATA_BEGIN:
1437 		printed += fprintf(fp, "\n");
1438 		break;
1439 	case BINARY_PRINT_LINE_BEGIN:
1440 		printed += fprintf(fp, "%17s", !printer_data->line_no ? "BPF output:" :
1441 						        "           ");
1442 		break;
1443 	case BINARY_PRINT_ADDR:
1444 		printed += fprintf(fp, " %04x:", val);
1445 		break;
1446 	case BINARY_PRINT_NUM_DATA:
1447 		printed += fprintf(fp, " %02x", val);
1448 		break;
1449 	case BINARY_PRINT_NUM_PAD:
1450 		printed += fprintf(fp, "   ");
1451 		break;
1452 	case BINARY_PRINT_SEP:
1453 		printed += fprintf(fp, "  ");
1454 		break;
1455 	case BINARY_PRINT_CHAR_DATA:
1456 		if (printer_data->hit_nul && ch)
1457 			printer_data->is_printable = false;
1458 
1459 		if (!isprint(ch)) {
1460 			printed += fprintf(fp, "%c", '.');
1461 
1462 			if (!printer_data->is_printable)
1463 				break;
1464 
1465 			if (ch == '\0')
1466 				printer_data->hit_nul = true;
1467 			else
1468 				printer_data->is_printable = false;
1469 		} else {
1470 			printed += fprintf(fp, "%c", ch);
1471 		}
1472 		break;
1473 	case BINARY_PRINT_CHAR_PAD:
1474 		printed += fprintf(fp, " ");
1475 		break;
1476 	case BINARY_PRINT_LINE_END:
1477 		printed += fprintf(fp, "\n");
1478 		printer_data->line_no++;
1479 		break;
1480 	case BINARY_PRINT_DATA_END:
1481 	default:
1482 		break;
1483 	}
1484 
1485 	return printed;
1486 }
1487 
1488 static int perf_sample__fprintf_bpf_output(struct perf_sample *sample, FILE *fp)
1489 {
1490 	unsigned int nr_bytes = sample->raw_size;
1491 	struct printer_data printer_data = {0, false, true};
1492 	int printed = binary__fprintf(sample->raw_data, nr_bytes, 8,
1493 				      sample__fprintf_bpf_output, &printer_data, fp);
1494 
1495 	if (printer_data.is_printable && printer_data.hit_nul)
1496 		printed += fprintf(fp, "%17s \"%s\"\n", "BPF string:", (char *)(sample->raw_data));
1497 
1498 	return printed;
1499 }
1500 
1501 static int perf_sample__fprintf_spacing(int len, int spacing, FILE *fp)
1502 {
1503 	if (len > 0 && len < spacing)
1504 		return fprintf(fp, "%*s", spacing - len, "");
1505 
1506 	return 0;
1507 }
1508 
1509 static int perf_sample__fprintf_pt_spacing(int len, FILE *fp)
1510 {
1511 	return perf_sample__fprintf_spacing(len, 34, fp);
1512 }
1513 
1514 static int perf_sample__fprintf_synth_ptwrite(struct perf_sample *sample, FILE *fp)
1515 {
1516 	struct perf_synth_intel_ptwrite *data = perf_sample__synth_ptr(sample);
1517 	int len;
1518 
1519 	if (perf_sample__bad_synth_size(sample, *data))
1520 		return 0;
1521 
1522 	len = fprintf(fp, " IP: %u payload: %#" PRIx64 " ",
1523 		     data->ip, le64_to_cpu(data->payload));
1524 	return len + perf_sample__fprintf_pt_spacing(len, fp);
1525 }
1526 
1527 static int perf_sample__fprintf_synth_mwait(struct perf_sample *sample, FILE *fp)
1528 {
1529 	struct perf_synth_intel_mwait *data = perf_sample__synth_ptr(sample);
1530 	int len;
1531 
1532 	if (perf_sample__bad_synth_size(sample, *data))
1533 		return 0;
1534 
1535 	len = fprintf(fp, " hints: %#x extensions: %#x ",
1536 		      data->hints, data->extensions);
1537 	return len + perf_sample__fprintf_pt_spacing(len, fp);
1538 }
1539 
1540 static int perf_sample__fprintf_synth_pwre(struct perf_sample *sample, FILE *fp)
1541 {
1542 	struct perf_synth_intel_pwre *data = perf_sample__synth_ptr(sample);
1543 	int len;
1544 
1545 	if (perf_sample__bad_synth_size(sample, *data))
1546 		return 0;
1547 
1548 	len = fprintf(fp, " hw: %u cstate: %u sub-cstate: %u ",
1549 		      data->hw, data->cstate, data->subcstate);
1550 	return len + perf_sample__fprintf_pt_spacing(len, fp);
1551 }
1552 
1553 static int perf_sample__fprintf_synth_exstop(struct perf_sample *sample, FILE *fp)
1554 {
1555 	struct perf_synth_intel_exstop *data = perf_sample__synth_ptr(sample);
1556 	int len;
1557 
1558 	if (perf_sample__bad_synth_size(sample, *data))
1559 		return 0;
1560 
1561 	len = fprintf(fp, " IP: %u ", data->ip);
1562 	return len + perf_sample__fprintf_pt_spacing(len, fp);
1563 }
1564 
1565 static int perf_sample__fprintf_synth_pwrx(struct perf_sample *sample, FILE *fp)
1566 {
1567 	struct perf_synth_intel_pwrx *data = perf_sample__synth_ptr(sample);
1568 	int len;
1569 
1570 	if (perf_sample__bad_synth_size(sample, *data))
1571 		return 0;
1572 
1573 	len = fprintf(fp, " deepest cstate: %u last cstate: %u wake reason: %#x ",
1574 		     data->deepest_cstate, data->last_cstate,
1575 		     data->wake_reason);
1576 	return len + perf_sample__fprintf_pt_spacing(len, fp);
1577 }
1578 
1579 static int perf_sample__fprintf_synth_cbr(struct perf_sample *sample, FILE *fp)
1580 {
1581 	struct perf_synth_intel_cbr *data = perf_sample__synth_ptr(sample);
1582 	unsigned int percent, freq;
1583 	int len;
1584 
1585 	if (perf_sample__bad_synth_size(sample, *data))
1586 		return 0;
1587 
1588 	freq = (le32_to_cpu(data->freq) + 500) / 1000;
1589 	len = fprintf(fp, " cbr: %2u freq: %4u MHz ", data->cbr, freq);
1590 	if (data->max_nonturbo) {
1591 		percent = (5 + (1000 * data->cbr) / data->max_nonturbo) / 10;
1592 		len += fprintf(fp, "(%3u%%) ", percent);
1593 	}
1594 	return len + perf_sample__fprintf_pt_spacing(len, fp);
1595 }
1596 
1597 static int perf_sample__fprintf_synth(struct perf_sample *sample,
1598 				      struct evsel *evsel, FILE *fp)
1599 {
1600 	switch (evsel->core.attr.config) {
1601 	case PERF_SYNTH_INTEL_PTWRITE:
1602 		return perf_sample__fprintf_synth_ptwrite(sample, fp);
1603 	case PERF_SYNTH_INTEL_MWAIT:
1604 		return perf_sample__fprintf_synth_mwait(sample, fp);
1605 	case PERF_SYNTH_INTEL_PWRE:
1606 		return perf_sample__fprintf_synth_pwre(sample, fp);
1607 	case PERF_SYNTH_INTEL_EXSTOP:
1608 		return perf_sample__fprintf_synth_exstop(sample, fp);
1609 	case PERF_SYNTH_INTEL_PWRX:
1610 		return perf_sample__fprintf_synth_pwrx(sample, fp);
1611 	case PERF_SYNTH_INTEL_CBR:
1612 		return perf_sample__fprintf_synth_cbr(sample, fp);
1613 	default:
1614 		break;
1615 	}
1616 
1617 	return 0;
1618 }
1619 
1620 struct perf_script {
1621 	struct perf_tool	tool;
1622 	struct perf_session	*session;
1623 	bool			show_task_events;
1624 	bool			show_mmap_events;
1625 	bool			show_switch_events;
1626 	bool			show_namespace_events;
1627 	bool			show_lost_events;
1628 	bool			show_round_events;
1629 	bool			show_bpf_events;
1630 	bool			allocated;
1631 	bool			per_event_dump;
1632 	struct evswitch		evswitch;
1633 	struct perf_cpu_map	*cpus;
1634 	struct perf_thread_map *threads;
1635 	int			name_width;
1636 	const char              *time_str;
1637 	struct perf_time_interval *ptime_range;
1638 	int			range_size;
1639 	int			range_num;
1640 };
1641 
1642 static int perf_evlist__max_name_len(struct evlist *evlist)
1643 {
1644 	struct evsel *evsel;
1645 	int max = 0;
1646 
1647 	evlist__for_each_entry(evlist, evsel) {
1648 		int len = strlen(perf_evsel__name(evsel));
1649 
1650 		max = MAX(len, max);
1651 	}
1652 
1653 	return max;
1654 }
1655 
1656 static int data_src__fprintf(u64 data_src, FILE *fp)
1657 {
1658 	struct mem_info mi = { .data_src.val = data_src };
1659 	char decode[100];
1660 	char out[100];
1661 	static int maxlen;
1662 	int len;
1663 
1664 	perf_script__meminfo_scnprintf(decode, 100, &mi);
1665 
1666 	len = scnprintf(out, 100, "%16" PRIx64 " %s", data_src, decode);
1667 	if (maxlen < len)
1668 		maxlen = len;
1669 
1670 	return fprintf(fp, "%-*s", maxlen, out);
1671 }
1672 
1673 struct metric_ctx {
1674 	struct perf_sample	*sample;
1675 	struct thread		*thread;
1676 	struct evsel	*evsel;
1677 	FILE 			*fp;
1678 };
1679 
1680 static void script_print_metric(struct perf_stat_config *config __maybe_unused,
1681 				void *ctx, const char *color,
1682 			        const char *fmt,
1683 			        const char *unit, double val)
1684 {
1685 	struct metric_ctx *mctx = ctx;
1686 
1687 	if (!fmt)
1688 		return;
1689 	perf_sample__fprintf_start(mctx->sample, mctx->thread, mctx->evsel,
1690 				   PERF_RECORD_SAMPLE, mctx->fp);
1691 	fputs("\tmetric: ", mctx->fp);
1692 	if (color)
1693 		color_fprintf(mctx->fp, color, fmt, val);
1694 	else
1695 		printf(fmt, val);
1696 	fprintf(mctx->fp, " %s\n", unit);
1697 }
1698 
1699 static void script_new_line(struct perf_stat_config *config __maybe_unused,
1700 			    void *ctx)
1701 {
1702 	struct metric_ctx *mctx = ctx;
1703 
1704 	perf_sample__fprintf_start(mctx->sample, mctx->thread, mctx->evsel,
1705 				   PERF_RECORD_SAMPLE, mctx->fp);
1706 	fputs("\tmetric: ", mctx->fp);
1707 }
1708 
1709 static void perf_sample__fprint_metric(struct perf_script *script,
1710 				       struct thread *thread,
1711 				       struct evsel *evsel,
1712 				       struct perf_sample *sample,
1713 				       FILE *fp)
1714 {
1715 	struct perf_stat_output_ctx ctx = {
1716 		.print_metric = script_print_metric,
1717 		.new_line = script_new_line,
1718 		.ctx = &(struct metric_ctx) {
1719 				.sample = sample,
1720 				.thread = thread,
1721 				.evsel  = evsel,
1722 				.fp     = fp,
1723 			 },
1724 		.force_header = false,
1725 	};
1726 	struct evsel *ev2;
1727 	u64 val;
1728 
1729 	if (!evsel->stats)
1730 		perf_evlist__alloc_stats(script->session->evlist, false);
1731 	if (evsel_script(evsel->leader)->gnum++ == 0)
1732 		perf_stat__reset_shadow_stats();
1733 	val = sample->period * evsel->scale;
1734 	perf_stat__update_shadow_stats(evsel,
1735 				       val,
1736 				       sample->cpu,
1737 				       &rt_stat);
1738 	evsel_script(evsel)->val = val;
1739 	if (evsel_script(evsel->leader)->gnum == evsel->leader->core.nr_members) {
1740 		for_each_group_member (ev2, evsel->leader) {
1741 			perf_stat__print_shadow_stats(&stat_config, ev2,
1742 						      evsel_script(ev2)->val,
1743 						      sample->cpu,
1744 						      &ctx,
1745 						      NULL,
1746 						      &rt_stat);
1747 		}
1748 		evsel_script(evsel->leader)->gnum = 0;
1749 	}
1750 }
1751 
1752 static bool show_event(struct perf_sample *sample,
1753 		       struct evsel *evsel,
1754 		       struct thread *thread,
1755 		       struct addr_location *al)
1756 {
1757 	int depth = thread_stack__depth(thread, sample->cpu);
1758 
1759 	if (!symbol_conf.graph_function)
1760 		return true;
1761 
1762 	if (thread->filter) {
1763 		if (depth <= thread->filter_entry_depth) {
1764 			thread->filter = false;
1765 			return false;
1766 		}
1767 		return true;
1768 	} else {
1769 		const char *s = symbol_conf.graph_function;
1770 		u64 ip;
1771 		const char *name = resolve_branch_sym(sample, evsel, thread, al,
1772 				&ip);
1773 		unsigned nlen;
1774 
1775 		if (!name)
1776 			return false;
1777 		nlen = strlen(name);
1778 		while (*s) {
1779 			unsigned len = strcspn(s, ",");
1780 			if (nlen == len && !strncmp(name, s, len)) {
1781 				thread->filter = true;
1782 				thread->filter_entry_depth = depth;
1783 				return true;
1784 			}
1785 			s += len;
1786 			if (*s == ',')
1787 				s++;
1788 		}
1789 		return false;
1790 	}
1791 }
1792 
1793 static void process_event(struct perf_script *script,
1794 			  struct perf_sample *sample, struct evsel *evsel,
1795 			  struct addr_location *al,
1796 			  struct machine *machine)
1797 {
1798 	struct thread *thread = al->thread;
1799 	struct perf_event_attr *attr = &evsel->core.attr;
1800 	unsigned int type = output_type(attr->type);
1801 	struct evsel_script *es = evsel->priv;
1802 	FILE *fp = es->fp;
1803 
1804 	if (output[type].fields == 0)
1805 		return;
1806 
1807 	if (!show_event(sample, evsel, thread, al))
1808 		return;
1809 
1810 	if (evswitch__discard(&script->evswitch, evsel))
1811 		return;
1812 
1813 	++es->samples;
1814 
1815 	perf_sample__fprintf_start(sample, thread, evsel,
1816 				   PERF_RECORD_SAMPLE, fp);
1817 
1818 	if (PRINT_FIELD(PERIOD))
1819 		fprintf(fp, "%10" PRIu64 " ", sample->period);
1820 
1821 	if (PRINT_FIELD(EVNAME)) {
1822 		const char *evname = perf_evsel__name(evsel);
1823 
1824 		if (!script->name_width)
1825 			script->name_width = perf_evlist__max_name_len(script->session->evlist);
1826 
1827 		fprintf(fp, "%*s: ", script->name_width, evname ?: "[unknown]");
1828 	}
1829 
1830 	if (print_flags)
1831 		perf_sample__fprintf_flags(sample->flags, fp);
1832 
1833 	if (is_bts_event(attr)) {
1834 		perf_sample__fprintf_bts(sample, evsel, thread, al, machine, fp);
1835 		return;
1836 	}
1837 
1838 	if (PRINT_FIELD(TRACE) && sample->raw_data) {
1839 		event_format__fprintf(evsel->tp_format, sample->cpu,
1840 				      sample->raw_data, sample->raw_size, fp);
1841 	}
1842 
1843 	if (attr->type == PERF_TYPE_SYNTH && PRINT_FIELD(SYNTH))
1844 		perf_sample__fprintf_synth(sample, evsel, fp);
1845 
1846 	if (PRINT_FIELD(ADDR))
1847 		perf_sample__fprintf_addr(sample, thread, attr, fp);
1848 
1849 	if (PRINT_FIELD(DATA_SRC))
1850 		data_src__fprintf(sample->data_src, fp);
1851 
1852 	if (PRINT_FIELD(WEIGHT))
1853 		fprintf(fp, "%16" PRIu64, sample->weight);
1854 
1855 	if (PRINT_FIELD(IP)) {
1856 		struct callchain_cursor *cursor = NULL;
1857 
1858 		if (symbol_conf.use_callchain && sample->callchain &&
1859 		    thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
1860 					      sample, NULL, NULL, scripting_max_stack) == 0)
1861 			cursor = &callchain_cursor;
1862 
1863 		fputc(cursor ? '\n' : ' ', fp);
1864 		sample__fprintf_sym(sample, al, 0, output[type].print_ip_opts, cursor, fp);
1865 	}
1866 
1867 	if (PRINT_FIELD(IREGS))
1868 		perf_sample__fprintf_iregs(sample, attr, fp);
1869 
1870 	if (PRINT_FIELD(UREGS))
1871 		perf_sample__fprintf_uregs(sample, attr, fp);
1872 
1873 	if (PRINT_FIELD(BRSTACK))
1874 		perf_sample__fprintf_brstack(sample, thread, attr, fp);
1875 	else if (PRINT_FIELD(BRSTACKSYM))
1876 		perf_sample__fprintf_brstacksym(sample, thread, attr, fp);
1877 	else if (PRINT_FIELD(BRSTACKOFF))
1878 		perf_sample__fprintf_brstackoff(sample, thread, attr, fp);
1879 
1880 	if (perf_evsel__is_bpf_output(evsel) && PRINT_FIELD(BPF_OUTPUT))
1881 		perf_sample__fprintf_bpf_output(sample, fp);
1882 	perf_sample__fprintf_insn(sample, attr, thread, machine, fp);
1883 
1884 	if (PRINT_FIELD(PHYS_ADDR))
1885 		fprintf(fp, "%16" PRIx64, sample->phys_addr);
1886 
1887 	perf_sample__fprintf_ipc(sample, attr, fp);
1888 
1889 	fprintf(fp, "\n");
1890 
1891 	if (PRINT_FIELD(SRCCODE)) {
1892 		if (map__fprintf_srccode(al->map, al->addr, stdout,
1893 					 &thread->srccode_state))
1894 			printf("\n");
1895 	}
1896 
1897 	if (PRINT_FIELD(METRIC))
1898 		perf_sample__fprint_metric(script, thread, evsel, sample, fp);
1899 
1900 	if (verbose)
1901 		fflush(fp);
1902 }
1903 
1904 static struct scripting_ops	*scripting_ops;
1905 
1906 static void __process_stat(struct evsel *counter, u64 tstamp)
1907 {
1908 	int nthreads = thread_map__nr(counter->core.threads);
1909 	int ncpus = perf_evsel__nr_cpus(counter);
1910 	int cpu, thread;
1911 	static int header_printed;
1912 
1913 	if (counter->system_wide)
1914 		nthreads = 1;
1915 
1916 	if (!header_printed) {
1917 		printf("%3s %8s %15s %15s %15s %15s %s\n",
1918 		       "CPU", "THREAD", "VAL", "ENA", "RUN", "TIME", "EVENT");
1919 		header_printed = 1;
1920 	}
1921 
1922 	for (thread = 0; thread < nthreads; thread++) {
1923 		for (cpu = 0; cpu < ncpus; cpu++) {
1924 			struct perf_counts_values *counts;
1925 
1926 			counts = perf_counts(counter->counts, cpu, thread);
1927 
1928 			printf("%3d %8d %15" PRIu64 " %15" PRIu64 " %15" PRIu64 " %15" PRIu64 " %s\n",
1929 				counter->core.cpus->map[cpu],
1930 				thread_map__pid(counter->core.threads, thread),
1931 				counts->val,
1932 				counts->ena,
1933 				counts->run,
1934 				tstamp,
1935 				perf_evsel__name(counter));
1936 		}
1937 	}
1938 }
1939 
1940 static void process_stat(struct evsel *counter, u64 tstamp)
1941 {
1942 	if (scripting_ops && scripting_ops->process_stat)
1943 		scripting_ops->process_stat(&stat_config, counter, tstamp);
1944 	else
1945 		__process_stat(counter, tstamp);
1946 }
1947 
1948 static void process_stat_interval(u64 tstamp)
1949 {
1950 	if (scripting_ops && scripting_ops->process_stat_interval)
1951 		scripting_ops->process_stat_interval(tstamp);
1952 }
1953 
1954 static void setup_scripting(void)
1955 {
1956 	setup_perl_scripting();
1957 	setup_python_scripting();
1958 }
1959 
1960 static int flush_scripting(void)
1961 {
1962 	return scripting_ops ? scripting_ops->flush_script() : 0;
1963 }
1964 
1965 static int cleanup_scripting(void)
1966 {
1967 	pr_debug("\nperf script stopped\n");
1968 
1969 	return scripting_ops ? scripting_ops->stop_script() : 0;
1970 }
1971 
1972 static bool filter_cpu(struct perf_sample *sample)
1973 {
1974 	if (cpu_list)
1975 		return !test_bit(sample->cpu, cpu_bitmap);
1976 	return false;
1977 }
1978 
1979 static int process_sample_event(struct perf_tool *tool,
1980 				union perf_event *event,
1981 				struct perf_sample *sample,
1982 				struct evsel *evsel,
1983 				struct machine *machine)
1984 {
1985 	struct perf_script *scr = container_of(tool, struct perf_script, tool);
1986 	struct addr_location al;
1987 
1988 	if (perf_time__ranges_skip_sample(scr->ptime_range, scr->range_num,
1989 					  sample->time)) {
1990 		return 0;
1991 	}
1992 
1993 	if (debug_mode) {
1994 		if (sample->time < last_timestamp) {
1995 			pr_err("Samples misordered, previous: %" PRIu64
1996 				" this: %" PRIu64 "\n", last_timestamp,
1997 				sample->time);
1998 			nr_unordered++;
1999 		}
2000 		last_timestamp = sample->time;
2001 		return 0;
2002 	}
2003 
2004 	if (machine__resolve(machine, &al, sample) < 0) {
2005 		pr_err("problem processing %d event, skipping it.\n",
2006 		       event->header.type);
2007 		return -1;
2008 	}
2009 
2010 	if (al.filtered)
2011 		goto out_put;
2012 
2013 	if (filter_cpu(sample))
2014 		goto out_put;
2015 
2016 	if (scripting_ops)
2017 		scripting_ops->process_event(event, sample, evsel, &al);
2018 	else
2019 		process_event(scr, sample, evsel, &al, machine);
2020 
2021 out_put:
2022 	addr_location__put(&al);
2023 	return 0;
2024 }
2025 
2026 static int process_attr(struct perf_tool *tool, union perf_event *event,
2027 			struct evlist **pevlist)
2028 {
2029 	struct perf_script *scr = container_of(tool, struct perf_script, tool);
2030 	struct evlist *evlist;
2031 	struct evsel *evsel, *pos;
2032 	int err;
2033 	static struct evsel_script *es;
2034 
2035 	err = perf_event__process_attr(tool, event, pevlist);
2036 	if (err)
2037 		return err;
2038 
2039 	evlist = *pevlist;
2040 	evsel = perf_evlist__last(*pevlist);
2041 
2042 	if (!evsel->priv) {
2043 		if (scr->per_event_dump) {
2044 			evsel->priv = perf_evsel_script__new(evsel,
2045 						scr->session->data);
2046 		} else {
2047 			es = zalloc(sizeof(*es));
2048 			if (!es)
2049 				return -ENOMEM;
2050 			es->fp = stdout;
2051 			evsel->priv = es;
2052 		}
2053 	}
2054 
2055 	if (evsel->core.attr.type >= PERF_TYPE_MAX &&
2056 	    evsel->core.attr.type != PERF_TYPE_SYNTH)
2057 		return 0;
2058 
2059 	evlist__for_each_entry(evlist, pos) {
2060 		if (pos->core.attr.type == evsel->core.attr.type && pos != evsel)
2061 			return 0;
2062 	}
2063 
2064 	set_print_ip_opts(&evsel->core.attr);
2065 
2066 	if (evsel->core.attr.sample_type)
2067 		err = perf_evsel__check_attr(evsel, scr->session);
2068 
2069 	return err;
2070 }
2071 
2072 static int process_comm_event(struct perf_tool *tool,
2073 			      union perf_event *event,
2074 			      struct perf_sample *sample,
2075 			      struct machine *machine)
2076 {
2077 	struct thread *thread;
2078 	struct perf_script *script = container_of(tool, struct perf_script, tool);
2079 	struct perf_session *session = script->session;
2080 	struct evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2081 	int ret = -1;
2082 
2083 	thread = machine__findnew_thread(machine, event->comm.pid, event->comm.tid);
2084 	if (thread == NULL) {
2085 		pr_debug("problem processing COMM event, skipping it.\n");
2086 		return -1;
2087 	}
2088 
2089 	if (perf_event__process_comm(tool, event, sample, machine) < 0)
2090 		goto out;
2091 
2092 	if (!evsel->core.attr.sample_id_all) {
2093 		sample->cpu = 0;
2094 		sample->time = 0;
2095 		sample->tid = event->comm.tid;
2096 		sample->pid = event->comm.pid;
2097 	}
2098 	if (!filter_cpu(sample)) {
2099 		perf_sample__fprintf_start(sample, thread, evsel,
2100 				   PERF_RECORD_COMM, stdout);
2101 		perf_event__fprintf(event, stdout);
2102 	}
2103 	ret = 0;
2104 out:
2105 	thread__put(thread);
2106 	return ret;
2107 }
2108 
2109 static int process_namespaces_event(struct perf_tool *tool,
2110 				    union perf_event *event,
2111 				    struct perf_sample *sample,
2112 				    struct machine *machine)
2113 {
2114 	struct thread *thread;
2115 	struct perf_script *script = container_of(tool, struct perf_script, tool);
2116 	struct perf_session *session = script->session;
2117 	struct evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2118 	int ret = -1;
2119 
2120 	thread = machine__findnew_thread(machine, event->namespaces.pid,
2121 					 event->namespaces.tid);
2122 	if (thread == NULL) {
2123 		pr_debug("problem processing NAMESPACES event, skipping it.\n");
2124 		return -1;
2125 	}
2126 
2127 	if (perf_event__process_namespaces(tool, event, sample, machine) < 0)
2128 		goto out;
2129 
2130 	if (!evsel->core.attr.sample_id_all) {
2131 		sample->cpu = 0;
2132 		sample->time = 0;
2133 		sample->tid = event->namespaces.tid;
2134 		sample->pid = event->namespaces.pid;
2135 	}
2136 	if (!filter_cpu(sample)) {
2137 		perf_sample__fprintf_start(sample, thread, evsel,
2138 					   PERF_RECORD_NAMESPACES, stdout);
2139 		perf_event__fprintf(event, stdout);
2140 	}
2141 	ret = 0;
2142 out:
2143 	thread__put(thread);
2144 	return ret;
2145 }
2146 
2147 static int process_fork_event(struct perf_tool *tool,
2148 			      union perf_event *event,
2149 			      struct perf_sample *sample,
2150 			      struct machine *machine)
2151 {
2152 	struct thread *thread;
2153 	struct perf_script *script = container_of(tool, struct perf_script, tool);
2154 	struct perf_session *session = script->session;
2155 	struct evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2156 
2157 	if (perf_event__process_fork(tool, event, sample, machine) < 0)
2158 		return -1;
2159 
2160 	thread = machine__findnew_thread(machine, event->fork.pid, event->fork.tid);
2161 	if (thread == NULL) {
2162 		pr_debug("problem processing FORK event, skipping it.\n");
2163 		return -1;
2164 	}
2165 
2166 	if (!evsel->core.attr.sample_id_all) {
2167 		sample->cpu = 0;
2168 		sample->time = event->fork.time;
2169 		sample->tid = event->fork.tid;
2170 		sample->pid = event->fork.pid;
2171 	}
2172 	if (!filter_cpu(sample)) {
2173 		perf_sample__fprintf_start(sample, thread, evsel,
2174 					   PERF_RECORD_FORK, stdout);
2175 		perf_event__fprintf(event, stdout);
2176 	}
2177 	thread__put(thread);
2178 
2179 	return 0;
2180 }
2181 static int process_exit_event(struct perf_tool *tool,
2182 			      union perf_event *event,
2183 			      struct perf_sample *sample,
2184 			      struct machine *machine)
2185 {
2186 	int err = 0;
2187 	struct thread *thread;
2188 	struct perf_script *script = container_of(tool, struct perf_script, tool);
2189 	struct perf_session *session = script->session;
2190 	struct evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2191 
2192 	thread = machine__findnew_thread(machine, event->fork.pid, event->fork.tid);
2193 	if (thread == NULL) {
2194 		pr_debug("problem processing EXIT event, skipping it.\n");
2195 		return -1;
2196 	}
2197 
2198 	if (!evsel->core.attr.sample_id_all) {
2199 		sample->cpu = 0;
2200 		sample->time = 0;
2201 		sample->tid = event->fork.tid;
2202 		sample->pid = event->fork.pid;
2203 	}
2204 	if (!filter_cpu(sample)) {
2205 		perf_sample__fprintf_start(sample, thread, evsel,
2206 					   PERF_RECORD_EXIT, stdout);
2207 		perf_event__fprintf(event, stdout);
2208 	}
2209 
2210 	if (perf_event__process_exit(tool, event, sample, machine) < 0)
2211 		err = -1;
2212 
2213 	thread__put(thread);
2214 	return err;
2215 }
2216 
2217 static int process_mmap_event(struct perf_tool *tool,
2218 			      union perf_event *event,
2219 			      struct perf_sample *sample,
2220 			      struct machine *machine)
2221 {
2222 	struct thread *thread;
2223 	struct perf_script *script = container_of(tool, struct perf_script, tool);
2224 	struct perf_session *session = script->session;
2225 	struct evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2226 
2227 	if (perf_event__process_mmap(tool, event, sample, machine) < 0)
2228 		return -1;
2229 
2230 	thread = machine__findnew_thread(machine, event->mmap.pid, event->mmap.tid);
2231 	if (thread == NULL) {
2232 		pr_debug("problem processing MMAP event, skipping it.\n");
2233 		return -1;
2234 	}
2235 
2236 	if (!evsel->core.attr.sample_id_all) {
2237 		sample->cpu = 0;
2238 		sample->time = 0;
2239 		sample->tid = event->mmap.tid;
2240 		sample->pid = event->mmap.pid;
2241 	}
2242 	if (!filter_cpu(sample)) {
2243 		perf_sample__fprintf_start(sample, thread, evsel,
2244 					   PERF_RECORD_MMAP, stdout);
2245 		perf_event__fprintf(event, stdout);
2246 	}
2247 	thread__put(thread);
2248 	return 0;
2249 }
2250 
2251 static int process_mmap2_event(struct perf_tool *tool,
2252 			      union perf_event *event,
2253 			      struct perf_sample *sample,
2254 			      struct machine *machine)
2255 {
2256 	struct thread *thread;
2257 	struct perf_script *script = container_of(tool, struct perf_script, tool);
2258 	struct perf_session *session = script->session;
2259 	struct evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2260 
2261 	if (perf_event__process_mmap2(tool, event, sample, machine) < 0)
2262 		return -1;
2263 
2264 	thread = machine__findnew_thread(machine, event->mmap2.pid, event->mmap2.tid);
2265 	if (thread == NULL) {
2266 		pr_debug("problem processing MMAP2 event, skipping it.\n");
2267 		return -1;
2268 	}
2269 
2270 	if (!evsel->core.attr.sample_id_all) {
2271 		sample->cpu = 0;
2272 		sample->time = 0;
2273 		sample->tid = event->mmap2.tid;
2274 		sample->pid = event->mmap2.pid;
2275 	}
2276 	if (!filter_cpu(sample)) {
2277 		perf_sample__fprintf_start(sample, thread, evsel,
2278 					   PERF_RECORD_MMAP2, stdout);
2279 		perf_event__fprintf(event, stdout);
2280 	}
2281 	thread__put(thread);
2282 	return 0;
2283 }
2284 
2285 static int process_switch_event(struct perf_tool *tool,
2286 				union perf_event *event,
2287 				struct perf_sample *sample,
2288 				struct machine *machine)
2289 {
2290 	struct thread *thread;
2291 	struct perf_script *script = container_of(tool, struct perf_script, tool);
2292 	struct perf_session *session = script->session;
2293 	struct evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2294 
2295 	if (perf_event__process_switch(tool, event, sample, machine) < 0)
2296 		return -1;
2297 
2298 	if (scripting_ops && scripting_ops->process_switch)
2299 		scripting_ops->process_switch(event, sample, machine);
2300 
2301 	if (!script->show_switch_events)
2302 		return 0;
2303 
2304 	thread = machine__findnew_thread(machine, sample->pid,
2305 					 sample->tid);
2306 	if (thread == NULL) {
2307 		pr_debug("problem processing SWITCH event, skipping it.\n");
2308 		return -1;
2309 	}
2310 
2311 	if (!filter_cpu(sample)) {
2312 		perf_sample__fprintf_start(sample, thread, evsel,
2313 					   PERF_RECORD_SWITCH, stdout);
2314 		perf_event__fprintf(event, stdout);
2315 	}
2316 	thread__put(thread);
2317 	return 0;
2318 }
2319 
2320 static int
2321 process_lost_event(struct perf_tool *tool,
2322 		   union perf_event *event,
2323 		   struct perf_sample *sample,
2324 		   struct machine *machine)
2325 {
2326 	struct perf_script *script = container_of(tool, struct perf_script, tool);
2327 	struct perf_session *session = script->session;
2328 	struct evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2329 	struct thread *thread;
2330 
2331 	thread = machine__findnew_thread(machine, sample->pid,
2332 					 sample->tid);
2333 	if (thread == NULL)
2334 		return -1;
2335 
2336 	if (!filter_cpu(sample)) {
2337 		perf_sample__fprintf_start(sample, thread, evsel,
2338 					   PERF_RECORD_LOST, stdout);
2339 		perf_event__fprintf(event, stdout);
2340 	}
2341 	thread__put(thread);
2342 	return 0;
2343 }
2344 
2345 static int
2346 process_finished_round_event(struct perf_tool *tool __maybe_unused,
2347 			     union perf_event *event,
2348 			     struct ordered_events *oe __maybe_unused)
2349 
2350 {
2351 	perf_event__fprintf(event, stdout);
2352 	return 0;
2353 }
2354 
2355 static int
2356 process_bpf_events(struct perf_tool *tool __maybe_unused,
2357 		   union perf_event *event,
2358 		   struct perf_sample *sample,
2359 		   struct machine *machine)
2360 {
2361 	struct thread *thread;
2362 	struct perf_script *script = container_of(tool, struct perf_script, tool);
2363 	struct perf_session *session = script->session;
2364 	struct evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
2365 
2366 	if (machine__process_ksymbol(machine, event, sample) < 0)
2367 		return -1;
2368 
2369 	if (!evsel->core.attr.sample_id_all) {
2370 		perf_event__fprintf(event, stdout);
2371 		return 0;
2372 	}
2373 
2374 	thread = machine__findnew_thread(machine, sample->pid, sample->tid);
2375 	if (thread == NULL) {
2376 		pr_debug("problem processing MMAP event, skipping it.\n");
2377 		return -1;
2378 	}
2379 
2380 	if (!filter_cpu(sample)) {
2381 		perf_sample__fprintf_start(sample, thread, evsel,
2382 					   event->header.type, stdout);
2383 		perf_event__fprintf(event, stdout);
2384 	}
2385 
2386 	thread__put(thread);
2387 	return 0;
2388 }
2389 
2390 static void sig_handler(int sig __maybe_unused)
2391 {
2392 	session_done = 1;
2393 }
2394 
2395 static void perf_script__fclose_per_event_dump(struct perf_script *script)
2396 {
2397 	struct evlist *evlist = script->session->evlist;
2398 	struct evsel *evsel;
2399 
2400 	evlist__for_each_entry(evlist, evsel) {
2401 		if (!evsel->priv)
2402 			break;
2403 		perf_evsel_script__delete(evsel->priv);
2404 		evsel->priv = NULL;
2405 	}
2406 }
2407 
2408 static int perf_script__fopen_per_event_dump(struct perf_script *script)
2409 {
2410 	struct evsel *evsel;
2411 
2412 	evlist__for_each_entry(script->session->evlist, evsel) {
2413 		/*
2414 		 * Already setup? I.e. we may be called twice in cases like
2415 		 * Intel PT, one for the intel_pt// and dummy events, then
2416 		 * for the evsels syntheized from the auxtrace info.
2417 		 *
2418 		 * Ses perf_script__process_auxtrace_info.
2419 		 */
2420 		if (evsel->priv != NULL)
2421 			continue;
2422 
2423 		evsel->priv = perf_evsel_script__new(evsel, script->session->data);
2424 		if (evsel->priv == NULL)
2425 			goto out_err_fclose;
2426 	}
2427 
2428 	return 0;
2429 
2430 out_err_fclose:
2431 	perf_script__fclose_per_event_dump(script);
2432 	return -1;
2433 }
2434 
2435 static int perf_script__setup_per_event_dump(struct perf_script *script)
2436 {
2437 	struct evsel *evsel;
2438 	static struct evsel_script es_stdout;
2439 
2440 	if (script->per_event_dump)
2441 		return perf_script__fopen_per_event_dump(script);
2442 
2443 	es_stdout.fp = stdout;
2444 
2445 	evlist__for_each_entry(script->session->evlist, evsel)
2446 		evsel->priv = &es_stdout;
2447 
2448 	return 0;
2449 }
2450 
2451 static void perf_script__exit_per_event_dump_stats(struct perf_script *script)
2452 {
2453 	struct evsel *evsel;
2454 
2455 	evlist__for_each_entry(script->session->evlist, evsel) {
2456 		struct evsel_script *es = evsel->priv;
2457 
2458 		perf_evsel_script__fprintf(es, stdout);
2459 		perf_evsel_script__delete(es);
2460 		evsel->priv = NULL;
2461 	}
2462 }
2463 
2464 static int __cmd_script(struct perf_script *script)
2465 {
2466 	int ret;
2467 
2468 	signal(SIGINT, sig_handler);
2469 
2470 	perf_stat__init_shadow_stats();
2471 
2472 	/* override event processing functions */
2473 	if (script->show_task_events) {
2474 		script->tool.comm = process_comm_event;
2475 		script->tool.fork = process_fork_event;
2476 		script->tool.exit = process_exit_event;
2477 	}
2478 	if (script->show_mmap_events) {
2479 		script->tool.mmap = process_mmap_event;
2480 		script->tool.mmap2 = process_mmap2_event;
2481 	}
2482 	if (script->show_switch_events || (scripting_ops && scripting_ops->process_switch))
2483 		script->tool.context_switch = process_switch_event;
2484 	if (script->show_namespace_events)
2485 		script->tool.namespaces = process_namespaces_event;
2486 	if (script->show_lost_events)
2487 		script->tool.lost = process_lost_event;
2488 	if (script->show_round_events) {
2489 		script->tool.ordered_events = false;
2490 		script->tool.finished_round = process_finished_round_event;
2491 	}
2492 	if (script->show_bpf_events) {
2493 		script->tool.ksymbol   = process_bpf_events;
2494 		script->tool.bpf_event = process_bpf_events;
2495 	}
2496 
2497 	if (perf_script__setup_per_event_dump(script)) {
2498 		pr_err("Couldn't create the per event dump files\n");
2499 		return -1;
2500 	}
2501 
2502 	ret = perf_session__process_events(script->session);
2503 
2504 	if (script->per_event_dump)
2505 		perf_script__exit_per_event_dump_stats(script);
2506 
2507 	if (debug_mode)
2508 		pr_err("Misordered timestamps: %" PRIu64 "\n", nr_unordered);
2509 
2510 	return ret;
2511 }
2512 
2513 struct script_spec {
2514 	struct list_head	node;
2515 	struct scripting_ops	*ops;
2516 	char			spec[0];
2517 };
2518 
2519 static LIST_HEAD(script_specs);
2520 
2521 static struct script_spec *script_spec__new(const char *spec,
2522 					    struct scripting_ops *ops)
2523 {
2524 	struct script_spec *s = malloc(sizeof(*s) + strlen(spec) + 1);
2525 
2526 	if (s != NULL) {
2527 		strcpy(s->spec, spec);
2528 		s->ops = ops;
2529 	}
2530 
2531 	return s;
2532 }
2533 
2534 static void script_spec__add(struct script_spec *s)
2535 {
2536 	list_add_tail(&s->node, &script_specs);
2537 }
2538 
2539 static struct script_spec *script_spec__find(const char *spec)
2540 {
2541 	struct script_spec *s;
2542 
2543 	list_for_each_entry(s, &script_specs, node)
2544 		if (strcasecmp(s->spec, spec) == 0)
2545 			return s;
2546 	return NULL;
2547 }
2548 
2549 int script_spec_register(const char *spec, struct scripting_ops *ops)
2550 {
2551 	struct script_spec *s;
2552 
2553 	s = script_spec__find(spec);
2554 	if (s)
2555 		return -1;
2556 
2557 	s = script_spec__new(spec, ops);
2558 	if (!s)
2559 		return -1;
2560 	else
2561 		script_spec__add(s);
2562 
2563 	return 0;
2564 }
2565 
2566 static struct scripting_ops *script_spec__lookup(const char *spec)
2567 {
2568 	struct script_spec *s = script_spec__find(spec);
2569 	if (!s)
2570 		return NULL;
2571 
2572 	return s->ops;
2573 }
2574 
2575 static void list_available_languages(void)
2576 {
2577 	struct script_spec *s;
2578 
2579 	fprintf(stderr, "\n");
2580 	fprintf(stderr, "Scripting language extensions (used in "
2581 		"perf script -s [spec:]script.[spec]):\n\n");
2582 
2583 	list_for_each_entry(s, &script_specs, node)
2584 		fprintf(stderr, "  %-42s [%s]\n", s->spec, s->ops->name);
2585 
2586 	fprintf(stderr, "\n");
2587 }
2588 
2589 static int parse_scriptname(const struct option *opt __maybe_unused,
2590 			    const char *str, int unset __maybe_unused)
2591 {
2592 	char spec[PATH_MAX];
2593 	const char *script, *ext;
2594 	int len;
2595 
2596 	if (strcmp(str, "lang") == 0) {
2597 		list_available_languages();
2598 		exit(0);
2599 	}
2600 
2601 	script = strchr(str, ':');
2602 	if (script) {
2603 		len = script - str;
2604 		if (len >= PATH_MAX) {
2605 			fprintf(stderr, "invalid language specifier");
2606 			return -1;
2607 		}
2608 		strncpy(spec, str, len);
2609 		spec[len] = '\0';
2610 		scripting_ops = script_spec__lookup(spec);
2611 		if (!scripting_ops) {
2612 			fprintf(stderr, "invalid language specifier");
2613 			return -1;
2614 		}
2615 		script++;
2616 	} else {
2617 		script = str;
2618 		ext = strrchr(script, '.');
2619 		if (!ext) {
2620 			fprintf(stderr, "invalid script extension");
2621 			return -1;
2622 		}
2623 		scripting_ops = script_spec__lookup(++ext);
2624 		if (!scripting_ops) {
2625 			fprintf(stderr, "invalid script extension");
2626 			return -1;
2627 		}
2628 	}
2629 
2630 	script_name = strdup(script);
2631 
2632 	return 0;
2633 }
2634 
2635 static int parse_output_fields(const struct option *opt __maybe_unused,
2636 			    const char *arg, int unset __maybe_unused)
2637 {
2638 	char *tok, *strtok_saveptr = NULL;
2639 	int i, imax = ARRAY_SIZE(all_output_options);
2640 	int j;
2641 	int rc = 0;
2642 	char *str = strdup(arg);
2643 	int type = -1;
2644 	enum { DEFAULT, SET, ADD, REMOVE } change = DEFAULT;
2645 
2646 	if (!str)
2647 		return -ENOMEM;
2648 
2649 	/* first word can state for which event type the user is specifying
2650 	 * the fields. If no type exists, the specified fields apply to all
2651 	 * event types found in the file minus the invalid fields for a type.
2652 	 */
2653 	tok = strchr(str, ':');
2654 	if (tok) {
2655 		*tok = '\0';
2656 		tok++;
2657 		if (!strcmp(str, "hw"))
2658 			type = PERF_TYPE_HARDWARE;
2659 		else if (!strcmp(str, "sw"))
2660 			type = PERF_TYPE_SOFTWARE;
2661 		else if (!strcmp(str, "trace"))
2662 			type = PERF_TYPE_TRACEPOINT;
2663 		else if (!strcmp(str, "raw"))
2664 			type = PERF_TYPE_RAW;
2665 		else if (!strcmp(str, "break"))
2666 			type = PERF_TYPE_BREAKPOINT;
2667 		else if (!strcmp(str, "synth"))
2668 			type = OUTPUT_TYPE_SYNTH;
2669 		else {
2670 			fprintf(stderr, "Invalid event type in field string.\n");
2671 			rc = -EINVAL;
2672 			goto out;
2673 		}
2674 
2675 		if (output[type].user_set)
2676 			pr_warning("Overriding previous field request for %s events.\n",
2677 				   event_type(type));
2678 
2679 		/* Don't override defaults for +- */
2680 		if (strchr(tok, '+') || strchr(tok, '-'))
2681 			goto parse;
2682 
2683 		output[type].fields = 0;
2684 		output[type].user_set = true;
2685 		output[type].wildcard_set = false;
2686 
2687 	} else {
2688 		tok = str;
2689 		if (strlen(str) == 0) {
2690 			fprintf(stderr,
2691 				"Cannot set fields to 'none' for all event types.\n");
2692 			rc = -EINVAL;
2693 			goto out;
2694 		}
2695 
2696 		/* Don't override defaults for +- */
2697 		if (strchr(str, '+') || strchr(str, '-'))
2698 			goto parse;
2699 
2700 		if (output_set_by_user())
2701 			pr_warning("Overriding previous field request for all events.\n");
2702 
2703 		for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
2704 			output[j].fields = 0;
2705 			output[j].user_set = true;
2706 			output[j].wildcard_set = true;
2707 		}
2708 	}
2709 
2710 parse:
2711 	for (tok = strtok_r(tok, ",", &strtok_saveptr); tok; tok = strtok_r(NULL, ",", &strtok_saveptr)) {
2712 		if (*tok == '+') {
2713 			if (change == SET)
2714 				goto out_badmix;
2715 			change = ADD;
2716 			tok++;
2717 		} else if (*tok == '-') {
2718 			if (change == SET)
2719 				goto out_badmix;
2720 			change = REMOVE;
2721 			tok++;
2722 		} else {
2723 			if (change != SET && change != DEFAULT)
2724 				goto out_badmix;
2725 			change = SET;
2726 		}
2727 
2728 		for (i = 0; i < imax; ++i) {
2729 			if (strcmp(tok, all_output_options[i].str) == 0)
2730 				break;
2731 		}
2732 		if (i == imax && strcmp(tok, "flags") == 0) {
2733 			print_flags = change == REMOVE ? false : true;
2734 			continue;
2735 		}
2736 		if (i == imax) {
2737 			fprintf(stderr, "Invalid field requested.\n");
2738 			rc = -EINVAL;
2739 			goto out;
2740 		}
2741 
2742 		if (type == -1) {
2743 			/* add user option to all events types for
2744 			 * which it is valid
2745 			 */
2746 			for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
2747 				if (output[j].invalid_fields & all_output_options[i].field) {
2748 					pr_warning("\'%s\' not valid for %s events. Ignoring.\n",
2749 						   all_output_options[i].str, event_type(j));
2750 				} else {
2751 					if (change == REMOVE) {
2752 						output[j].fields &= ~all_output_options[i].field;
2753 						output[j].user_set_fields &= ~all_output_options[i].field;
2754 					} else {
2755 						output[j].fields |= all_output_options[i].field;
2756 						output[j].user_set_fields |= all_output_options[i].field;
2757 					}
2758 					output[j].user_set = true;
2759 					output[j].wildcard_set = true;
2760 				}
2761 			}
2762 		} else {
2763 			if (output[type].invalid_fields & all_output_options[i].field) {
2764 				fprintf(stderr, "\'%s\' not valid for %s events.\n",
2765 					 all_output_options[i].str, event_type(type));
2766 
2767 				rc = -EINVAL;
2768 				goto out;
2769 			}
2770 			if (change == REMOVE)
2771 				output[type].fields &= ~all_output_options[i].field;
2772 			else
2773 				output[type].fields |= all_output_options[i].field;
2774 			output[type].user_set = true;
2775 			output[type].wildcard_set = true;
2776 		}
2777 	}
2778 
2779 	if (type >= 0) {
2780 		if (output[type].fields == 0) {
2781 			pr_debug("No fields requested for %s type. "
2782 				 "Events will not be displayed.\n", event_type(type));
2783 		}
2784 	}
2785 	goto out;
2786 
2787 out_badmix:
2788 	fprintf(stderr, "Cannot mix +-field with overridden fields\n");
2789 	rc = -EINVAL;
2790 out:
2791 	free(str);
2792 	return rc;
2793 }
2794 
2795 #define for_each_lang(scripts_path, scripts_dir, lang_dirent)		\
2796 	while ((lang_dirent = readdir(scripts_dir)) != NULL)		\
2797 		if ((lang_dirent->d_type == DT_DIR ||			\
2798 		     (lang_dirent->d_type == DT_UNKNOWN &&		\
2799 		      is_directory(scripts_path, lang_dirent))) &&	\
2800 		    (strcmp(lang_dirent->d_name, ".")) &&		\
2801 		    (strcmp(lang_dirent->d_name, "..")))
2802 
2803 #define for_each_script(lang_path, lang_dir, script_dirent)		\
2804 	while ((script_dirent = readdir(lang_dir)) != NULL)		\
2805 		if (script_dirent->d_type != DT_DIR &&			\
2806 		    (script_dirent->d_type != DT_UNKNOWN ||		\
2807 		     !is_directory(lang_path, script_dirent)))
2808 
2809 
2810 #define RECORD_SUFFIX			"-record"
2811 #define REPORT_SUFFIX			"-report"
2812 
2813 struct script_desc {
2814 	struct list_head	node;
2815 	char			*name;
2816 	char			*half_liner;
2817 	char			*args;
2818 };
2819 
2820 static LIST_HEAD(script_descs);
2821 
2822 static struct script_desc *script_desc__new(const char *name)
2823 {
2824 	struct script_desc *s = zalloc(sizeof(*s));
2825 
2826 	if (s != NULL && name)
2827 		s->name = strdup(name);
2828 
2829 	return s;
2830 }
2831 
2832 static void script_desc__delete(struct script_desc *s)
2833 {
2834 	zfree(&s->name);
2835 	zfree(&s->half_liner);
2836 	zfree(&s->args);
2837 	free(s);
2838 }
2839 
2840 static void script_desc__add(struct script_desc *s)
2841 {
2842 	list_add_tail(&s->node, &script_descs);
2843 }
2844 
2845 static struct script_desc *script_desc__find(const char *name)
2846 {
2847 	struct script_desc *s;
2848 
2849 	list_for_each_entry(s, &script_descs, node)
2850 		if (strcasecmp(s->name, name) == 0)
2851 			return s;
2852 	return NULL;
2853 }
2854 
2855 static struct script_desc *script_desc__findnew(const char *name)
2856 {
2857 	struct script_desc *s = script_desc__find(name);
2858 
2859 	if (s)
2860 		return s;
2861 
2862 	s = script_desc__new(name);
2863 	if (!s)
2864 		return NULL;
2865 
2866 	script_desc__add(s);
2867 
2868 	return s;
2869 }
2870 
2871 static const char *ends_with(const char *str, const char *suffix)
2872 {
2873 	size_t suffix_len = strlen(suffix);
2874 	const char *p = str;
2875 
2876 	if (strlen(str) > suffix_len) {
2877 		p = str + strlen(str) - suffix_len;
2878 		if (!strncmp(p, suffix, suffix_len))
2879 			return p;
2880 	}
2881 
2882 	return NULL;
2883 }
2884 
2885 static int read_script_info(struct script_desc *desc, const char *filename)
2886 {
2887 	char line[BUFSIZ], *p;
2888 	FILE *fp;
2889 
2890 	fp = fopen(filename, "r");
2891 	if (!fp)
2892 		return -1;
2893 
2894 	while (fgets(line, sizeof(line), fp)) {
2895 		p = skip_spaces(line);
2896 		if (strlen(p) == 0)
2897 			continue;
2898 		if (*p != '#')
2899 			continue;
2900 		p++;
2901 		if (strlen(p) && *p == '!')
2902 			continue;
2903 
2904 		p = skip_spaces(p);
2905 		if (strlen(p) && p[strlen(p) - 1] == '\n')
2906 			p[strlen(p) - 1] = '\0';
2907 
2908 		if (!strncmp(p, "description:", strlen("description:"))) {
2909 			p += strlen("description:");
2910 			desc->half_liner = strdup(skip_spaces(p));
2911 			continue;
2912 		}
2913 
2914 		if (!strncmp(p, "args:", strlen("args:"))) {
2915 			p += strlen("args:");
2916 			desc->args = strdup(skip_spaces(p));
2917 			continue;
2918 		}
2919 	}
2920 
2921 	fclose(fp);
2922 
2923 	return 0;
2924 }
2925 
2926 static char *get_script_root(struct dirent *script_dirent, const char *suffix)
2927 {
2928 	char *script_root, *str;
2929 
2930 	script_root = strdup(script_dirent->d_name);
2931 	if (!script_root)
2932 		return NULL;
2933 
2934 	str = (char *)ends_with(script_root, suffix);
2935 	if (!str) {
2936 		free(script_root);
2937 		return NULL;
2938 	}
2939 
2940 	*str = '\0';
2941 	return script_root;
2942 }
2943 
2944 static int list_available_scripts(const struct option *opt __maybe_unused,
2945 				  const char *s __maybe_unused,
2946 				  int unset __maybe_unused)
2947 {
2948 	struct dirent *script_dirent, *lang_dirent;
2949 	char scripts_path[MAXPATHLEN];
2950 	DIR *scripts_dir, *lang_dir;
2951 	char script_path[MAXPATHLEN];
2952 	char lang_path[MAXPATHLEN];
2953 	struct script_desc *desc;
2954 	char first_half[BUFSIZ];
2955 	char *script_root;
2956 
2957 	snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2958 
2959 	scripts_dir = opendir(scripts_path);
2960 	if (!scripts_dir) {
2961 		fprintf(stdout,
2962 			"open(%s) failed.\n"
2963 			"Check \"PERF_EXEC_PATH\" env to set scripts dir.\n",
2964 			scripts_path);
2965 		exit(-1);
2966 	}
2967 
2968 	for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2969 		scnprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
2970 			  lang_dirent->d_name);
2971 		lang_dir = opendir(lang_path);
2972 		if (!lang_dir)
2973 			continue;
2974 
2975 		for_each_script(lang_path, lang_dir, script_dirent) {
2976 			script_root = get_script_root(script_dirent, REPORT_SUFFIX);
2977 			if (script_root) {
2978 				desc = script_desc__findnew(script_root);
2979 				scnprintf(script_path, MAXPATHLEN, "%s/%s",
2980 					  lang_path, script_dirent->d_name);
2981 				read_script_info(desc, script_path);
2982 				free(script_root);
2983 			}
2984 		}
2985 	}
2986 
2987 	fprintf(stdout, "List of available trace scripts:\n");
2988 	list_for_each_entry(desc, &script_descs, node) {
2989 		sprintf(first_half, "%s %s", desc->name,
2990 			desc->args ? desc->args : "");
2991 		fprintf(stdout, "  %-36s %s\n", first_half,
2992 			desc->half_liner ? desc->half_liner : "");
2993 	}
2994 
2995 	exit(0);
2996 }
2997 
2998 /*
2999  * Some scripts specify the required events in their "xxx-record" file,
3000  * this function will check if the events in perf.data match those
3001  * mentioned in the "xxx-record".
3002  *
3003  * Fixme: All existing "xxx-record" are all in good formats "-e event ",
3004  * which is covered well now. And new parsing code should be added to
3005  * cover the future complexing formats like event groups etc.
3006  */
3007 static int check_ev_match(char *dir_name, char *scriptname,
3008 			struct perf_session *session)
3009 {
3010 	char filename[MAXPATHLEN], evname[128];
3011 	char line[BUFSIZ], *p;
3012 	struct evsel *pos;
3013 	int match, len;
3014 	FILE *fp;
3015 
3016 	scnprintf(filename, MAXPATHLEN, "%s/bin/%s-record", dir_name, scriptname);
3017 
3018 	fp = fopen(filename, "r");
3019 	if (!fp)
3020 		return -1;
3021 
3022 	while (fgets(line, sizeof(line), fp)) {
3023 		p = skip_spaces(line);
3024 		if (*p == '#')
3025 			continue;
3026 
3027 		while (strlen(p)) {
3028 			p = strstr(p, "-e");
3029 			if (!p)
3030 				break;
3031 
3032 			p += 2;
3033 			p = skip_spaces(p);
3034 			len = strcspn(p, " \t");
3035 			if (!len)
3036 				break;
3037 
3038 			snprintf(evname, len + 1, "%s", p);
3039 
3040 			match = 0;
3041 			evlist__for_each_entry(session->evlist, pos) {
3042 				if (!strcmp(perf_evsel__name(pos), evname)) {
3043 					match = 1;
3044 					break;
3045 				}
3046 			}
3047 
3048 			if (!match) {
3049 				fclose(fp);
3050 				return -1;
3051 			}
3052 		}
3053 	}
3054 
3055 	fclose(fp);
3056 	return 0;
3057 }
3058 
3059 /*
3060  * Return -1 if none is found, otherwise the actual scripts number.
3061  *
3062  * Currently the only user of this function is the script browser, which
3063  * will list all statically runnable scripts, select one, execute it and
3064  * show the output in a perf browser.
3065  */
3066 int find_scripts(char **scripts_array, char **scripts_path_array, int num,
3067 		 int pathlen)
3068 {
3069 	struct dirent *script_dirent, *lang_dirent;
3070 	char scripts_path[MAXPATHLEN], lang_path[MAXPATHLEN];
3071 	DIR *scripts_dir, *lang_dir;
3072 	struct perf_session *session;
3073 	struct perf_data data = {
3074 		.path = input_name,
3075 		.mode = PERF_DATA_MODE_READ,
3076 	};
3077 	char *temp;
3078 	int i = 0;
3079 
3080 	session = perf_session__new(&data, false, NULL);
3081 	if (!session)
3082 		return -1;
3083 
3084 	snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
3085 
3086 	scripts_dir = opendir(scripts_path);
3087 	if (!scripts_dir) {
3088 		perf_session__delete(session);
3089 		return -1;
3090 	}
3091 
3092 	for_each_lang(scripts_path, scripts_dir, lang_dirent) {
3093 		scnprintf(lang_path, MAXPATHLEN, "%s/%s", scripts_path,
3094 			  lang_dirent->d_name);
3095 #ifndef HAVE_LIBPERL_SUPPORT
3096 		if (strstr(lang_path, "perl"))
3097 			continue;
3098 #endif
3099 #ifndef HAVE_LIBPYTHON_SUPPORT
3100 		if (strstr(lang_path, "python"))
3101 			continue;
3102 #endif
3103 
3104 		lang_dir = opendir(lang_path);
3105 		if (!lang_dir)
3106 			continue;
3107 
3108 		for_each_script(lang_path, lang_dir, script_dirent) {
3109 			/* Skip those real time scripts: xxxtop.p[yl] */
3110 			if (strstr(script_dirent->d_name, "top."))
3111 				continue;
3112 			if (i >= num)
3113 				break;
3114 			snprintf(scripts_path_array[i], pathlen, "%s/%s",
3115 				lang_path,
3116 				script_dirent->d_name);
3117 			temp = strchr(script_dirent->d_name, '.');
3118 			snprintf(scripts_array[i],
3119 				(temp - script_dirent->d_name) + 1,
3120 				"%s", script_dirent->d_name);
3121 
3122 			if (check_ev_match(lang_path,
3123 					scripts_array[i], session))
3124 				continue;
3125 
3126 			i++;
3127 		}
3128 		closedir(lang_dir);
3129 	}
3130 
3131 	closedir(scripts_dir);
3132 	perf_session__delete(session);
3133 	return i;
3134 }
3135 
3136 static char *get_script_path(const char *script_root, const char *suffix)
3137 {
3138 	struct dirent *script_dirent, *lang_dirent;
3139 	char scripts_path[MAXPATHLEN];
3140 	char script_path[MAXPATHLEN];
3141 	DIR *scripts_dir, *lang_dir;
3142 	char lang_path[MAXPATHLEN];
3143 	char *__script_root;
3144 
3145 	snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
3146 
3147 	scripts_dir = opendir(scripts_path);
3148 	if (!scripts_dir)
3149 		return NULL;
3150 
3151 	for_each_lang(scripts_path, scripts_dir, lang_dirent) {
3152 		scnprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
3153 			  lang_dirent->d_name);
3154 		lang_dir = opendir(lang_path);
3155 		if (!lang_dir)
3156 			continue;
3157 
3158 		for_each_script(lang_path, lang_dir, script_dirent) {
3159 			__script_root = get_script_root(script_dirent, suffix);
3160 			if (__script_root && !strcmp(script_root, __script_root)) {
3161 				free(__script_root);
3162 				closedir(lang_dir);
3163 				closedir(scripts_dir);
3164 				scnprintf(script_path, MAXPATHLEN, "%s/%s",
3165 					  lang_path, script_dirent->d_name);
3166 				return strdup(script_path);
3167 			}
3168 			free(__script_root);
3169 		}
3170 		closedir(lang_dir);
3171 	}
3172 	closedir(scripts_dir);
3173 
3174 	return NULL;
3175 }
3176 
3177 static bool is_top_script(const char *script_path)
3178 {
3179 	return ends_with(script_path, "top") == NULL ? false : true;
3180 }
3181 
3182 static int has_required_arg(char *script_path)
3183 {
3184 	struct script_desc *desc;
3185 	int n_args = 0;
3186 	char *p;
3187 
3188 	desc = script_desc__new(NULL);
3189 
3190 	if (read_script_info(desc, script_path))
3191 		goto out;
3192 
3193 	if (!desc->args)
3194 		goto out;
3195 
3196 	for (p = desc->args; *p; p++)
3197 		if (*p == '<')
3198 			n_args++;
3199 out:
3200 	script_desc__delete(desc);
3201 
3202 	return n_args;
3203 }
3204 
3205 static int have_cmd(int argc, const char **argv)
3206 {
3207 	char **__argv = malloc(sizeof(const char *) * argc);
3208 
3209 	if (!__argv) {
3210 		pr_err("malloc failed\n");
3211 		return -1;
3212 	}
3213 
3214 	memcpy(__argv, argv, sizeof(const char *) * argc);
3215 	argc = parse_options(argc, (const char **)__argv, record_options,
3216 			     NULL, PARSE_OPT_STOP_AT_NON_OPTION);
3217 	free(__argv);
3218 
3219 	system_wide = (argc == 0);
3220 
3221 	return 0;
3222 }
3223 
3224 static void script__setup_sample_type(struct perf_script *script)
3225 {
3226 	struct perf_session *session = script->session;
3227 	u64 sample_type = perf_evlist__combined_sample_type(session->evlist);
3228 
3229 	if (symbol_conf.use_callchain || symbol_conf.cumulate_callchain) {
3230 		if ((sample_type & PERF_SAMPLE_REGS_USER) &&
3231 		    (sample_type & PERF_SAMPLE_STACK_USER)) {
3232 			callchain_param.record_mode = CALLCHAIN_DWARF;
3233 			dwarf_callchain_users = true;
3234 		} else if (sample_type & PERF_SAMPLE_BRANCH_STACK)
3235 			callchain_param.record_mode = CALLCHAIN_LBR;
3236 		else
3237 			callchain_param.record_mode = CALLCHAIN_FP;
3238 	}
3239 }
3240 
3241 static int process_stat_round_event(struct perf_session *session,
3242 				    union perf_event *event)
3243 {
3244 	struct stat_round_event *round = &event->stat_round;
3245 	struct evsel *counter;
3246 
3247 	evlist__for_each_entry(session->evlist, counter) {
3248 		perf_stat_process_counter(&stat_config, counter);
3249 		process_stat(counter, round->time);
3250 	}
3251 
3252 	process_stat_interval(round->time);
3253 	return 0;
3254 }
3255 
3256 static int process_stat_config_event(struct perf_session *session __maybe_unused,
3257 				     union perf_event *event)
3258 {
3259 	perf_event__read_stat_config(&stat_config, &event->stat_config);
3260 	return 0;
3261 }
3262 
3263 static int set_maps(struct perf_script *script)
3264 {
3265 	struct evlist *evlist = script->session->evlist;
3266 
3267 	if (!script->cpus || !script->threads)
3268 		return 0;
3269 
3270 	if (WARN_ONCE(script->allocated, "stats double allocation\n"))
3271 		return -EINVAL;
3272 
3273 	perf_evlist__set_maps(&evlist->core, script->cpus, script->threads);
3274 
3275 	if (perf_evlist__alloc_stats(evlist, true))
3276 		return -ENOMEM;
3277 
3278 	script->allocated = true;
3279 	return 0;
3280 }
3281 
3282 static
3283 int process_thread_map_event(struct perf_session *session,
3284 			     union perf_event *event)
3285 {
3286 	struct perf_tool *tool = session->tool;
3287 	struct perf_script *script = container_of(tool, struct perf_script, tool);
3288 
3289 	if (script->threads) {
3290 		pr_warning("Extra thread map event, ignoring.\n");
3291 		return 0;
3292 	}
3293 
3294 	script->threads = thread_map__new_event(&event->thread_map);
3295 	if (!script->threads)
3296 		return -ENOMEM;
3297 
3298 	return set_maps(script);
3299 }
3300 
3301 static
3302 int process_cpu_map_event(struct perf_session *session,
3303 			  union perf_event *event)
3304 {
3305 	struct perf_tool *tool = session->tool;
3306 	struct perf_script *script = container_of(tool, struct perf_script, tool);
3307 
3308 	if (script->cpus) {
3309 		pr_warning("Extra cpu map event, ignoring.\n");
3310 		return 0;
3311 	}
3312 
3313 	script->cpus = cpu_map__new_data(&event->cpu_map.data);
3314 	if (!script->cpus)
3315 		return -ENOMEM;
3316 
3317 	return set_maps(script);
3318 }
3319 
3320 static int process_feature_event(struct perf_session *session,
3321 				 union perf_event *event)
3322 {
3323 	if (event->feat.feat_id < HEADER_LAST_FEATURE)
3324 		return perf_event__process_feature(session, event);
3325 	return 0;
3326 }
3327 
3328 #ifdef HAVE_AUXTRACE_SUPPORT
3329 static int perf_script__process_auxtrace_info(struct perf_session *session,
3330 					      union perf_event *event)
3331 {
3332 	struct perf_tool *tool = session->tool;
3333 
3334 	int ret = perf_event__process_auxtrace_info(session, event);
3335 
3336 	if (ret == 0) {
3337 		struct perf_script *script = container_of(tool, struct perf_script, tool);
3338 
3339 		ret = perf_script__setup_per_event_dump(script);
3340 	}
3341 
3342 	return ret;
3343 }
3344 #else
3345 #define perf_script__process_auxtrace_info 0
3346 #endif
3347 
3348 static int parse_insn_trace(const struct option *opt __maybe_unused,
3349 			    const char *str __maybe_unused,
3350 			    int unset __maybe_unused)
3351 {
3352 	parse_output_fields(NULL, "+insn,-event,-period", 0);
3353 	itrace_parse_synth_opts(opt, "i0ns", 0);
3354 	symbol_conf.nanosecs = true;
3355 	return 0;
3356 }
3357 
3358 static int parse_xed(const struct option *opt __maybe_unused,
3359 		     const char *str __maybe_unused,
3360 		     int unset __maybe_unused)
3361 {
3362 	force_pager("xed -F insn: -A -64 | less");
3363 	return 0;
3364 }
3365 
3366 static int parse_call_trace(const struct option *opt __maybe_unused,
3367 			    const char *str __maybe_unused,
3368 			    int unset __maybe_unused)
3369 {
3370 	parse_output_fields(NULL, "-ip,-addr,-event,-period,+callindent", 0);
3371 	itrace_parse_synth_opts(opt, "cewp", 0);
3372 	symbol_conf.nanosecs = true;
3373 	symbol_conf.pad_output_len_dso = 50;
3374 	return 0;
3375 }
3376 
3377 static int parse_callret_trace(const struct option *opt __maybe_unused,
3378 			    const char *str __maybe_unused,
3379 			    int unset __maybe_unused)
3380 {
3381 	parse_output_fields(NULL, "-ip,-addr,-event,-period,+callindent,+flags", 0);
3382 	itrace_parse_synth_opts(opt, "crewp", 0);
3383 	symbol_conf.nanosecs = true;
3384 	return 0;
3385 }
3386 
3387 int cmd_script(int argc, const char **argv)
3388 {
3389 	bool show_full_info = false;
3390 	bool header = false;
3391 	bool header_only = false;
3392 	bool script_started = false;
3393 	char *rec_script_path = NULL;
3394 	char *rep_script_path = NULL;
3395 	struct perf_session *session;
3396 	struct itrace_synth_opts itrace_synth_opts = {
3397 		.set = false,
3398 		.default_no_sample = true,
3399 	};
3400 	struct utsname uts;
3401 	char *script_path = NULL;
3402 	const char **__argv;
3403 	int i, j, err = 0;
3404 	struct perf_script script = {
3405 		.tool = {
3406 			.sample		 = process_sample_event,
3407 			.mmap		 = perf_event__process_mmap,
3408 			.mmap2		 = perf_event__process_mmap2,
3409 			.comm		 = perf_event__process_comm,
3410 			.namespaces	 = perf_event__process_namespaces,
3411 			.exit		 = perf_event__process_exit,
3412 			.fork		 = perf_event__process_fork,
3413 			.attr		 = process_attr,
3414 			.event_update   = perf_event__process_event_update,
3415 			.tracing_data	 = perf_event__process_tracing_data,
3416 			.feature	 = process_feature_event,
3417 			.build_id	 = perf_event__process_build_id,
3418 			.id_index	 = perf_event__process_id_index,
3419 			.auxtrace_info	 = perf_script__process_auxtrace_info,
3420 			.auxtrace	 = perf_event__process_auxtrace,
3421 			.auxtrace_error	 = perf_event__process_auxtrace_error,
3422 			.stat		 = perf_event__process_stat_event,
3423 			.stat_round	 = process_stat_round_event,
3424 			.stat_config	 = process_stat_config_event,
3425 			.thread_map	 = process_thread_map_event,
3426 			.cpu_map	 = process_cpu_map_event,
3427 			.ordered_events	 = true,
3428 			.ordering_requires_timestamps = true,
3429 		},
3430 	};
3431 	struct perf_data data = {
3432 		.mode = PERF_DATA_MODE_READ,
3433 	};
3434 	const struct option options[] = {
3435 	OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
3436 		    "dump raw trace in ASCII"),
3437 	OPT_INCR('v', "verbose", &verbose,
3438 		 "be more verbose (show symbol address, etc)"),
3439 	OPT_BOOLEAN('L', "Latency", &latency_format,
3440 		    "show latency attributes (irqs/preemption disabled, etc)"),
3441 	OPT_CALLBACK_NOOPT('l', "list", NULL, NULL, "list available scripts",
3442 			   list_available_scripts),
3443 	OPT_CALLBACK('s', "script", NULL, "name",
3444 		     "script file name (lang:script name, script name, or *)",
3445 		     parse_scriptname),
3446 	OPT_STRING('g', "gen-script", &generate_script_lang, "lang",
3447 		   "generate perf-script.xx script in specified language"),
3448 	OPT_STRING('i', "input", &input_name, "file", "input file name"),
3449 	OPT_BOOLEAN('d', "debug-mode", &debug_mode,
3450 		   "do various checks like samples ordering and lost events"),
3451 	OPT_BOOLEAN(0, "header", &header, "Show data header."),
3452 	OPT_BOOLEAN(0, "header-only", &header_only, "Show only data header."),
3453 	OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
3454 		   "file", "vmlinux pathname"),
3455 	OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
3456 		   "file", "kallsyms pathname"),
3457 	OPT_BOOLEAN('G', "hide-call-graph", &no_callchain,
3458 		    "When printing symbols do not display call chain"),
3459 	OPT_CALLBACK(0, "symfs", NULL, "directory",
3460 		     "Look for files with symbols relative to this directory",
3461 		     symbol__config_symfs),
3462 	OPT_CALLBACK('F', "fields", NULL, "str",
3463 		     "comma separated output fields prepend with 'type:'. "
3464 		     "+field to add and -field to remove."
3465 		     "Valid types: hw,sw,trace,raw,synth. "
3466 		     "Fields: comm,tid,pid,time,cpu,event,trace,ip,sym,dso,"
3467 		     "addr,symoff,srcline,period,iregs,uregs,brstack,"
3468 		     "brstacksym,flags,bpf-output,brstackinsn,brstackoff,"
3469 		     "callindent,insn,insnlen,synth,phys_addr,metric,misc,ipc",
3470 		     parse_output_fields),
3471 	OPT_BOOLEAN('a', "all-cpus", &system_wide,
3472 		    "system-wide collection from all CPUs"),
3473 	OPT_STRING('S', "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
3474 		   "only consider these symbols"),
3475 	OPT_CALLBACK_OPTARG(0, "insn-trace", &itrace_synth_opts, NULL, NULL,
3476 			"Decode instructions from itrace", parse_insn_trace),
3477 	OPT_CALLBACK_OPTARG(0, "xed", NULL, NULL, NULL,
3478 			"Run xed disassembler on output", parse_xed),
3479 	OPT_CALLBACK_OPTARG(0, "call-trace", &itrace_synth_opts, NULL, NULL,
3480 			"Decode calls from from itrace", parse_call_trace),
3481 	OPT_CALLBACK_OPTARG(0, "call-ret-trace", &itrace_synth_opts, NULL, NULL,
3482 			"Decode calls and returns from itrace", parse_callret_trace),
3483 	OPT_STRING(0, "graph-function", &symbol_conf.graph_function, "symbol[,symbol...]",
3484 			"Only print symbols and callees with --call-trace/--call-ret-trace"),
3485 	OPT_STRING(0, "stop-bt", &symbol_conf.bt_stop_list_str, "symbol[,symbol...]",
3486 		   "Stop display of callgraph at these symbols"),
3487 	OPT_STRING('C', "cpu", &cpu_list, "cpu", "list of cpus to profile"),
3488 	OPT_STRING('c', "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
3489 		   "only display events for these comms"),
3490 	OPT_STRING(0, "pid", &symbol_conf.pid_list_str, "pid[,pid...]",
3491 		   "only consider symbols in these pids"),
3492 	OPT_STRING(0, "tid", &symbol_conf.tid_list_str, "tid[,tid...]",
3493 		   "only consider symbols in these tids"),
3494 	OPT_UINTEGER(0, "max-stack", &scripting_max_stack,
3495 		     "Set the maximum stack depth when parsing the callchain, "
3496 		     "anything beyond the specified depth will be ignored. "
3497 		     "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
3498 	OPT_BOOLEAN(0, "reltime", &reltime, "Show time stamps relative to start"),
3499 	OPT_BOOLEAN('I', "show-info", &show_full_info,
3500 		    "display extended information from perf.data file"),
3501 	OPT_BOOLEAN('\0', "show-kernel-path", &symbol_conf.show_kernel_path,
3502 		    "Show the path of [kernel.kallsyms]"),
3503 	OPT_BOOLEAN('\0', "show-task-events", &script.show_task_events,
3504 		    "Show the fork/comm/exit events"),
3505 	OPT_BOOLEAN('\0', "show-mmap-events", &script.show_mmap_events,
3506 		    "Show the mmap events"),
3507 	OPT_BOOLEAN('\0', "show-switch-events", &script.show_switch_events,
3508 		    "Show context switch events (if recorded)"),
3509 	OPT_BOOLEAN('\0', "show-namespace-events", &script.show_namespace_events,
3510 		    "Show namespace events (if recorded)"),
3511 	OPT_BOOLEAN('\0', "show-lost-events", &script.show_lost_events,
3512 		    "Show lost events (if recorded)"),
3513 	OPT_BOOLEAN('\0', "show-round-events", &script.show_round_events,
3514 		    "Show round events (if recorded)"),
3515 	OPT_BOOLEAN('\0', "show-bpf-events", &script.show_bpf_events,
3516 		    "Show bpf related events (if recorded)"),
3517 	OPT_BOOLEAN('\0', "per-event-dump", &script.per_event_dump,
3518 		    "Dump trace output to files named by the monitored events"),
3519 	OPT_BOOLEAN('f', "force", &symbol_conf.force, "don't complain, do it"),
3520 	OPT_INTEGER(0, "max-blocks", &max_blocks,
3521 		    "Maximum number of code blocks to dump with brstackinsn"),
3522 	OPT_BOOLEAN(0, "ns", &symbol_conf.nanosecs,
3523 		    "Use 9 decimal places when displaying time"),
3524 	OPT_CALLBACK_OPTARG(0, "itrace", &itrace_synth_opts, NULL, "opts",
3525 			    "Instruction Tracing options\n" ITRACE_HELP,
3526 			    itrace_parse_synth_opts),
3527 	OPT_BOOLEAN(0, "full-source-path", &srcline_full_filename,
3528 			"Show full source file name path for source lines"),
3529 	OPT_BOOLEAN(0, "demangle", &symbol_conf.demangle,
3530 			"Enable symbol demangling"),
3531 	OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel,
3532 			"Enable kernel symbol demangling"),
3533 	OPT_STRING(0, "time", &script.time_str, "str",
3534 		   "Time span of interest (start,stop)"),
3535 	OPT_BOOLEAN(0, "inline", &symbol_conf.inline_name,
3536 		    "Show inline function"),
3537 	OPT_STRING(0, "guestmount", &symbol_conf.guestmount, "directory",
3538 		   "guest mount directory under which every guest os"
3539 		   " instance has a subdir"),
3540 	OPT_STRING(0, "guestvmlinux", &symbol_conf.default_guest_vmlinux_name,
3541 		   "file", "file saving guest os vmlinux"),
3542 	OPT_STRING(0, "guestkallsyms", &symbol_conf.default_guest_kallsyms,
3543 		   "file", "file saving guest os /proc/kallsyms"),
3544 	OPT_STRING(0, "guestmodules", &symbol_conf.default_guest_modules,
3545 		   "file", "file saving guest os /proc/modules"),
3546 	OPTS_EVSWITCH(&script.evswitch),
3547 	OPT_END()
3548 	};
3549 	const char * const script_subcommands[] = { "record", "report", NULL };
3550 	const char *script_usage[] = {
3551 		"perf script [<options>]",
3552 		"perf script [<options>] record <script> [<record-options>] <command>",
3553 		"perf script [<options>] report <script> [script-args]",
3554 		"perf script [<options>] <script> [<record-options>] <command>",
3555 		"perf script [<options>] <top-script> [script-args]",
3556 		NULL
3557 	};
3558 
3559 	perf_set_singlethreaded();
3560 
3561 	setup_scripting();
3562 
3563 	argc = parse_options_subcommand(argc, argv, options, script_subcommands, script_usage,
3564 			     PARSE_OPT_STOP_AT_NON_OPTION);
3565 
3566 	if (symbol_conf.guestmount ||
3567 	    symbol_conf.default_guest_vmlinux_name ||
3568 	    symbol_conf.default_guest_kallsyms ||
3569 	    symbol_conf.default_guest_modules) {
3570 		/*
3571 		 * Enable guest sample processing.
3572 		 */
3573 		perf_guest = true;
3574 	}
3575 
3576 	data.path  = input_name;
3577 	data.force = symbol_conf.force;
3578 
3579 	if (argc > 1 && !strncmp(argv[0], "rec", strlen("rec"))) {
3580 		rec_script_path = get_script_path(argv[1], RECORD_SUFFIX);
3581 		if (!rec_script_path)
3582 			return cmd_record(argc, argv);
3583 	}
3584 
3585 	if (argc > 1 && !strncmp(argv[0], "rep", strlen("rep"))) {
3586 		rep_script_path = get_script_path(argv[1], REPORT_SUFFIX);
3587 		if (!rep_script_path) {
3588 			fprintf(stderr,
3589 				"Please specify a valid report script"
3590 				"(see 'perf script -l' for listing)\n");
3591 			return -1;
3592 		}
3593 	}
3594 
3595 	if (script.time_str && reltime) {
3596 		fprintf(stderr, "Don't combine --reltime with --time\n");
3597 		return -1;
3598 	}
3599 
3600 	if (itrace_synth_opts.callchain &&
3601 	    itrace_synth_opts.callchain_sz > scripting_max_stack)
3602 		scripting_max_stack = itrace_synth_opts.callchain_sz;
3603 
3604 	/* make sure PERF_EXEC_PATH is set for scripts */
3605 	set_argv_exec_path(get_argv_exec_path());
3606 
3607 	if (argc && !script_name && !rec_script_path && !rep_script_path) {
3608 		int live_pipe[2];
3609 		int rep_args;
3610 		pid_t pid;
3611 
3612 		rec_script_path = get_script_path(argv[0], RECORD_SUFFIX);
3613 		rep_script_path = get_script_path(argv[0], REPORT_SUFFIX);
3614 
3615 		if (!rec_script_path && !rep_script_path) {
3616 			usage_with_options_msg(script_usage, options,
3617 				"Couldn't find script `%s'\n\n See perf"
3618 				" script -l for available scripts.\n", argv[0]);
3619 		}
3620 
3621 		if (is_top_script(argv[0])) {
3622 			rep_args = argc - 1;
3623 		} else {
3624 			int rec_args;
3625 
3626 			rep_args = has_required_arg(rep_script_path);
3627 			rec_args = (argc - 1) - rep_args;
3628 			if (rec_args < 0) {
3629 				usage_with_options_msg(script_usage, options,
3630 					"`%s' script requires options."
3631 					"\n\n See perf script -l for available "
3632 					"scripts and options.\n", argv[0]);
3633 			}
3634 		}
3635 
3636 		if (pipe(live_pipe) < 0) {
3637 			perror("failed to create pipe");
3638 			return -1;
3639 		}
3640 
3641 		pid = fork();
3642 		if (pid < 0) {
3643 			perror("failed to fork");
3644 			return -1;
3645 		}
3646 
3647 		if (!pid) {
3648 			j = 0;
3649 
3650 			dup2(live_pipe[1], 1);
3651 			close(live_pipe[0]);
3652 
3653 			if (is_top_script(argv[0])) {
3654 				system_wide = true;
3655 			} else if (!system_wide) {
3656 				if (have_cmd(argc - rep_args, &argv[rep_args]) != 0) {
3657 					err = -1;
3658 					goto out;
3659 				}
3660 			}
3661 
3662 			__argv = malloc((argc + 6) * sizeof(const char *));
3663 			if (!__argv) {
3664 				pr_err("malloc failed\n");
3665 				err = -ENOMEM;
3666 				goto out;
3667 			}
3668 
3669 			__argv[j++] = "/bin/sh";
3670 			__argv[j++] = rec_script_path;
3671 			if (system_wide)
3672 				__argv[j++] = "-a";
3673 			__argv[j++] = "-q";
3674 			__argv[j++] = "-o";
3675 			__argv[j++] = "-";
3676 			for (i = rep_args + 1; i < argc; i++)
3677 				__argv[j++] = argv[i];
3678 			__argv[j++] = NULL;
3679 
3680 			execvp("/bin/sh", (char **)__argv);
3681 			free(__argv);
3682 			exit(-1);
3683 		}
3684 
3685 		dup2(live_pipe[0], 0);
3686 		close(live_pipe[1]);
3687 
3688 		__argv = malloc((argc + 4) * sizeof(const char *));
3689 		if (!__argv) {
3690 			pr_err("malloc failed\n");
3691 			err = -ENOMEM;
3692 			goto out;
3693 		}
3694 
3695 		j = 0;
3696 		__argv[j++] = "/bin/sh";
3697 		__argv[j++] = rep_script_path;
3698 		for (i = 1; i < rep_args + 1; i++)
3699 			__argv[j++] = argv[i];
3700 		__argv[j++] = "-i";
3701 		__argv[j++] = "-";
3702 		__argv[j++] = NULL;
3703 
3704 		execvp("/bin/sh", (char **)__argv);
3705 		free(__argv);
3706 		exit(-1);
3707 	}
3708 
3709 	if (rec_script_path)
3710 		script_path = rec_script_path;
3711 	if (rep_script_path)
3712 		script_path = rep_script_path;
3713 
3714 	if (script_path) {
3715 		j = 0;
3716 
3717 		if (!rec_script_path)
3718 			system_wide = false;
3719 		else if (!system_wide) {
3720 			if (have_cmd(argc - 1, &argv[1]) != 0) {
3721 				err = -1;
3722 				goto out;
3723 			}
3724 		}
3725 
3726 		__argv = malloc((argc + 2) * sizeof(const char *));
3727 		if (!__argv) {
3728 			pr_err("malloc failed\n");
3729 			err = -ENOMEM;
3730 			goto out;
3731 		}
3732 
3733 		__argv[j++] = "/bin/sh";
3734 		__argv[j++] = script_path;
3735 		if (system_wide)
3736 			__argv[j++] = "-a";
3737 		for (i = 2; i < argc; i++)
3738 			__argv[j++] = argv[i];
3739 		__argv[j++] = NULL;
3740 
3741 		execvp("/bin/sh", (char **)__argv);
3742 		free(__argv);
3743 		exit(-1);
3744 	}
3745 
3746 	if (!script_name) {
3747 		setup_pager();
3748 		use_browser = 0;
3749 	}
3750 
3751 	session = perf_session__new(&data, false, &script.tool);
3752 	if (session == NULL)
3753 		return -1;
3754 
3755 	if (header || header_only) {
3756 		script.tool.show_feat_hdr = SHOW_FEAT_HEADER;
3757 		perf_session__fprintf_info(session, stdout, show_full_info);
3758 		if (header_only)
3759 			goto out_delete;
3760 	}
3761 	if (show_full_info)
3762 		script.tool.show_feat_hdr = SHOW_FEAT_HEADER_FULL_INFO;
3763 
3764 	if (symbol__init(&session->header.env) < 0)
3765 		goto out_delete;
3766 
3767 	uname(&uts);
3768 	if (data.is_pipe ||  /* assume pipe_mode indicates native_arch */
3769 	    !strcmp(uts.machine, session->header.env.arch) ||
3770 	    (!strcmp(uts.machine, "x86_64") &&
3771 	     !strcmp(session->header.env.arch, "i386")))
3772 		native_arch = true;
3773 
3774 	script.session = session;
3775 	script__setup_sample_type(&script);
3776 
3777 	if ((output[PERF_TYPE_HARDWARE].fields & PERF_OUTPUT_CALLINDENT) ||
3778 	    symbol_conf.graph_function)
3779 		itrace_synth_opts.thread_stack = true;
3780 
3781 	session->itrace_synth_opts = &itrace_synth_opts;
3782 
3783 	if (cpu_list) {
3784 		err = perf_session__cpu_bitmap(session, cpu_list, cpu_bitmap);
3785 		if (err < 0)
3786 			goto out_delete;
3787 		itrace_synth_opts.cpu_bitmap = cpu_bitmap;
3788 	}
3789 
3790 	if (!no_callchain)
3791 		symbol_conf.use_callchain = true;
3792 	else
3793 		symbol_conf.use_callchain = false;
3794 
3795 	if (session->tevent.pevent &&
3796 	    tep_set_function_resolver(session->tevent.pevent,
3797 				      machine__resolve_kernel_addr,
3798 				      &session->machines.host) < 0) {
3799 		pr_err("%s: failed to set libtraceevent function resolver\n", __func__);
3800 		err = -1;
3801 		goto out_delete;
3802 	}
3803 
3804 	if (generate_script_lang) {
3805 		struct stat perf_stat;
3806 		int input;
3807 
3808 		if (output_set_by_user()) {
3809 			fprintf(stderr,
3810 				"custom fields not supported for generated scripts");
3811 			err = -EINVAL;
3812 			goto out_delete;
3813 		}
3814 
3815 		input = open(data.path, O_RDONLY);	/* input_name */
3816 		if (input < 0) {
3817 			err = -errno;
3818 			perror("failed to open file");
3819 			goto out_delete;
3820 		}
3821 
3822 		err = fstat(input, &perf_stat);
3823 		if (err < 0) {
3824 			perror("failed to stat file");
3825 			goto out_delete;
3826 		}
3827 
3828 		if (!perf_stat.st_size) {
3829 			fprintf(stderr, "zero-sized file, nothing to do!\n");
3830 			goto out_delete;
3831 		}
3832 
3833 		scripting_ops = script_spec__lookup(generate_script_lang);
3834 		if (!scripting_ops) {
3835 			fprintf(stderr, "invalid language specifier");
3836 			err = -ENOENT;
3837 			goto out_delete;
3838 		}
3839 
3840 		err = scripting_ops->generate_script(session->tevent.pevent,
3841 						     "perf-script");
3842 		goto out_delete;
3843 	}
3844 
3845 	if (script_name) {
3846 		err = scripting_ops->start_script(script_name, argc, argv);
3847 		if (err)
3848 			goto out_delete;
3849 		pr_debug("perf script started with script %s\n\n", script_name);
3850 		script_started = true;
3851 	}
3852 
3853 
3854 	err = perf_session__check_output_opt(session);
3855 	if (err < 0)
3856 		goto out_delete;
3857 
3858 	if (script.time_str) {
3859 		err = perf_time__parse_for_ranges(script.time_str, session,
3860 						  &script.ptime_range,
3861 						  &script.range_size,
3862 						  &script.range_num);
3863 		if (err < 0)
3864 			goto out_delete;
3865 
3866 		itrace_synth_opts__set_time_range(&itrace_synth_opts,
3867 						  script.ptime_range,
3868 						  script.range_num);
3869 	}
3870 
3871 	err = evswitch__init(&script.evswitch, session->evlist, stderr);
3872 	if (err)
3873 		goto out_delete;
3874 
3875 	err = __cmd_script(&script);
3876 
3877 	flush_scripting();
3878 
3879 out_delete:
3880 	if (script.ptime_range) {
3881 		itrace_synth_opts__clear_time_range(&itrace_synth_opts);
3882 		zfree(&script.ptime_range);
3883 	}
3884 
3885 	perf_evlist__free_stats(session->evlist);
3886 	perf_session__delete(session);
3887 
3888 	if (script_started)
3889 		cleanup_scripting();
3890 out:
3891 	return err;
3892 }
3893