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