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