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