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