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