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