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