• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 #include "builtin.h"
3 
4 #include "perf.h"
5 #include "util/cache.h"
6 #include "util/debug.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/symbol.h"
14 #include "util/thread.h"
15 #include "util/trace-event.h"
16 #include "util/util.h"
17 #include "util/evlist.h"
18 #include "util/evsel.h"
19 #include "util/sort.h"
20 #include "util/data.h"
21 #include "util/auxtrace.h"
22 #include "util/cpumap.h"
23 #include "util/thread_map.h"
24 #include "util/stat.h"
25 #include "util/string2.h"
26 #include "util/thread-stack.h"
27 #include "util/time-utils.h"
28 #include "util/path.h"
29 #include "print_binary.h"
30 #include <linux/bitmap.h>
31 #include <linux/kernel.h>
32 #include <linux/stringify.h>
33 #include <linux/time64.h>
34 #include "asm/bug.h"
35 #include "util/mem-events.h"
36 #include "util/dump-insn.h"
37 #include <dirent.h>
38 #include <errno.h>
39 #include <inttypes.h>
40 #include <signal.h>
41 #include <sys/param.h>
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <unistd.h>
45 
46 #include "sane_ctype.h"
47 
48 static char const		*script_name;
49 static char const		*generate_script_lang;
50 static bool			debug_mode;
51 static u64			last_timestamp;
52 static u64			nr_unordered;
53 static bool			no_callchain;
54 static bool			latency_format;
55 static bool			system_wide;
56 static bool			print_flags;
57 static bool			nanosecs;
58 static const char		*cpu_list;
59 static DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
60 static struct perf_stat_config	stat_config;
61 static int			max_blocks;
62 
63 unsigned int scripting_max_stack = PERF_MAX_STACK_DEPTH;
64 
65 enum perf_output_field {
66 	PERF_OUTPUT_COMM            = 1U << 0,
67 	PERF_OUTPUT_TID             = 1U << 1,
68 	PERF_OUTPUT_PID             = 1U << 2,
69 	PERF_OUTPUT_TIME            = 1U << 3,
70 	PERF_OUTPUT_CPU             = 1U << 4,
71 	PERF_OUTPUT_EVNAME          = 1U << 5,
72 	PERF_OUTPUT_TRACE           = 1U << 6,
73 	PERF_OUTPUT_IP              = 1U << 7,
74 	PERF_OUTPUT_SYM             = 1U << 8,
75 	PERF_OUTPUT_DSO             = 1U << 9,
76 	PERF_OUTPUT_ADDR            = 1U << 10,
77 	PERF_OUTPUT_SYMOFFSET       = 1U << 11,
78 	PERF_OUTPUT_SRCLINE         = 1U << 12,
79 	PERF_OUTPUT_PERIOD          = 1U << 13,
80 	PERF_OUTPUT_IREGS	    = 1U << 14,
81 	PERF_OUTPUT_BRSTACK	    = 1U << 15,
82 	PERF_OUTPUT_BRSTACKSYM	    = 1U << 16,
83 	PERF_OUTPUT_DATA_SRC	    = 1U << 17,
84 	PERF_OUTPUT_WEIGHT	    = 1U << 18,
85 	PERF_OUTPUT_BPF_OUTPUT	    = 1U << 19,
86 	PERF_OUTPUT_CALLINDENT	    = 1U << 20,
87 	PERF_OUTPUT_INSN	    = 1U << 21,
88 	PERF_OUTPUT_INSNLEN	    = 1U << 22,
89 	PERF_OUTPUT_BRSTACKINSN	    = 1U << 23,
90 	PERF_OUTPUT_BRSTACKOFF	    = 1U << 24,
91 	PERF_OUTPUT_SYNTH           = 1U << 25,
92 	PERF_OUTPUT_PHYS_ADDR       = 1U << 26,
93 };
94 
95 struct output_option {
96 	const char *str;
97 	enum perf_output_field field;
98 } all_output_options[] = {
99 	{.str = "comm",  .field = PERF_OUTPUT_COMM},
100 	{.str = "tid",   .field = PERF_OUTPUT_TID},
101 	{.str = "pid",   .field = PERF_OUTPUT_PID},
102 	{.str = "time",  .field = PERF_OUTPUT_TIME},
103 	{.str = "cpu",   .field = PERF_OUTPUT_CPU},
104 	{.str = "event", .field = PERF_OUTPUT_EVNAME},
105 	{.str = "trace", .field = PERF_OUTPUT_TRACE},
106 	{.str = "ip",    .field = PERF_OUTPUT_IP},
107 	{.str = "sym",   .field = PERF_OUTPUT_SYM},
108 	{.str = "dso",   .field = PERF_OUTPUT_DSO},
109 	{.str = "addr",  .field = PERF_OUTPUT_ADDR},
110 	{.str = "symoff", .field = PERF_OUTPUT_SYMOFFSET},
111 	{.str = "srcline", .field = PERF_OUTPUT_SRCLINE},
112 	{.str = "period", .field = PERF_OUTPUT_PERIOD},
113 	{.str = "iregs", .field = PERF_OUTPUT_IREGS},
114 	{.str = "brstack", .field = PERF_OUTPUT_BRSTACK},
115 	{.str = "brstacksym", .field = PERF_OUTPUT_BRSTACKSYM},
116 	{.str = "data_src", .field = PERF_OUTPUT_DATA_SRC},
117 	{.str = "weight",   .field = PERF_OUTPUT_WEIGHT},
118 	{.str = "bpf-output",   .field = PERF_OUTPUT_BPF_OUTPUT},
119 	{.str = "callindent", .field = PERF_OUTPUT_CALLINDENT},
120 	{.str = "insn", .field = PERF_OUTPUT_INSN},
121 	{.str = "insnlen", .field = PERF_OUTPUT_INSNLEN},
122 	{.str = "brstackinsn", .field = PERF_OUTPUT_BRSTACKINSN},
123 	{.str = "brstackoff", .field = PERF_OUTPUT_BRSTACKOFF},
124 	{.str = "synth", .field = PERF_OUTPUT_SYNTH},
125 	{.str = "phys_addr", .field = PERF_OUTPUT_PHYS_ADDR},
126 };
127 
128 enum {
129 	OUTPUT_TYPE_SYNTH = PERF_TYPE_MAX,
130 	OUTPUT_TYPE_MAX
131 };
132 
133 /* default set to maintain compatibility with current format */
134 static struct {
135 	bool user_set;
136 	bool wildcard_set;
137 	unsigned int print_ip_opts;
138 	u64 fields;
139 	u64 invalid_fields;
140 } output[OUTPUT_TYPE_MAX] = {
141 
142 	[PERF_TYPE_HARDWARE] = {
143 		.user_set = false,
144 
145 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
146 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
147 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
148 			      PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
149 			      PERF_OUTPUT_PERIOD,
150 
151 		.invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
152 	},
153 
154 	[PERF_TYPE_SOFTWARE] = {
155 		.user_set = false,
156 
157 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
158 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
159 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
160 			      PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
161 			      PERF_OUTPUT_PERIOD | PERF_OUTPUT_BPF_OUTPUT,
162 
163 		.invalid_fields = PERF_OUTPUT_TRACE,
164 	},
165 
166 	[PERF_TYPE_TRACEPOINT] = {
167 		.user_set = false,
168 
169 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
170 				  PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
171 				  PERF_OUTPUT_EVNAME | PERF_OUTPUT_TRACE
172 	},
173 
174 	[PERF_TYPE_RAW] = {
175 		.user_set = false,
176 
177 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
178 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
179 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
180 			      PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
181 			      PERF_OUTPUT_PERIOD |  PERF_OUTPUT_ADDR |
182 			      PERF_OUTPUT_DATA_SRC | PERF_OUTPUT_WEIGHT |
183 			      PERF_OUTPUT_PHYS_ADDR,
184 
185 		.invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
186 	},
187 
188 	[PERF_TYPE_BREAKPOINT] = {
189 		.user_set = false,
190 
191 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
192 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
193 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
194 			      PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
195 			      PERF_OUTPUT_PERIOD,
196 
197 		.invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
198 	},
199 
200 	[OUTPUT_TYPE_SYNTH] = {
201 		.user_set = false,
202 
203 		.fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
204 			      PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
205 			      PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
206 			      PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
207 			      PERF_OUTPUT_SYNTH,
208 
209 		.invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
210 	},
211 };
212 
output_type(unsigned int type)213 static inline int output_type(unsigned int type)
214 {
215 	switch (type) {
216 	case PERF_TYPE_SYNTH:
217 		return OUTPUT_TYPE_SYNTH;
218 	default:
219 		return type;
220 	}
221 }
222 
attr_type(unsigned int type)223 static inline unsigned int attr_type(unsigned int type)
224 {
225 	switch (type) {
226 	case OUTPUT_TYPE_SYNTH:
227 		return PERF_TYPE_SYNTH;
228 	default:
229 		return type;
230 	}
231 }
232 
output_set_by_user(void)233 static bool output_set_by_user(void)
234 {
235 	int j;
236 	for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
237 		if (output[j].user_set)
238 			return true;
239 	}
240 	return false;
241 }
242 
output_field2str(enum perf_output_field field)243 static const char *output_field2str(enum perf_output_field field)
244 {
245 	int i, imax = ARRAY_SIZE(all_output_options);
246 	const char *str = "";
247 
248 	for (i = 0; i < imax; ++i) {
249 		if (all_output_options[i].field == field) {
250 			str = all_output_options[i].str;
251 			break;
252 		}
253 	}
254 	return str;
255 }
256 
257 #define PRINT_FIELD(x)  (output[output_type(attr->type)].fields & PERF_OUTPUT_##x)
258 
perf_evsel__do_check_stype(struct perf_evsel * evsel,u64 sample_type,const char * sample_msg,enum perf_output_field field,bool allow_user_set)259 static int perf_evsel__do_check_stype(struct perf_evsel *evsel,
260 				      u64 sample_type, const char *sample_msg,
261 				      enum perf_output_field field,
262 				      bool allow_user_set)
263 {
264 	struct perf_event_attr *attr = &evsel->attr;
265 	int type = output_type(attr->type);
266 	const char *evname;
267 
268 	if (attr->sample_type & sample_type)
269 		return 0;
270 
271 	if (output[type].user_set) {
272 		if (allow_user_set)
273 			return 0;
274 		evname = perf_evsel__name(evsel);
275 		pr_err("Samples for '%s' event do not have %s attribute set. "
276 		       "Cannot print '%s' field.\n",
277 		       evname, sample_msg, output_field2str(field));
278 		return -1;
279 	}
280 
281 	/* user did not ask for it explicitly so remove from the default list */
282 	output[type].fields &= ~field;
283 	evname = perf_evsel__name(evsel);
284 	pr_debug("Samples for '%s' event do not have %s attribute set. "
285 		 "Skipping '%s' field.\n",
286 		 evname, sample_msg, output_field2str(field));
287 
288 	return 0;
289 }
290 
perf_evsel__check_stype(struct perf_evsel * evsel,u64 sample_type,const char * sample_msg,enum perf_output_field field)291 static int perf_evsel__check_stype(struct perf_evsel *evsel,
292 				   u64 sample_type, const char *sample_msg,
293 				   enum perf_output_field field)
294 {
295 	return perf_evsel__do_check_stype(evsel, sample_type, sample_msg, field,
296 					  false);
297 }
298 
perf_evsel__check_attr(struct perf_evsel * evsel,struct perf_session * session)299 static int perf_evsel__check_attr(struct perf_evsel *evsel,
300 				  struct perf_session *session)
301 {
302 	struct perf_event_attr *attr = &evsel->attr;
303 	bool allow_user_set;
304 
305 	if (perf_header__has_feat(&session->header, HEADER_STAT))
306 		return 0;
307 
308 	allow_user_set = perf_header__has_feat(&session->header,
309 					       HEADER_AUXTRACE);
310 
311 	if (PRINT_FIELD(TRACE) &&
312 		!perf_session__has_traces(session, "record -R"))
313 		return -EINVAL;
314 
315 	if (PRINT_FIELD(IP)) {
316 		if (perf_evsel__check_stype(evsel, PERF_SAMPLE_IP, "IP",
317 					    PERF_OUTPUT_IP))
318 			return -EINVAL;
319 	}
320 
321 	if (PRINT_FIELD(ADDR) &&
322 		perf_evsel__do_check_stype(evsel, PERF_SAMPLE_ADDR, "ADDR",
323 					   PERF_OUTPUT_ADDR, allow_user_set))
324 		return -EINVAL;
325 
326 	if (PRINT_FIELD(DATA_SRC) &&
327 		perf_evsel__check_stype(evsel, PERF_SAMPLE_DATA_SRC, "DATA_SRC",
328 					PERF_OUTPUT_DATA_SRC))
329 		return -EINVAL;
330 
331 	if (PRINT_FIELD(WEIGHT) &&
332 		perf_evsel__check_stype(evsel, PERF_SAMPLE_WEIGHT, "WEIGHT",
333 					PERF_OUTPUT_WEIGHT))
334 		return -EINVAL;
335 
336 	if (PRINT_FIELD(SYM) && !PRINT_FIELD(IP) && !PRINT_FIELD(ADDR)) {
337 		pr_err("Display of symbols requested but neither sample IP nor "
338 			   "sample address\nis selected. Hence, no addresses to convert "
339 		       "to symbols.\n");
340 		return -EINVAL;
341 	}
342 	if (PRINT_FIELD(SYMOFFSET) && !PRINT_FIELD(SYM)) {
343 		pr_err("Display of offsets requested but symbol is not"
344 		       "selected.\n");
345 		return -EINVAL;
346 	}
347 	if (PRINT_FIELD(DSO) && !PRINT_FIELD(IP) && !PRINT_FIELD(ADDR) &&
348 	    !PRINT_FIELD(BRSTACK) && !PRINT_FIELD(BRSTACKSYM) && !PRINT_FIELD(BRSTACKOFF)) {
349 		pr_err("Display of DSO requested but no address to convert.  Select\n"
350 		       "sample IP, sample address, brstack, brstacksym, or brstackoff.\n");
351 		return -EINVAL;
352 	}
353 	if (PRINT_FIELD(SRCLINE) && !PRINT_FIELD(IP)) {
354 		pr_err("Display of source line number requested but sample IP is not\n"
355 		       "selected. Hence, no address to lookup the source line number.\n");
356 		return -EINVAL;
357 	}
358 	if (PRINT_FIELD(BRSTACKINSN) && !allow_user_set &&
359 	    !(perf_evlist__combined_branch_type(session->evlist) &
360 	      PERF_SAMPLE_BRANCH_ANY)) {
361 		pr_err("Display of branch stack assembler requested, but non all-branch filter set\n"
362 		       "Hint: run 'perf record -b ...'\n");
363 		return -EINVAL;
364 	}
365 	if ((PRINT_FIELD(PID) || PRINT_FIELD(TID)) &&
366 		perf_evsel__check_stype(evsel, PERF_SAMPLE_TID, "TID",
367 					PERF_OUTPUT_TID|PERF_OUTPUT_PID))
368 		return -EINVAL;
369 
370 	if (PRINT_FIELD(TIME) &&
371 		perf_evsel__check_stype(evsel, PERF_SAMPLE_TIME, "TIME",
372 					PERF_OUTPUT_TIME))
373 		return -EINVAL;
374 
375 	if (PRINT_FIELD(CPU) &&
376 		perf_evsel__do_check_stype(evsel, PERF_SAMPLE_CPU, "CPU",
377 					   PERF_OUTPUT_CPU, allow_user_set))
378 		return -EINVAL;
379 
380 	if (PRINT_FIELD(PERIOD) &&
381 		perf_evsel__check_stype(evsel, PERF_SAMPLE_PERIOD, "PERIOD",
382 					PERF_OUTPUT_PERIOD))
383 		return -EINVAL;
384 
385 	if (PRINT_FIELD(IREGS) &&
386 		perf_evsel__check_stype(evsel, PERF_SAMPLE_REGS_INTR, "IREGS",
387 					PERF_OUTPUT_IREGS))
388 		return -EINVAL;
389 
390 	if (PRINT_FIELD(PHYS_ADDR) &&
391 		perf_evsel__check_stype(evsel, PERF_SAMPLE_PHYS_ADDR, "PHYS_ADDR",
392 					PERF_OUTPUT_PHYS_ADDR))
393 		return -EINVAL;
394 
395 	return 0;
396 }
397 
set_print_ip_opts(struct perf_event_attr * attr)398 static void set_print_ip_opts(struct perf_event_attr *attr)
399 {
400 	unsigned int type = output_type(attr->type);
401 
402 	output[type].print_ip_opts = 0;
403 	if (PRINT_FIELD(IP))
404 		output[type].print_ip_opts |= EVSEL__PRINT_IP;
405 
406 	if (PRINT_FIELD(SYM))
407 		output[type].print_ip_opts |= EVSEL__PRINT_SYM;
408 
409 	if (PRINT_FIELD(DSO))
410 		output[type].print_ip_opts |= EVSEL__PRINT_DSO;
411 
412 	if (PRINT_FIELD(SYMOFFSET))
413 		output[type].print_ip_opts |= EVSEL__PRINT_SYMOFFSET;
414 
415 	if (PRINT_FIELD(SRCLINE))
416 		output[type].print_ip_opts |= EVSEL__PRINT_SRCLINE;
417 }
418 
419 /*
420  * verify all user requested events exist and the samples
421  * have the expected data
422  */
perf_session__check_output_opt(struct perf_session * session)423 static int perf_session__check_output_opt(struct perf_session *session)
424 {
425 	unsigned int j;
426 	struct perf_evsel *evsel;
427 
428 	for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
429 		evsel = perf_session__find_first_evtype(session, attr_type(j));
430 
431 		/*
432 		 * even if fields is set to 0 (ie., show nothing) event must
433 		 * exist if user explicitly includes it on the command line
434 		 */
435 		if (!evsel && output[j].user_set && !output[j].wildcard_set &&
436 		    j != OUTPUT_TYPE_SYNTH) {
437 			pr_err("%s events do not exist. "
438 			       "Remove corresponding -F option to proceed.\n",
439 			       event_type(j));
440 			return -1;
441 		}
442 
443 		if (evsel && output[j].fields &&
444 			perf_evsel__check_attr(evsel, session))
445 			return -1;
446 
447 		if (evsel == NULL)
448 			continue;
449 
450 		set_print_ip_opts(&evsel->attr);
451 	}
452 
453 	if (!no_callchain) {
454 		bool use_callchain = false;
455 		bool not_pipe = false;
456 
457 		evlist__for_each_entry(session->evlist, evsel) {
458 			not_pipe = true;
459 			if (evsel->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
460 				use_callchain = true;
461 				break;
462 			}
463 		}
464 		if (not_pipe && !use_callchain)
465 			symbol_conf.use_callchain = false;
466 	}
467 
468 	/*
469 	 * set default for tracepoints to print symbols only
470 	 * if callchains are present
471 	 */
472 	if (symbol_conf.use_callchain &&
473 	    !output[PERF_TYPE_TRACEPOINT].user_set) {
474 		struct perf_event_attr *attr;
475 
476 		j = PERF_TYPE_TRACEPOINT;
477 
478 		evlist__for_each_entry(session->evlist, evsel) {
479 			if (evsel->attr.type != j)
480 				continue;
481 
482 			attr = &evsel->attr;
483 
484 			if (attr->sample_type & PERF_SAMPLE_CALLCHAIN) {
485 				output[j].fields |= PERF_OUTPUT_IP;
486 				output[j].fields |= PERF_OUTPUT_SYM;
487 				output[j].fields |= PERF_OUTPUT_DSO;
488 				set_print_ip_opts(attr);
489 				goto out;
490 			}
491 		}
492 	}
493 
494 out:
495 	return 0;
496 }
497 
print_sample_iregs(struct perf_sample * sample,struct perf_event_attr * attr)498 static void print_sample_iregs(struct perf_sample *sample,
499 			  struct perf_event_attr *attr)
500 {
501 	struct regs_dump *regs = &sample->intr_regs;
502 	uint64_t mask = attr->sample_regs_intr;
503 	unsigned i = 0, r;
504 
505 	if (!regs)
506 		return;
507 
508 	for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
509 		u64 val = regs->regs[i++];
510 		printf("%5s:0x%"PRIx64" ", perf_reg_name(r), val);
511 	}
512 }
513 
print_sample_start(struct perf_sample * sample,struct thread * thread,struct perf_evsel * evsel)514 static void print_sample_start(struct perf_sample *sample,
515 			       struct thread *thread,
516 			       struct perf_evsel *evsel)
517 {
518 	struct perf_event_attr *attr = &evsel->attr;
519 	unsigned long secs;
520 	unsigned long long nsecs;
521 
522 	if (PRINT_FIELD(COMM)) {
523 		if (latency_format)
524 			printf("%8.8s ", thread__comm_str(thread));
525 		else if (PRINT_FIELD(IP) && symbol_conf.use_callchain)
526 			printf("%s ", thread__comm_str(thread));
527 		else
528 			printf("%16s ", thread__comm_str(thread));
529 	}
530 
531 	if (PRINT_FIELD(PID) && PRINT_FIELD(TID))
532 		printf("%5d/%-5d ", sample->pid, sample->tid);
533 	else if (PRINT_FIELD(PID))
534 		printf("%5d ", sample->pid);
535 	else if (PRINT_FIELD(TID))
536 		printf("%5d ", sample->tid);
537 
538 	if (PRINT_FIELD(CPU)) {
539 		if (latency_format)
540 			printf("%3d ", sample->cpu);
541 		else
542 			printf("[%03d] ", sample->cpu);
543 	}
544 
545 	if (PRINT_FIELD(TIME)) {
546 		nsecs = sample->time;
547 		secs = nsecs / NSEC_PER_SEC;
548 		nsecs -= secs * NSEC_PER_SEC;
549 
550 		if (nanosecs)
551 			printf("%5lu.%09llu: ", secs, nsecs);
552 		else {
553 			char sample_time[32];
554 			timestamp__scnprintf_usec(sample->time, sample_time, sizeof(sample_time));
555 			printf("%12s: ", sample_time);
556 		}
557 	}
558 }
559 
560 static inline char
mispred_str(struct branch_entry * br)561 mispred_str(struct branch_entry *br)
562 {
563 	if (!(br->flags.mispred  || br->flags.predicted))
564 		return '-';
565 
566 	return br->flags.predicted ? 'P' : 'M';
567 }
568 
print_sample_brstack(struct perf_sample * sample,struct thread * thread,struct perf_event_attr * attr)569 static void print_sample_brstack(struct perf_sample *sample,
570 				 struct thread *thread,
571 				 struct perf_event_attr *attr)
572 {
573 	struct branch_stack *br = sample->branch_stack;
574 	struct addr_location alf, alt;
575 	u64 i, from, to;
576 
577 	if (!(br && br->nr))
578 		return;
579 
580 	for (i = 0; i < br->nr; i++) {
581 		from = br->entries[i].from;
582 		to   = br->entries[i].to;
583 
584 		if (PRINT_FIELD(DSO)) {
585 			memset(&alf, 0, sizeof(alf));
586 			memset(&alt, 0, sizeof(alt));
587 			thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, from, &alf);
588 			thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, to, &alt);
589 		}
590 
591 		printf(" 0x%"PRIx64, from);
592 		if (PRINT_FIELD(DSO)) {
593 			printf("(");
594 			map__fprintf_dsoname(alf.map, stdout);
595 			printf(")");
596 		}
597 
598 		printf("/0x%"PRIx64, to);
599 		if (PRINT_FIELD(DSO)) {
600 			printf("(");
601 			map__fprintf_dsoname(alt.map, stdout);
602 			printf(")");
603 		}
604 
605 		printf("/%c/%c/%c/%d ",
606 			mispred_str( br->entries + i),
607 			br->entries[i].flags.in_tx? 'X' : '-',
608 			br->entries[i].flags.abort? 'A' : '-',
609 			br->entries[i].flags.cycles);
610 	}
611 }
612 
print_sample_brstacksym(struct perf_sample * sample,struct thread * thread,struct perf_event_attr * attr)613 static void print_sample_brstacksym(struct perf_sample *sample,
614 				    struct thread *thread,
615 				    struct perf_event_attr *attr)
616 {
617 	struct branch_stack *br = sample->branch_stack;
618 	struct addr_location alf, alt;
619 	u64 i, from, to;
620 
621 	if (!(br && br->nr))
622 		return;
623 
624 	for (i = 0; i < br->nr; i++) {
625 
626 		memset(&alf, 0, sizeof(alf));
627 		memset(&alt, 0, sizeof(alt));
628 		from = br->entries[i].from;
629 		to   = br->entries[i].to;
630 
631 		thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, from, &alf);
632 		if (alf.map)
633 			alf.sym = map__find_symbol(alf.map, alf.addr);
634 
635 		thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, to, &alt);
636 		if (alt.map)
637 			alt.sym = map__find_symbol(alt.map, alt.addr);
638 
639 		symbol__fprintf_symname_offs(alf.sym, &alf, stdout);
640 		if (PRINT_FIELD(DSO)) {
641 			printf("(");
642 			map__fprintf_dsoname(alf.map, stdout);
643 			printf(")");
644 		}
645 		putchar('/');
646 		symbol__fprintf_symname_offs(alt.sym, &alt, stdout);
647 		if (PRINT_FIELD(DSO)) {
648 			printf("(");
649 			map__fprintf_dsoname(alt.map, stdout);
650 			printf(")");
651 		}
652 		printf("/%c/%c/%c/%d ",
653 			mispred_str( br->entries + i),
654 			br->entries[i].flags.in_tx? 'X' : '-',
655 			br->entries[i].flags.abort? 'A' : '-',
656 			br->entries[i].flags.cycles);
657 	}
658 }
659 
print_sample_brstackoff(struct perf_sample * sample,struct thread * thread,struct perf_event_attr * attr)660 static void print_sample_brstackoff(struct perf_sample *sample,
661 				    struct thread *thread,
662 				    struct perf_event_attr *attr)
663 {
664 	struct branch_stack *br = sample->branch_stack;
665 	struct addr_location alf, alt;
666 	u64 i, from, to;
667 
668 	if (!(br && br->nr))
669 		return;
670 
671 	for (i = 0; i < br->nr; i++) {
672 
673 		memset(&alf, 0, sizeof(alf));
674 		memset(&alt, 0, sizeof(alt));
675 		from = br->entries[i].from;
676 		to   = br->entries[i].to;
677 
678 		thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, from, &alf);
679 		if (alf.map && !alf.map->dso->adjust_symbols)
680 			from = map__map_ip(alf.map, from);
681 
682 		thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, to, &alt);
683 		if (alt.map && !alt.map->dso->adjust_symbols)
684 			to = map__map_ip(alt.map, to);
685 
686 		printf(" 0x%"PRIx64, from);
687 		if (PRINT_FIELD(DSO)) {
688 			printf("(");
689 			map__fprintf_dsoname(alf.map, stdout);
690 			printf(")");
691 		}
692 		printf("/0x%"PRIx64, to);
693 		if (PRINT_FIELD(DSO)) {
694 			printf("(");
695 			map__fprintf_dsoname(alt.map, stdout);
696 			printf(")");
697 		}
698 		printf("/%c/%c/%c/%d ",
699 			mispred_str(br->entries + i),
700 			br->entries[i].flags.in_tx ? 'X' : '-',
701 			br->entries[i].flags.abort ? 'A' : '-',
702 			br->entries[i].flags.cycles);
703 	}
704 }
705 #define MAXBB 16384UL
706 
grab_bb(u8 * buffer,u64 start,u64 end,struct machine * machine,struct thread * thread,bool * is64bit,u8 * cpumode,bool last)707 static int grab_bb(u8 *buffer, u64 start, u64 end,
708 		    struct machine *machine, struct thread *thread,
709 		    bool *is64bit, u8 *cpumode, bool last)
710 {
711 	long offset, len;
712 	struct addr_location al;
713 	bool kernel;
714 
715 	if (!start || !end)
716 		return 0;
717 
718 	kernel = machine__kernel_ip(machine, start);
719 	if (kernel)
720 		*cpumode = PERF_RECORD_MISC_KERNEL;
721 	else
722 		*cpumode = PERF_RECORD_MISC_USER;
723 
724 	/*
725 	 * Block overlaps between kernel and user.
726 	 * This can happen due to ring filtering
727 	 * On Intel CPUs the entry into the kernel is filtered,
728 	 * but the exit is not. Let the caller patch it up.
729 	 */
730 	if (kernel != machine__kernel_ip(machine, end)) {
731 		printf("\tblock %" PRIx64 "-%" PRIx64 " transfers between kernel and user\n",
732 				start, end);
733 		return -ENXIO;
734 	}
735 
736 	memset(&al, 0, sizeof(al));
737 	if (end - start > MAXBB - MAXINSN) {
738 		if (last)
739 			printf("\tbrstack does not reach to final jump (%" PRIx64 "-%" PRIx64 ")\n", start, end);
740 		else
741 			printf("\tblock %" PRIx64 "-%" PRIx64 " (%" PRIu64 ") too long to dump\n", start, end, end - start);
742 		return 0;
743 	}
744 
745 	thread__find_addr_map(thread, *cpumode, MAP__FUNCTION, start, &al);
746 	if (!al.map || !al.map->dso) {
747 		printf("\tcannot resolve %" PRIx64 "-%" PRIx64 "\n", start, end);
748 		return 0;
749 	}
750 	if (al.map->dso->data.status == DSO_DATA_STATUS_ERROR) {
751 		printf("\tcannot resolve %" PRIx64 "-%" PRIx64 "\n", start, end);
752 		return 0;
753 	}
754 
755 	/* Load maps to ensure dso->is_64_bit has been updated */
756 	map__load(al.map);
757 
758 	offset = al.map->map_ip(al.map, start);
759 	len = dso__data_read_offset(al.map->dso, machine, offset, (u8 *)buffer,
760 				    end - start + MAXINSN);
761 
762 	*is64bit = al.map->dso->is_64_bit;
763 	if (len <= 0)
764 		printf("\tcannot fetch code for block at %" PRIx64 "-%" PRIx64 "\n",
765 			start, end);
766 	return len;
767 }
768 
print_jump(uint64_t ip,struct branch_entry * en,struct perf_insn * x,u8 * inbuf,int len,int insn)769 static void print_jump(uint64_t ip, struct branch_entry *en,
770 		       struct perf_insn *x, u8 *inbuf, int len,
771 		       int insn)
772 {
773 	printf("\t%016" PRIx64 "\t%-30s\t#%s%s%s%s",
774 	       ip,
775 	       dump_insn(x, ip, inbuf, len, NULL),
776 	       en->flags.predicted ? " PRED" : "",
777 	       en->flags.mispred ? " MISPRED" : "",
778 	       en->flags.in_tx ? " INTX" : "",
779 	       en->flags.abort ? " ABORT" : "");
780 	if (en->flags.cycles) {
781 		printf(" %d cycles", en->flags.cycles);
782 		if (insn)
783 			printf(" %.2f IPC", (float)insn / en->flags.cycles);
784 	}
785 	putchar('\n');
786 }
787 
print_ip_sym(struct thread * thread,u8 cpumode,int cpu,uint64_t addr,struct symbol ** lastsym,struct perf_event_attr * attr)788 static void print_ip_sym(struct thread *thread, u8 cpumode, int cpu,
789 			 uint64_t addr, struct symbol **lastsym,
790 			 struct perf_event_attr *attr)
791 {
792 	struct addr_location al;
793 	int off;
794 
795 	memset(&al, 0, sizeof(al));
796 
797 	thread__find_addr_map(thread, cpumode, MAP__FUNCTION, addr, &al);
798 	if (!al.map)
799 		thread__find_addr_map(thread, cpumode, MAP__VARIABLE,
800 				      addr, &al);
801 	if ((*lastsym) && al.addr >= (*lastsym)->start && al.addr < (*lastsym)->end)
802 		return;
803 
804 	al.cpu = cpu;
805 	al.sym = NULL;
806 	if (al.map)
807 		al.sym = map__find_symbol(al.map, al.addr);
808 
809 	if (!al.sym)
810 		return;
811 
812 	if (al.addr < al.sym->end)
813 		off = al.addr - al.sym->start;
814 	else
815 		off = al.addr - al.map->start - al.sym->start;
816 	printf("\t%s", al.sym->name);
817 	if (off)
818 		printf("%+d", off);
819 	putchar(':');
820 	if (PRINT_FIELD(SRCLINE))
821 		map__fprintf_srcline(al.map, al.addr, "\t", stdout);
822 	putchar('\n');
823 	*lastsym = al.sym;
824 }
825 
print_sample_brstackinsn(struct perf_sample * sample,struct thread * thread,struct perf_event_attr * attr,struct machine * machine)826 static void print_sample_brstackinsn(struct perf_sample *sample,
827 				     struct thread *thread,
828 				     struct perf_event_attr *attr,
829 				     struct machine *machine)
830 {
831 	struct branch_stack *br = sample->branch_stack;
832 	u64 start, end;
833 	int i, insn, len, nr, ilen;
834 	struct perf_insn x;
835 	u8 buffer[MAXBB];
836 	unsigned off;
837 	struct symbol *lastsym = NULL;
838 
839 	if (!(br && br->nr))
840 		return;
841 	nr = br->nr;
842 	if (max_blocks && nr > max_blocks + 1)
843 		nr = max_blocks + 1;
844 
845 	x.thread = thread;
846 	x.cpu = sample->cpu;
847 
848 	putchar('\n');
849 
850 	/* Handle first from jump, of which we don't know the entry. */
851 	len = grab_bb(buffer, br->entries[nr-1].from,
852 			br->entries[nr-1].from,
853 			machine, thread, &x.is64bit, &x.cpumode, false);
854 	if (len > 0) {
855 		print_ip_sym(thread, x.cpumode, x.cpu,
856 			     br->entries[nr - 1].from, &lastsym, attr);
857 		print_jump(br->entries[nr - 1].from, &br->entries[nr - 1],
858 			    &x, buffer, len, 0);
859 	}
860 
861 	/* Print all blocks */
862 	for (i = nr - 2; i >= 0; i--) {
863 		if (br->entries[i].from || br->entries[i].to)
864 			pr_debug("%d: %" PRIx64 "-%" PRIx64 "\n", i,
865 				 br->entries[i].from,
866 				 br->entries[i].to);
867 		start = br->entries[i + 1].to;
868 		end   = br->entries[i].from;
869 
870 		len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, false);
871 		/* Patch up missing kernel transfers due to ring filters */
872 		if (len == -ENXIO && i > 0) {
873 			end = br->entries[--i].from;
874 			pr_debug("\tpatching up to %" PRIx64 "-%" PRIx64 "\n", start, end);
875 			len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, false);
876 		}
877 		if (len <= 0)
878 			continue;
879 
880 		insn = 0;
881 		for (off = 0;; off += ilen) {
882 			uint64_t ip = start + off;
883 
884 			print_ip_sym(thread, x.cpumode, x.cpu, ip, &lastsym, attr);
885 			if (ip == end) {
886 				print_jump(ip, &br->entries[i], &x, buffer + off, len - off, insn);
887 				break;
888 			} else {
889 				printf("\t%016" PRIx64 "\t%s\n", ip,
890 					dump_insn(&x, ip, buffer + off, len - off, &ilen));
891 				if (ilen == 0)
892 					break;
893 				insn++;
894 			}
895 		}
896 	}
897 
898 	/*
899 	 * Hit the branch? In this case we are already done, and the target
900 	 * has not been executed yet.
901 	 */
902 	if (br->entries[0].from == sample->ip)
903 		return;
904 	if (br->entries[0].flags.abort)
905 		return;
906 
907 	/*
908 	 * Print final block upto sample
909 	 */
910 	start = br->entries[0].to;
911 	end = sample->ip;
912 	len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, true);
913 	print_ip_sym(thread, x.cpumode, x.cpu, start, &lastsym, attr);
914 	if (len <= 0) {
915 		/* Print at least last IP if basic block did not work */
916 		len = grab_bb(buffer, sample->ip, sample->ip,
917 			      machine, thread, &x.is64bit, &x.cpumode, false);
918 		if (len <= 0)
919 			return;
920 
921 		printf("\t%016" PRIx64 "\t%s\n", sample->ip,
922 			dump_insn(&x, sample->ip, buffer, len, NULL));
923 		return;
924 	}
925 	for (off = 0; off <= end - start; off += ilen) {
926 		printf("\t%016" PRIx64 "\t%s\n", start + off,
927 			dump_insn(&x, start + off, buffer + off, len - off, &ilen));
928 		if (ilen == 0)
929 			break;
930 	}
931 }
932 
print_sample_addr(struct perf_sample * sample,struct thread * thread,struct perf_event_attr * attr)933 static void print_sample_addr(struct perf_sample *sample,
934 			  struct thread *thread,
935 			  struct perf_event_attr *attr)
936 {
937 	struct addr_location al;
938 
939 	printf("%16" PRIx64, sample->addr);
940 
941 	if (!sample_addr_correlates_sym(attr))
942 		return;
943 
944 	thread__resolve(thread, &al, sample);
945 
946 	if (PRINT_FIELD(SYM)) {
947 		printf(" ");
948 		if (PRINT_FIELD(SYMOFFSET))
949 			symbol__fprintf_symname_offs(al.sym, &al, stdout);
950 		else
951 			symbol__fprintf_symname(al.sym, stdout);
952 	}
953 
954 	if (PRINT_FIELD(DSO)) {
955 		printf(" (");
956 		map__fprintf_dsoname(al.map, stdout);
957 		printf(")");
958 	}
959 }
960 
print_sample_callindent(struct perf_sample * sample,struct perf_evsel * evsel,struct thread * thread,struct addr_location * al)961 static void print_sample_callindent(struct perf_sample *sample,
962 				    struct perf_evsel *evsel,
963 				    struct thread *thread,
964 				    struct addr_location *al)
965 {
966 	struct perf_event_attr *attr = &evsel->attr;
967 	size_t depth = thread_stack__depth(thread);
968 	struct addr_location addr_al;
969 	const char *name = NULL;
970 	static int spacing;
971 	int len = 0;
972 	u64 ip = 0;
973 
974 	/*
975 	 * The 'return' has already been popped off the stack so the depth has
976 	 * to be adjusted to match the 'call'.
977 	 */
978 	if (thread->ts && sample->flags & PERF_IP_FLAG_RETURN)
979 		depth += 1;
980 
981 	if (sample->flags & (PERF_IP_FLAG_CALL | PERF_IP_FLAG_TRACE_BEGIN)) {
982 		if (sample_addr_correlates_sym(attr)) {
983 			thread__resolve(thread, &addr_al, sample);
984 			if (addr_al.sym)
985 				name = addr_al.sym->name;
986 			else
987 				ip = sample->addr;
988 		} else {
989 			ip = sample->addr;
990 		}
991 	} else if (sample->flags & (PERF_IP_FLAG_RETURN | PERF_IP_FLAG_TRACE_END)) {
992 		if (al->sym)
993 			name = al->sym->name;
994 		else
995 			ip = sample->ip;
996 	}
997 
998 	if (name)
999 		len = printf("%*s%s", (int)depth * 4, "", name);
1000 	else if (ip)
1001 		len = printf("%*s%16" PRIx64, (int)depth * 4, "", ip);
1002 
1003 	if (len < 0)
1004 		return;
1005 
1006 	/*
1007 	 * Try to keep the output length from changing frequently so that the
1008 	 * output lines up more nicely.
1009 	 */
1010 	if (len > spacing || (len && len < spacing - 52))
1011 		spacing = round_up(len + 4, 32);
1012 
1013 	if (len < spacing)
1014 		printf("%*s", spacing - len, "");
1015 }
1016 
print_insn(struct perf_sample * sample,struct perf_event_attr * attr,struct thread * thread,struct machine * machine)1017 static void print_insn(struct perf_sample *sample,
1018 		       struct perf_event_attr *attr,
1019 		       struct thread *thread,
1020 		       struct machine *machine)
1021 {
1022 	if (PRINT_FIELD(INSNLEN))
1023 		printf(" ilen: %d", sample->insn_len);
1024 	if (PRINT_FIELD(INSN)) {
1025 		int i;
1026 
1027 		printf(" insn:");
1028 		for (i = 0; i < sample->insn_len; i++)
1029 			printf(" %02x", (unsigned char)sample->insn[i]);
1030 	}
1031 	if (PRINT_FIELD(BRSTACKINSN))
1032 		print_sample_brstackinsn(sample, thread, attr, machine);
1033 }
1034 
print_sample_bts(struct perf_sample * sample,struct perf_evsel * evsel,struct thread * thread,struct addr_location * al,struct machine * machine)1035 static void print_sample_bts(struct perf_sample *sample,
1036 			     struct perf_evsel *evsel,
1037 			     struct thread *thread,
1038 			     struct addr_location *al,
1039 			     struct machine *machine)
1040 {
1041 	struct perf_event_attr *attr = &evsel->attr;
1042 	unsigned int type = output_type(attr->type);
1043 	bool print_srcline_last = false;
1044 
1045 	if (PRINT_FIELD(CALLINDENT))
1046 		print_sample_callindent(sample, evsel, thread, al);
1047 
1048 	/* print branch_from information */
1049 	if (PRINT_FIELD(IP)) {
1050 		unsigned int print_opts = output[type].print_ip_opts;
1051 		struct callchain_cursor *cursor = NULL;
1052 
1053 		if (symbol_conf.use_callchain && sample->callchain &&
1054 		    thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
1055 					      sample, NULL, NULL, scripting_max_stack) == 0)
1056 			cursor = &callchain_cursor;
1057 
1058 		if (cursor == NULL) {
1059 			putchar(' ');
1060 			if (print_opts & EVSEL__PRINT_SRCLINE) {
1061 				print_srcline_last = true;
1062 				print_opts &= ~EVSEL__PRINT_SRCLINE;
1063 			}
1064 		} else
1065 			putchar('\n');
1066 
1067 		sample__fprintf_sym(sample, al, 0, print_opts, cursor, stdout);
1068 	}
1069 
1070 	/* print branch_to information */
1071 	if (PRINT_FIELD(ADDR) ||
1072 	    ((evsel->attr.sample_type & PERF_SAMPLE_ADDR) &&
1073 	     !output[type].user_set)) {
1074 		printf(" => ");
1075 		print_sample_addr(sample, thread, attr);
1076 	}
1077 
1078 	if (print_srcline_last)
1079 		map__fprintf_srcline(al->map, al->addr, "\n  ", stdout);
1080 
1081 	print_insn(sample, attr, thread, machine);
1082 
1083 	printf("\n");
1084 }
1085 
1086 static struct {
1087 	u32 flags;
1088 	const char *name;
1089 } sample_flags[] = {
1090 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL, "call"},
1091 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN, "return"},
1092 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CONDITIONAL, "jcc"},
1093 	{PERF_IP_FLAG_BRANCH, "jmp"},
1094 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_INTERRUPT, "int"},
1095 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN | PERF_IP_FLAG_INTERRUPT, "iret"},
1096 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_SYSCALLRET, "syscall"},
1097 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN | PERF_IP_FLAG_SYSCALLRET, "sysret"},
1098 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_ASYNC, "async"},
1099 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_ASYNC |	PERF_IP_FLAG_INTERRUPT, "hw int"},
1100 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TX_ABORT, "tx abrt"},
1101 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TRACE_BEGIN, "tr strt"},
1102 	{PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TRACE_END, "tr end"},
1103 	{0, NULL}
1104 };
1105 
print_sample_flags(u32 flags)1106 static void print_sample_flags(u32 flags)
1107 {
1108 	const char *chars = PERF_IP_FLAG_CHARS;
1109 	const int n = strlen(PERF_IP_FLAG_CHARS);
1110 	bool in_tx = flags & PERF_IP_FLAG_IN_TX;
1111 	const char *name = NULL;
1112 	char str[33];
1113 	int i, pos = 0;
1114 
1115 	for (i = 0; sample_flags[i].name ; i++) {
1116 		if (sample_flags[i].flags == (flags & ~PERF_IP_FLAG_IN_TX)) {
1117 			name = sample_flags[i].name;
1118 			break;
1119 		}
1120 	}
1121 
1122 	for (i = 0; i < n; i++, flags >>= 1) {
1123 		if (flags & 1)
1124 			str[pos++] = chars[i];
1125 	}
1126 	for (; i < 32; i++, flags >>= 1) {
1127 		if (flags & 1)
1128 			str[pos++] = '?';
1129 	}
1130 	str[pos] = 0;
1131 
1132 	if (name)
1133 		printf("  %-7s%4s ", name, in_tx ? "(x)" : "");
1134 	else
1135 		printf("  %-11s ", str);
1136 }
1137 
1138 struct printer_data {
1139 	int line_no;
1140 	bool hit_nul;
1141 	bool is_printable;
1142 };
1143 
1144 static void
print_sample_bpf_output_printer(enum binary_printer_ops op,unsigned int val,void * extra)1145 print_sample_bpf_output_printer(enum binary_printer_ops op,
1146 				unsigned int val,
1147 				void *extra)
1148 {
1149 	unsigned char ch = (unsigned char)val;
1150 	struct printer_data *printer_data = extra;
1151 
1152 	switch (op) {
1153 	case BINARY_PRINT_DATA_BEGIN:
1154 		printf("\n");
1155 		break;
1156 	case BINARY_PRINT_LINE_BEGIN:
1157 		printf("%17s", !printer_data->line_no ? "BPF output:" :
1158 						        "           ");
1159 		break;
1160 	case BINARY_PRINT_ADDR:
1161 		printf(" %04x:", val);
1162 		break;
1163 	case BINARY_PRINT_NUM_DATA:
1164 		printf(" %02x", val);
1165 		break;
1166 	case BINARY_PRINT_NUM_PAD:
1167 		printf("   ");
1168 		break;
1169 	case BINARY_PRINT_SEP:
1170 		printf("  ");
1171 		break;
1172 	case BINARY_PRINT_CHAR_DATA:
1173 		if (printer_data->hit_nul && ch)
1174 			printer_data->is_printable = false;
1175 
1176 		if (!isprint(ch)) {
1177 			printf("%c", '.');
1178 
1179 			if (!printer_data->is_printable)
1180 				break;
1181 
1182 			if (ch == '\0')
1183 				printer_data->hit_nul = true;
1184 			else
1185 				printer_data->is_printable = false;
1186 		} else {
1187 			printf("%c", ch);
1188 		}
1189 		break;
1190 	case BINARY_PRINT_CHAR_PAD:
1191 		printf(" ");
1192 		break;
1193 	case BINARY_PRINT_LINE_END:
1194 		printf("\n");
1195 		printer_data->line_no++;
1196 		break;
1197 	case BINARY_PRINT_DATA_END:
1198 	default:
1199 		break;
1200 	}
1201 }
1202 
print_sample_bpf_output(struct perf_sample * sample)1203 static void print_sample_bpf_output(struct perf_sample *sample)
1204 {
1205 	unsigned int nr_bytes = sample->raw_size;
1206 	struct printer_data printer_data = {0, false, true};
1207 
1208 	print_binary(sample->raw_data, nr_bytes, 8,
1209 		     print_sample_bpf_output_printer, &printer_data);
1210 
1211 	if (printer_data.is_printable && printer_data.hit_nul)
1212 		printf("%17s \"%s\"\n", "BPF string:",
1213 		       (char *)(sample->raw_data));
1214 }
1215 
print_sample_spacing(int len,int spacing)1216 static void print_sample_spacing(int len, int spacing)
1217 {
1218 	if (len > 0 && len < spacing)
1219 		printf("%*s", spacing - len, "");
1220 }
1221 
print_sample_pt_spacing(int len)1222 static void print_sample_pt_spacing(int len)
1223 {
1224 	print_sample_spacing(len, 34);
1225 }
1226 
print_sample_synth_ptwrite(struct perf_sample * sample)1227 static void print_sample_synth_ptwrite(struct perf_sample *sample)
1228 {
1229 	struct perf_synth_intel_ptwrite *data = perf_sample__synth_ptr(sample);
1230 	int len;
1231 
1232 	if (perf_sample__bad_synth_size(sample, *data))
1233 		return;
1234 
1235 	len = printf(" IP: %u payload: %#" PRIx64 " ",
1236 		     data->ip, le64_to_cpu(data->payload));
1237 	print_sample_pt_spacing(len);
1238 }
1239 
print_sample_synth_mwait(struct perf_sample * sample)1240 static void print_sample_synth_mwait(struct perf_sample *sample)
1241 {
1242 	struct perf_synth_intel_mwait *data = perf_sample__synth_ptr(sample);
1243 	int len;
1244 
1245 	if (perf_sample__bad_synth_size(sample, *data))
1246 		return;
1247 
1248 	len = printf(" hints: %#x extensions: %#x ",
1249 		     data->hints, data->extensions);
1250 	print_sample_pt_spacing(len);
1251 }
1252 
print_sample_synth_pwre(struct perf_sample * sample)1253 static void print_sample_synth_pwre(struct perf_sample *sample)
1254 {
1255 	struct perf_synth_intel_pwre *data = perf_sample__synth_ptr(sample);
1256 	int len;
1257 
1258 	if (perf_sample__bad_synth_size(sample, *data))
1259 		return;
1260 
1261 	len = printf(" hw: %u cstate: %u sub-cstate: %u ",
1262 		     data->hw, data->cstate, data->subcstate);
1263 	print_sample_pt_spacing(len);
1264 }
1265 
print_sample_synth_exstop(struct perf_sample * sample)1266 static void print_sample_synth_exstop(struct perf_sample *sample)
1267 {
1268 	struct perf_synth_intel_exstop *data = perf_sample__synth_ptr(sample);
1269 	int len;
1270 
1271 	if (perf_sample__bad_synth_size(sample, *data))
1272 		return;
1273 
1274 	len = printf(" IP: %u ", data->ip);
1275 	print_sample_pt_spacing(len);
1276 }
1277 
print_sample_synth_pwrx(struct perf_sample * sample)1278 static void print_sample_synth_pwrx(struct perf_sample *sample)
1279 {
1280 	struct perf_synth_intel_pwrx *data = perf_sample__synth_ptr(sample);
1281 	int len;
1282 
1283 	if (perf_sample__bad_synth_size(sample, *data))
1284 		return;
1285 
1286 	len = printf(" deepest cstate: %u last cstate: %u wake reason: %#x ",
1287 		     data->deepest_cstate, data->last_cstate,
1288 		     data->wake_reason);
1289 	print_sample_pt_spacing(len);
1290 }
1291 
print_sample_synth_cbr(struct perf_sample * sample)1292 static void print_sample_synth_cbr(struct perf_sample *sample)
1293 {
1294 	struct perf_synth_intel_cbr *data = perf_sample__synth_ptr(sample);
1295 	unsigned int percent, freq;
1296 	int len;
1297 
1298 	if (perf_sample__bad_synth_size(sample, *data))
1299 		return;
1300 
1301 	freq = (le32_to_cpu(data->freq) + 500) / 1000;
1302 	len = printf(" cbr: %2u freq: %4u MHz ", data->cbr, freq);
1303 	if (data->max_nonturbo) {
1304 		percent = (5 + (1000 * data->cbr) / data->max_nonturbo) / 10;
1305 		len += printf("(%3u%%) ", percent);
1306 	}
1307 	print_sample_pt_spacing(len);
1308 }
1309 
print_sample_synth(struct perf_sample * sample,struct perf_evsel * evsel)1310 static void print_sample_synth(struct perf_sample *sample,
1311 			       struct perf_evsel *evsel)
1312 {
1313 	switch (evsel->attr.config) {
1314 	case PERF_SYNTH_INTEL_PTWRITE:
1315 		print_sample_synth_ptwrite(sample);
1316 		break;
1317 	case PERF_SYNTH_INTEL_MWAIT:
1318 		print_sample_synth_mwait(sample);
1319 		break;
1320 	case PERF_SYNTH_INTEL_PWRE:
1321 		print_sample_synth_pwre(sample);
1322 		break;
1323 	case PERF_SYNTH_INTEL_EXSTOP:
1324 		print_sample_synth_exstop(sample);
1325 		break;
1326 	case PERF_SYNTH_INTEL_PWRX:
1327 		print_sample_synth_pwrx(sample);
1328 		break;
1329 	case PERF_SYNTH_INTEL_CBR:
1330 		print_sample_synth_cbr(sample);
1331 		break;
1332 	default:
1333 		break;
1334 	}
1335 }
1336 
1337 struct perf_script {
1338 	struct perf_tool	tool;
1339 	struct perf_session	*session;
1340 	bool			show_task_events;
1341 	bool			show_mmap_events;
1342 	bool			show_switch_events;
1343 	bool			show_namespace_events;
1344 	bool			allocated;
1345 	struct cpu_map		*cpus;
1346 	struct thread_map	*threads;
1347 	int			name_width;
1348 	const char              *time_str;
1349 	struct perf_time_interval ptime;
1350 };
1351 
perf_evlist__max_name_len(struct perf_evlist * evlist)1352 static int perf_evlist__max_name_len(struct perf_evlist *evlist)
1353 {
1354 	struct perf_evsel *evsel;
1355 	int max = 0;
1356 
1357 	evlist__for_each_entry(evlist, evsel) {
1358 		int len = strlen(perf_evsel__name(evsel));
1359 
1360 		max = MAX(len, max);
1361 	}
1362 
1363 	return max;
1364 }
1365 
data_src__printf(u64 data_src)1366 static size_t data_src__printf(u64 data_src)
1367 {
1368 	struct mem_info mi = { .data_src.val = data_src };
1369 	char decode[100];
1370 	char out[100];
1371 	static int maxlen;
1372 	int len;
1373 
1374 	perf_script__meminfo_scnprintf(decode, 100, &mi);
1375 
1376 	len = scnprintf(out, 100, "%16" PRIx64 " %s", data_src, decode);
1377 	if (maxlen < len)
1378 		maxlen = len;
1379 
1380 	return printf("%-*s", maxlen, out);
1381 }
1382 
process_event(struct perf_script * script,struct perf_sample * sample,struct perf_evsel * evsel,struct addr_location * al,struct machine * machine)1383 static void process_event(struct perf_script *script,
1384 			  struct perf_sample *sample, struct perf_evsel *evsel,
1385 			  struct addr_location *al,
1386 			  struct machine *machine)
1387 {
1388 	struct thread *thread = al->thread;
1389 	struct perf_event_attr *attr = &evsel->attr;
1390 	unsigned int type = output_type(attr->type);
1391 
1392 	if (output[type].fields == 0)
1393 		return;
1394 
1395 	print_sample_start(sample, thread, evsel);
1396 
1397 	if (PRINT_FIELD(PERIOD))
1398 		printf("%10" PRIu64 " ", sample->period);
1399 
1400 	if (PRINT_FIELD(EVNAME)) {
1401 		const char *evname = perf_evsel__name(evsel);
1402 
1403 		if (!script->name_width)
1404 			script->name_width = perf_evlist__max_name_len(script->session->evlist);
1405 
1406 		printf("%*s: ", script->name_width,
1407 		       evname ? evname : "[unknown]");
1408 	}
1409 
1410 	if (print_flags)
1411 		print_sample_flags(sample->flags);
1412 
1413 	if (is_bts_event(attr)) {
1414 		print_sample_bts(sample, evsel, thread, al, machine);
1415 		return;
1416 	}
1417 
1418 	if (PRINT_FIELD(TRACE))
1419 		event_format__print(evsel->tp_format, sample->cpu,
1420 				    sample->raw_data, sample->raw_size);
1421 
1422 	if (attr->type == PERF_TYPE_SYNTH && PRINT_FIELD(SYNTH))
1423 		print_sample_synth(sample, evsel);
1424 
1425 	if (PRINT_FIELD(ADDR))
1426 		print_sample_addr(sample, thread, attr);
1427 
1428 	if (PRINT_FIELD(DATA_SRC))
1429 		data_src__printf(sample->data_src);
1430 
1431 	if (PRINT_FIELD(WEIGHT))
1432 		printf("%16" PRIu64, sample->weight);
1433 
1434 	if (PRINT_FIELD(IP)) {
1435 		struct callchain_cursor *cursor = NULL;
1436 
1437 		if (symbol_conf.use_callchain && sample->callchain &&
1438 		    thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
1439 					      sample, NULL, NULL, scripting_max_stack) == 0)
1440 			cursor = &callchain_cursor;
1441 
1442 		putchar(cursor ? '\n' : ' ');
1443 		sample__fprintf_sym(sample, al, 0, output[type].print_ip_opts, cursor, stdout);
1444 	}
1445 
1446 	if (PRINT_FIELD(IREGS))
1447 		print_sample_iregs(sample, attr);
1448 
1449 	if (PRINT_FIELD(BRSTACK))
1450 		print_sample_brstack(sample, thread, attr);
1451 	else if (PRINT_FIELD(BRSTACKSYM))
1452 		print_sample_brstacksym(sample, thread, attr);
1453 	else if (PRINT_FIELD(BRSTACKOFF))
1454 		print_sample_brstackoff(sample, thread, attr);
1455 
1456 	if (perf_evsel__is_bpf_output(evsel) && PRINT_FIELD(BPF_OUTPUT))
1457 		print_sample_bpf_output(sample);
1458 	print_insn(sample, attr, thread, machine);
1459 
1460 	if (PRINT_FIELD(PHYS_ADDR))
1461 		printf("%16" PRIx64, sample->phys_addr);
1462 	printf("\n");
1463 }
1464 
1465 static struct scripting_ops	*scripting_ops;
1466 
__process_stat(struct perf_evsel * counter,u64 tstamp)1467 static void __process_stat(struct perf_evsel *counter, u64 tstamp)
1468 {
1469 	int nthreads = thread_map__nr(counter->threads);
1470 	int ncpus = perf_evsel__nr_cpus(counter);
1471 	int cpu, thread;
1472 	static int header_printed;
1473 
1474 	if (counter->system_wide)
1475 		nthreads = 1;
1476 
1477 	if (!header_printed) {
1478 		printf("%3s %8s %15s %15s %15s %15s %s\n",
1479 		       "CPU", "THREAD", "VAL", "ENA", "RUN", "TIME", "EVENT");
1480 		header_printed = 1;
1481 	}
1482 
1483 	for (thread = 0; thread < nthreads; thread++) {
1484 		for (cpu = 0; cpu < ncpus; cpu++) {
1485 			struct perf_counts_values *counts;
1486 
1487 			counts = perf_counts(counter->counts, cpu, thread);
1488 
1489 			printf("%3d %8d %15" PRIu64 " %15" PRIu64 " %15" PRIu64 " %15" PRIu64 " %s\n",
1490 				counter->cpus->map[cpu],
1491 				thread_map__pid(counter->threads, thread),
1492 				counts->val,
1493 				counts->ena,
1494 				counts->run,
1495 				tstamp,
1496 				perf_evsel__name(counter));
1497 		}
1498 	}
1499 }
1500 
process_stat(struct perf_evsel * counter,u64 tstamp)1501 static void process_stat(struct perf_evsel *counter, u64 tstamp)
1502 {
1503 	if (scripting_ops && scripting_ops->process_stat)
1504 		scripting_ops->process_stat(&stat_config, counter, tstamp);
1505 	else
1506 		__process_stat(counter, tstamp);
1507 }
1508 
process_stat_interval(u64 tstamp)1509 static void process_stat_interval(u64 tstamp)
1510 {
1511 	if (scripting_ops && scripting_ops->process_stat_interval)
1512 		scripting_ops->process_stat_interval(tstamp);
1513 }
1514 
setup_scripting(void)1515 static void setup_scripting(void)
1516 {
1517 	setup_perl_scripting();
1518 	setup_python_scripting();
1519 }
1520 
flush_scripting(void)1521 static int flush_scripting(void)
1522 {
1523 	return scripting_ops ? scripting_ops->flush_script() : 0;
1524 }
1525 
cleanup_scripting(void)1526 static int cleanup_scripting(void)
1527 {
1528 	pr_debug("\nperf script stopped\n");
1529 
1530 	return scripting_ops ? scripting_ops->stop_script() : 0;
1531 }
1532 
process_sample_event(struct perf_tool * tool,union perf_event * event,struct perf_sample * sample,struct perf_evsel * evsel,struct machine * machine)1533 static int process_sample_event(struct perf_tool *tool,
1534 				union perf_event *event,
1535 				struct perf_sample *sample,
1536 				struct perf_evsel *evsel,
1537 				struct machine *machine)
1538 {
1539 	struct perf_script *scr = container_of(tool, struct perf_script, tool);
1540 	struct addr_location al;
1541 
1542 	if (perf_time__skip_sample(&scr->ptime, sample->time))
1543 		return 0;
1544 
1545 	if (debug_mode) {
1546 		if (sample->time < last_timestamp) {
1547 			pr_err("Samples misordered, previous: %" PRIu64
1548 				" this: %" PRIu64 "\n", last_timestamp,
1549 				sample->time);
1550 			nr_unordered++;
1551 		}
1552 		last_timestamp = sample->time;
1553 		return 0;
1554 	}
1555 
1556 	if (machine__resolve(machine, &al, sample) < 0) {
1557 		pr_err("problem processing %d event, skipping it.\n",
1558 		       event->header.type);
1559 		return -1;
1560 	}
1561 
1562 	if (al.filtered)
1563 		goto out_put;
1564 
1565 	if (cpu_list && !test_bit(sample->cpu, cpu_bitmap))
1566 		goto out_put;
1567 
1568 	if (scripting_ops)
1569 		scripting_ops->process_event(event, sample, evsel, &al);
1570 	else
1571 		process_event(scr, sample, evsel, &al, machine);
1572 
1573 out_put:
1574 	addr_location__put(&al);
1575 	return 0;
1576 }
1577 
process_attr(struct perf_tool * tool,union perf_event * event,struct perf_evlist ** pevlist)1578 static int process_attr(struct perf_tool *tool, union perf_event *event,
1579 			struct perf_evlist **pevlist)
1580 {
1581 	struct perf_script *scr = container_of(tool, struct perf_script, tool);
1582 	struct perf_evlist *evlist;
1583 	struct perf_evsel *evsel, *pos;
1584 	int err;
1585 
1586 	err = perf_event__process_attr(tool, event, pevlist);
1587 	if (err)
1588 		return err;
1589 
1590 	evlist = *pevlist;
1591 	evsel = perf_evlist__last(*pevlist);
1592 
1593 	if (evsel->attr.type >= PERF_TYPE_MAX &&
1594 	    evsel->attr.type != PERF_TYPE_SYNTH)
1595 		return 0;
1596 
1597 	evlist__for_each_entry(evlist, pos) {
1598 		if (pos->attr.type == evsel->attr.type && pos != evsel)
1599 			return 0;
1600 	}
1601 
1602 	set_print_ip_opts(&evsel->attr);
1603 
1604 	if (evsel->attr.sample_type)
1605 		err = perf_evsel__check_attr(evsel, scr->session);
1606 
1607 	return err;
1608 }
1609 
process_comm_event(struct perf_tool * tool,union perf_event * event,struct perf_sample * sample,struct machine * machine)1610 static int process_comm_event(struct perf_tool *tool,
1611 			      union perf_event *event,
1612 			      struct perf_sample *sample,
1613 			      struct machine *machine)
1614 {
1615 	struct thread *thread;
1616 	struct perf_script *script = container_of(tool, struct perf_script, tool);
1617 	struct perf_session *session = script->session;
1618 	struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1619 	int ret = -1;
1620 
1621 	thread = machine__findnew_thread(machine, event->comm.pid, event->comm.tid);
1622 	if (thread == NULL) {
1623 		pr_debug("problem processing COMM event, skipping it.\n");
1624 		return -1;
1625 	}
1626 
1627 	if (perf_event__process_comm(tool, event, sample, machine) < 0)
1628 		goto out;
1629 
1630 	if (!evsel->attr.sample_id_all) {
1631 		sample->cpu = 0;
1632 		sample->time = 0;
1633 		sample->tid = event->comm.tid;
1634 		sample->pid = event->comm.pid;
1635 	}
1636 	print_sample_start(sample, thread, evsel);
1637 	perf_event__fprintf(event, stdout);
1638 	ret = 0;
1639 out:
1640 	thread__put(thread);
1641 	return ret;
1642 }
1643 
process_namespaces_event(struct perf_tool * tool,union perf_event * event,struct perf_sample * sample,struct machine * machine)1644 static int process_namespaces_event(struct perf_tool *tool,
1645 				    union perf_event *event,
1646 				    struct perf_sample *sample,
1647 				    struct machine *machine)
1648 {
1649 	struct thread *thread;
1650 	struct perf_script *script = container_of(tool, struct perf_script, tool);
1651 	struct perf_session *session = script->session;
1652 	struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1653 	int ret = -1;
1654 
1655 	thread = machine__findnew_thread(machine, event->namespaces.pid,
1656 					 event->namespaces.tid);
1657 	if (thread == NULL) {
1658 		pr_debug("problem processing NAMESPACES event, skipping it.\n");
1659 		return -1;
1660 	}
1661 
1662 	if (perf_event__process_namespaces(tool, event, sample, machine) < 0)
1663 		goto out;
1664 
1665 	if (!evsel->attr.sample_id_all) {
1666 		sample->cpu = 0;
1667 		sample->time = 0;
1668 		sample->tid = event->namespaces.tid;
1669 		sample->pid = event->namespaces.pid;
1670 	}
1671 	print_sample_start(sample, thread, evsel);
1672 	perf_event__fprintf(event, stdout);
1673 	ret = 0;
1674 out:
1675 	thread__put(thread);
1676 	return ret;
1677 }
1678 
process_fork_event(struct perf_tool * tool,union perf_event * event,struct perf_sample * sample,struct machine * machine)1679 static int process_fork_event(struct perf_tool *tool,
1680 			      union perf_event *event,
1681 			      struct perf_sample *sample,
1682 			      struct machine *machine)
1683 {
1684 	struct thread *thread;
1685 	struct perf_script *script = container_of(tool, struct perf_script, tool);
1686 	struct perf_session *session = script->session;
1687 	struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1688 
1689 	if (perf_event__process_fork(tool, event, sample, machine) < 0)
1690 		return -1;
1691 
1692 	thread = machine__findnew_thread(machine, event->fork.pid, event->fork.tid);
1693 	if (thread == NULL) {
1694 		pr_debug("problem processing FORK event, skipping it.\n");
1695 		return -1;
1696 	}
1697 
1698 	if (!evsel->attr.sample_id_all) {
1699 		sample->cpu = 0;
1700 		sample->time = event->fork.time;
1701 		sample->tid = event->fork.tid;
1702 		sample->pid = event->fork.pid;
1703 	}
1704 	print_sample_start(sample, thread, evsel);
1705 	perf_event__fprintf(event, stdout);
1706 	thread__put(thread);
1707 
1708 	return 0;
1709 }
process_exit_event(struct perf_tool * tool,union perf_event * event,struct perf_sample * sample,struct machine * machine)1710 static int process_exit_event(struct perf_tool *tool,
1711 			      union perf_event *event,
1712 			      struct perf_sample *sample,
1713 			      struct machine *machine)
1714 {
1715 	int err = 0;
1716 	struct thread *thread;
1717 	struct perf_script *script = container_of(tool, struct perf_script, tool);
1718 	struct perf_session *session = script->session;
1719 	struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1720 
1721 	thread = machine__findnew_thread(machine, event->fork.pid, event->fork.tid);
1722 	if (thread == NULL) {
1723 		pr_debug("problem processing EXIT event, skipping it.\n");
1724 		return -1;
1725 	}
1726 
1727 	if (!evsel->attr.sample_id_all) {
1728 		sample->cpu = 0;
1729 		sample->time = 0;
1730 		sample->tid = event->fork.tid;
1731 		sample->pid = event->fork.pid;
1732 	}
1733 	print_sample_start(sample, thread, evsel);
1734 	perf_event__fprintf(event, stdout);
1735 
1736 	if (perf_event__process_exit(tool, event, sample, machine) < 0)
1737 		err = -1;
1738 
1739 	thread__put(thread);
1740 	return err;
1741 }
1742 
process_mmap_event(struct perf_tool * tool,union perf_event * event,struct perf_sample * sample,struct machine * machine)1743 static int process_mmap_event(struct perf_tool *tool,
1744 			      union perf_event *event,
1745 			      struct perf_sample *sample,
1746 			      struct machine *machine)
1747 {
1748 	struct thread *thread;
1749 	struct perf_script *script = container_of(tool, struct perf_script, tool);
1750 	struct perf_session *session = script->session;
1751 	struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1752 
1753 	if (perf_event__process_mmap(tool, event, sample, machine) < 0)
1754 		return -1;
1755 
1756 	thread = machine__findnew_thread(machine, event->mmap.pid, event->mmap.tid);
1757 	if (thread == NULL) {
1758 		pr_debug("problem processing MMAP event, skipping it.\n");
1759 		return -1;
1760 	}
1761 
1762 	if (!evsel->attr.sample_id_all) {
1763 		sample->cpu = 0;
1764 		sample->time = 0;
1765 		sample->tid = event->mmap.tid;
1766 		sample->pid = event->mmap.pid;
1767 	}
1768 	print_sample_start(sample, thread, evsel);
1769 	perf_event__fprintf(event, stdout);
1770 	thread__put(thread);
1771 	return 0;
1772 }
1773 
process_mmap2_event(struct perf_tool * tool,union perf_event * event,struct perf_sample * sample,struct machine * machine)1774 static int process_mmap2_event(struct perf_tool *tool,
1775 			      union perf_event *event,
1776 			      struct perf_sample *sample,
1777 			      struct machine *machine)
1778 {
1779 	struct thread *thread;
1780 	struct perf_script *script = container_of(tool, struct perf_script, tool);
1781 	struct perf_session *session = script->session;
1782 	struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1783 
1784 	if (perf_event__process_mmap2(tool, event, sample, machine) < 0)
1785 		return -1;
1786 
1787 	thread = machine__findnew_thread(machine, event->mmap2.pid, event->mmap2.tid);
1788 	if (thread == NULL) {
1789 		pr_debug("problem processing MMAP2 event, skipping it.\n");
1790 		return -1;
1791 	}
1792 
1793 	if (!evsel->attr.sample_id_all) {
1794 		sample->cpu = 0;
1795 		sample->time = 0;
1796 		sample->tid = event->mmap2.tid;
1797 		sample->pid = event->mmap2.pid;
1798 	}
1799 	print_sample_start(sample, thread, evsel);
1800 	perf_event__fprintf(event, stdout);
1801 	thread__put(thread);
1802 	return 0;
1803 }
1804 
process_switch_event(struct perf_tool * tool,union perf_event * event,struct perf_sample * sample,struct machine * machine)1805 static int process_switch_event(struct perf_tool *tool,
1806 				union perf_event *event,
1807 				struct perf_sample *sample,
1808 				struct machine *machine)
1809 {
1810 	struct thread *thread;
1811 	struct perf_script *script = container_of(tool, struct perf_script, tool);
1812 	struct perf_session *session = script->session;
1813 	struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1814 
1815 	if (perf_event__process_switch(tool, event, sample, machine) < 0)
1816 		return -1;
1817 
1818 	thread = machine__findnew_thread(machine, sample->pid,
1819 					 sample->tid);
1820 	if (thread == NULL) {
1821 		pr_debug("problem processing SWITCH event, skipping it.\n");
1822 		return -1;
1823 	}
1824 
1825 	print_sample_start(sample, thread, evsel);
1826 	perf_event__fprintf(event, stdout);
1827 	thread__put(thread);
1828 	return 0;
1829 }
1830 
sig_handler(int sig __maybe_unused)1831 static void sig_handler(int sig __maybe_unused)
1832 {
1833 	session_done = 1;
1834 }
1835 
__cmd_script(struct perf_script * script)1836 static int __cmd_script(struct perf_script *script)
1837 {
1838 	int ret;
1839 
1840 	signal(SIGINT, sig_handler);
1841 
1842 	/* override event processing functions */
1843 	if (script->show_task_events) {
1844 		script->tool.comm = process_comm_event;
1845 		script->tool.fork = process_fork_event;
1846 		script->tool.exit = process_exit_event;
1847 	}
1848 	if (script->show_mmap_events) {
1849 		script->tool.mmap = process_mmap_event;
1850 		script->tool.mmap2 = process_mmap2_event;
1851 	}
1852 	if (script->show_switch_events)
1853 		script->tool.context_switch = process_switch_event;
1854 	if (script->show_namespace_events)
1855 		script->tool.namespaces = process_namespaces_event;
1856 
1857 	ret = perf_session__process_events(script->session);
1858 
1859 	if (debug_mode)
1860 		pr_err("Misordered timestamps: %" PRIu64 "\n", nr_unordered);
1861 
1862 	return ret;
1863 }
1864 
1865 struct script_spec {
1866 	struct list_head	node;
1867 	struct scripting_ops	*ops;
1868 	char			spec[0];
1869 };
1870 
1871 static LIST_HEAD(script_specs);
1872 
script_spec__new(const char * spec,struct scripting_ops * ops)1873 static struct script_spec *script_spec__new(const char *spec,
1874 					    struct scripting_ops *ops)
1875 {
1876 	struct script_spec *s = malloc(sizeof(*s) + strlen(spec) + 1);
1877 
1878 	if (s != NULL) {
1879 		strcpy(s->spec, spec);
1880 		s->ops = ops;
1881 	}
1882 
1883 	return s;
1884 }
1885 
script_spec__add(struct script_spec * s)1886 static void script_spec__add(struct script_spec *s)
1887 {
1888 	list_add_tail(&s->node, &script_specs);
1889 }
1890 
script_spec__find(const char * spec)1891 static struct script_spec *script_spec__find(const char *spec)
1892 {
1893 	struct script_spec *s;
1894 
1895 	list_for_each_entry(s, &script_specs, node)
1896 		if (strcasecmp(s->spec, spec) == 0)
1897 			return s;
1898 	return NULL;
1899 }
1900 
script_spec_register(const char * spec,struct scripting_ops * ops)1901 int script_spec_register(const char *spec, struct scripting_ops *ops)
1902 {
1903 	struct script_spec *s;
1904 
1905 	s = script_spec__find(spec);
1906 	if (s)
1907 		return -1;
1908 
1909 	s = script_spec__new(spec, ops);
1910 	if (!s)
1911 		return -1;
1912 	else
1913 		script_spec__add(s);
1914 
1915 	return 0;
1916 }
1917 
script_spec__lookup(const char * spec)1918 static struct scripting_ops *script_spec__lookup(const char *spec)
1919 {
1920 	struct script_spec *s = script_spec__find(spec);
1921 	if (!s)
1922 		return NULL;
1923 
1924 	return s->ops;
1925 }
1926 
list_available_languages(void)1927 static void list_available_languages(void)
1928 {
1929 	struct script_spec *s;
1930 
1931 	fprintf(stderr, "\n");
1932 	fprintf(stderr, "Scripting language extensions (used in "
1933 		"perf script -s [spec:]script.[spec]):\n\n");
1934 
1935 	list_for_each_entry(s, &script_specs, node)
1936 		fprintf(stderr, "  %-42s [%s]\n", s->spec, s->ops->name);
1937 
1938 	fprintf(stderr, "\n");
1939 }
1940 
parse_scriptname(const struct option * opt __maybe_unused,const char * str,int unset __maybe_unused)1941 static int parse_scriptname(const struct option *opt __maybe_unused,
1942 			    const char *str, int unset __maybe_unused)
1943 {
1944 	char spec[PATH_MAX];
1945 	const char *script, *ext;
1946 	int len;
1947 
1948 	if (strcmp(str, "lang") == 0) {
1949 		list_available_languages();
1950 		exit(0);
1951 	}
1952 
1953 	script = strchr(str, ':');
1954 	if (script) {
1955 		len = script - str;
1956 		if (len >= PATH_MAX) {
1957 			fprintf(stderr, "invalid language specifier");
1958 			return -1;
1959 		}
1960 		strncpy(spec, str, len);
1961 		spec[len] = '\0';
1962 		scripting_ops = script_spec__lookup(spec);
1963 		if (!scripting_ops) {
1964 			fprintf(stderr, "invalid language specifier");
1965 			return -1;
1966 		}
1967 		script++;
1968 	} else {
1969 		script = str;
1970 		ext = strrchr(script, '.');
1971 		if (!ext) {
1972 			fprintf(stderr, "invalid script extension");
1973 			return -1;
1974 		}
1975 		scripting_ops = script_spec__lookup(++ext);
1976 		if (!scripting_ops) {
1977 			fprintf(stderr, "invalid script extension");
1978 			return -1;
1979 		}
1980 	}
1981 
1982 	script_name = strdup(script);
1983 
1984 	return 0;
1985 }
1986 
parse_output_fields(const struct option * opt __maybe_unused,const char * arg,int unset __maybe_unused)1987 static int parse_output_fields(const struct option *opt __maybe_unused,
1988 			    const char *arg, int unset __maybe_unused)
1989 {
1990 	char *tok, *strtok_saveptr = NULL;
1991 	int i, imax = ARRAY_SIZE(all_output_options);
1992 	int j;
1993 	int rc = 0;
1994 	char *str = strdup(arg);
1995 	int type = -1;
1996 	enum { DEFAULT, SET, ADD, REMOVE } change = DEFAULT;
1997 
1998 	if (!str)
1999 		return -ENOMEM;
2000 
2001 	/* first word can state for which event type the user is specifying
2002 	 * the fields. If no type exists, the specified fields apply to all
2003 	 * event types found in the file minus the invalid fields for a type.
2004 	 */
2005 	tok = strchr(str, ':');
2006 	if (tok) {
2007 		*tok = '\0';
2008 		tok++;
2009 		if (!strcmp(str, "hw"))
2010 			type = PERF_TYPE_HARDWARE;
2011 		else if (!strcmp(str, "sw"))
2012 			type = PERF_TYPE_SOFTWARE;
2013 		else if (!strcmp(str, "trace"))
2014 			type = PERF_TYPE_TRACEPOINT;
2015 		else if (!strcmp(str, "raw"))
2016 			type = PERF_TYPE_RAW;
2017 		else if (!strcmp(str, "break"))
2018 			type = PERF_TYPE_BREAKPOINT;
2019 		else if (!strcmp(str, "synth"))
2020 			type = OUTPUT_TYPE_SYNTH;
2021 		else {
2022 			fprintf(stderr, "Invalid event type in field string.\n");
2023 			rc = -EINVAL;
2024 			goto out;
2025 		}
2026 
2027 		if (output[type].user_set)
2028 			pr_warning("Overriding previous field request for %s events.\n",
2029 				   event_type(type));
2030 
2031 		output[type].fields = 0;
2032 		output[type].user_set = true;
2033 		output[type].wildcard_set = false;
2034 
2035 	} else {
2036 		tok = str;
2037 		if (strlen(str) == 0) {
2038 			fprintf(stderr,
2039 				"Cannot set fields to 'none' for all event types.\n");
2040 			rc = -EINVAL;
2041 			goto out;
2042 		}
2043 
2044 		/* Don't override defaults for +- */
2045 		if (strchr(str, '+') || strchr(str, '-'))
2046 			goto parse;
2047 
2048 		if (output_set_by_user())
2049 			pr_warning("Overriding previous field request for all events.\n");
2050 
2051 		for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
2052 			output[j].fields = 0;
2053 			output[j].user_set = true;
2054 			output[j].wildcard_set = true;
2055 		}
2056 	}
2057 
2058 parse:
2059 	for (tok = strtok_r(tok, ",", &strtok_saveptr); tok; tok = strtok_r(NULL, ",", &strtok_saveptr)) {
2060 		if (*tok == '+') {
2061 			if (change == SET)
2062 				goto out_badmix;
2063 			change = ADD;
2064 			tok++;
2065 		} else if (*tok == '-') {
2066 			if (change == SET)
2067 				goto out_badmix;
2068 			change = REMOVE;
2069 			tok++;
2070 		} else {
2071 			if (change != SET && change != DEFAULT)
2072 				goto out_badmix;
2073 			change = SET;
2074 		}
2075 
2076 		for (i = 0; i < imax; ++i) {
2077 			if (strcmp(tok, all_output_options[i].str) == 0)
2078 				break;
2079 		}
2080 		if (i == imax && strcmp(tok, "flags") == 0) {
2081 			print_flags = change == REMOVE ? false : true;
2082 			continue;
2083 		}
2084 		if (i == imax) {
2085 			fprintf(stderr, "Invalid field requested.\n");
2086 			rc = -EINVAL;
2087 			goto out;
2088 		}
2089 
2090 		if (type == -1) {
2091 			/* add user option to all events types for
2092 			 * which it is valid
2093 			 */
2094 			for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
2095 				if (output[j].invalid_fields & all_output_options[i].field) {
2096 					pr_warning("\'%s\' not valid for %s events. Ignoring.\n",
2097 						   all_output_options[i].str, event_type(j));
2098 				} else {
2099 					if (change == REMOVE)
2100 						output[j].fields &= ~all_output_options[i].field;
2101 					else
2102 						output[j].fields |= all_output_options[i].field;
2103 				}
2104 			}
2105 		} else {
2106 			if (output[type].invalid_fields & all_output_options[i].field) {
2107 				fprintf(stderr, "\'%s\' not valid for %s events.\n",
2108 					 all_output_options[i].str, event_type(type));
2109 
2110 				rc = -EINVAL;
2111 				goto out;
2112 			}
2113 			output[type].fields |= all_output_options[i].field;
2114 		}
2115 	}
2116 
2117 	if (type >= 0) {
2118 		if (output[type].fields == 0) {
2119 			pr_debug("No fields requested for %s type. "
2120 				 "Events will not be displayed.\n", event_type(type));
2121 		}
2122 	}
2123 	goto out;
2124 
2125 out_badmix:
2126 	fprintf(stderr, "Cannot mix +-field with overridden fields\n");
2127 	rc = -EINVAL;
2128 out:
2129 	free(str);
2130 	return rc;
2131 }
2132 
2133 #define for_each_lang(scripts_path, scripts_dir, lang_dirent)		\
2134 	while ((lang_dirent = readdir(scripts_dir)) != NULL)		\
2135 		if ((lang_dirent->d_type == DT_DIR ||			\
2136 		     (lang_dirent->d_type == DT_UNKNOWN &&		\
2137 		      is_directory(scripts_path, lang_dirent))) &&	\
2138 		    (strcmp(lang_dirent->d_name, ".")) &&		\
2139 		    (strcmp(lang_dirent->d_name, "..")))
2140 
2141 #define for_each_script(lang_path, lang_dir, script_dirent)		\
2142 	while ((script_dirent = readdir(lang_dir)) != NULL)		\
2143 		if (script_dirent->d_type != DT_DIR &&			\
2144 		    (script_dirent->d_type != DT_UNKNOWN ||		\
2145 		     !is_directory(lang_path, script_dirent)))
2146 
2147 
2148 #define RECORD_SUFFIX			"-record"
2149 #define REPORT_SUFFIX			"-report"
2150 
2151 struct script_desc {
2152 	struct list_head	node;
2153 	char			*name;
2154 	char			*half_liner;
2155 	char			*args;
2156 };
2157 
2158 static LIST_HEAD(script_descs);
2159 
script_desc__new(const char * name)2160 static struct script_desc *script_desc__new(const char *name)
2161 {
2162 	struct script_desc *s = zalloc(sizeof(*s));
2163 
2164 	if (s != NULL && name)
2165 		s->name = strdup(name);
2166 
2167 	return s;
2168 }
2169 
script_desc__delete(struct script_desc * s)2170 static void script_desc__delete(struct script_desc *s)
2171 {
2172 	zfree(&s->name);
2173 	zfree(&s->half_liner);
2174 	zfree(&s->args);
2175 	free(s);
2176 }
2177 
script_desc__add(struct script_desc * s)2178 static void script_desc__add(struct script_desc *s)
2179 {
2180 	list_add_tail(&s->node, &script_descs);
2181 }
2182 
script_desc__find(const char * name)2183 static struct script_desc *script_desc__find(const char *name)
2184 {
2185 	struct script_desc *s;
2186 
2187 	list_for_each_entry(s, &script_descs, node)
2188 		if (strcasecmp(s->name, name) == 0)
2189 			return s;
2190 	return NULL;
2191 }
2192 
script_desc__findnew(const char * name)2193 static struct script_desc *script_desc__findnew(const char *name)
2194 {
2195 	struct script_desc *s = script_desc__find(name);
2196 
2197 	if (s)
2198 		return s;
2199 
2200 	s = script_desc__new(name);
2201 	if (!s)
2202 		return NULL;
2203 
2204 	script_desc__add(s);
2205 
2206 	return s;
2207 }
2208 
ends_with(const char * str,const char * suffix)2209 static const char *ends_with(const char *str, const char *suffix)
2210 {
2211 	size_t suffix_len = strlen(suffix);
2212 	const char *p = str;
2213 
2214 	if (strlen(str) > suffix_len) {
2215 		p = str + strlen(str) - suffix_len;
2216 		if (!strncmp(p, suffix, suffix_len))
2217 			return p;
2218 	}
2219 
2220 	return NULL;
2221 }
2222 
read_script_info(struct script_desc * desc,const char * filename)2223 static int read_script_info(struct script_desc *desc, const char *filename)
2224 {
2225 	char line[BUFSIZ], *p;
2226 	FILE *fp;
2227 
2228 	fp = fopen(filename, "r");
2229 	if (!fp)
2230 		return -1;
2231 
2232 	while (fgets(line, sizeof(line), fp)) {
2233 		p = ltrim(line);
2234 		if (strlen(p) == 0)
2235 			continue;
2236 		if (*p != '#')
2237 			continue;
2238 		p++;
2239 		if (strlen(p) && *p == '!')
2240 			continue;
2241 
2242 		p = ltrim(p);
2243 		if (strlen(p) && p[strlen(p) - 1] == '\n')
2244 			p[strlen(p) - 1] = '\0';
2245 
2246 		if (!strncmp(p, "description:", strlen("description:"))) {
2247 			p += strlen("description:");
2248 			desc->half_liner = strdup(ltrim(p));
2249 			continue;
2250 		}
2251 
2252 		if (!strncmp(p, "args:", strlen("args:"))) {
2253 			p += strlen("args:");
2254 			desc->args = strdup(ltrim(p));
2255 			continue;
2256 		}
2257 	}
2258 
2259 	fclose(fp);
2260 
2261 	return 0;
2262 }
2263 
get_script_root(struct dirent * script_dirent,const char * suffix)2264 static char *get_script_root(struct dirent *script_dirent, const char *suffix)
2265 {
2266 	char *script_root, *str;
2267 
2268 	script_root = strdup(script_dirent->d_name);
2269 	if (!script_root)
2270 		return NULL;
2271 
2272 	str = (char *)ends_with(script_root, suffix);
2273 	if (!str) {
2274 		free(script_root);
2275 		return NULL;
2276 	}
2277 
2278 	*str = '\0';
2279 	return script_root;
2280 }
2281 
list_available_scripts(const struct option * opt __maybe_unused,const char * s __maybe_unused,int unset __maybe_unused)2282 static int list_available_scripts(const struct option *opt __maybe_unused,
2283 				  const char *s __maybe_unused,
2284 				  int unset __maybe_unused)
2285 {
2286 	struct dirent *script_dirent, *lang_dirent;
2287 	char scripts_path[MAXPATHLEN];
2288 	DIR *scripts_dir, *lang_dir;
2289 	char script_path[MAXPATHLEN];
2290 	char lang_path[MAXPATHLEN];
2291 	struct script_desc *desc;
2292 	char first_half[BUFSIZ];
2293 	char *script_root;
2294 
2295 	snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2296 
2297 	scripts_dir = opendir(scripts_path);
2298 	if (!scripts_dir) {
2299 		fprintf(stdout,
2300 			"open(%s) failed.\n"
2301 			"Check \"PERF_EXEC_PATH\" env to set scripts dir.\n",
2302 			scripts_path);
2303 		exit(-1);
2304 	}
2305 
2306 	for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2307 		scnprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
2308 			  lang_dirent->d_name);
2309 		lang_dir = opendir(lang_path);
2310 		if (!lang_dir)
2311 			continue;
2312 
2313 		for_each_script(lang_path, lang_dir, script_dirent) {
2314 			script_root = get_script_root(script_dirent, REPORT_SUFFIX);
2315 			if (script_root) {
2316 				desc = script_desc__findnew(script_root);
2317 				scnprintf(script_path, MAXPATHLEN, "%s/%s",
2318 					  lang_path, script_dirent->d_name);
2319 				read_script_info(desc, script_path);
2320 				free(script_root);
2321 			}
2322 		}
2323 	}
2324 
2325 	fprintf(stdout, "List of available trace scripts:\n");
2326 	list_for_each_entry(desc, &script_descs, node) {
2327 		sprintf(first_half, "%s %s", desc->name,
2328 			desc->args ? desc->args : "");
2329 		fprintf(stdout, "  %-36s %s\n", first_half,
2330 			desc->half_liner ? desc->half_liner : "");
2331 	}
2332 
2333 	exit(0);
2334 }
2335 
2336 /*
2337  * Some scripts specify the required events in their "xxx-record" file,
2338  * this function will check if the events in perf.data match those
2339  * mentioned in the "xxx-record".
2340  *
2341  * Fixme: All existing "xxx-record" are all in good formats "-e event ",
2342  * which is covered well now. And new parsing code should be added to
2343  * cover the future complexing formats like event groups etc.
2344  */
check_ev_match(char * dir_name,char * scriptname,struct perf_session * session)2345 static int check_ev_match(char *dir_name, char *scriptname,
2346 			struct perf_session *session)
2347 {
2348 	char filename[MAXPATHLEN], evname[128];
2349 	char line[BUFSIZ], *p;
2350 	struct perf_evsel *pos;
2351 	int match, len;
2352 	FILE *fp;
2353 
2354 	scnprintf(filename, MAXPATHLEN, "%s/bin/%s-record", dir_name, scriptname);
2355 
2356 	fp = fopen(filename, "r");
2357 	if (!fp)
2358 		return -1;
2359 
2360 	while (fgets(line, sizeof(line), fp)) {
2361 		p = ltrim(line);
2362 		if (*p == '#')
2363 			continue;
2364 
2365 		while (strlen(p)) {
2366 			p = strstr(p, "-e");
2367 			if (!p)
2368 				break;
2369 
2370 			p += 2;
2371 			p = ltrim(p);
2372 			len = strcspn(p, " \t");
2373 			if (!len)
2374 				break;
2375 
2376 			snprintf(evname, len + 1, "%s", p);
2377 
2378 			match = 0;
2379 			evlist__for_each_entry(session->evlist, pos) {
2380 				if (!strcmp(perf_evsel__name(pos), evname)) {
2381 					match = 1;
2382 					break;
2383 				}
2384 			}
2385 
2386 			if (!match) {
2387 				fclose(fp);
2388 				return -1;
2389 			}
2390 		}
2391 	}
2392 
2393 	fclose(fp);
2394 	return 0;
2395 }
2396 
2397 /*
2398  * Return -1 if none is found, otherwise the actual scripts number.
2399  *
2400  * Currently the only user of this function is the script browser, which
2401  * will list all statically runnable scripts, select one, execute it and
2402  * show the output in a perf browser.
2403  */
find_scripts(char ** scripts_array,char ** scripts_path_array)2404 int find_scripts(char **scripts_array, char **scripts_path_array)
2405 {
2406 	struct dirent *script_dirent, *lang_dirent;
2407 	char scripts_path[MAXPATHLEN], lang_path[MAXPATHLEN];
2408 	DIR *scripts_dir, *lang_dir;
2409 	struct perf_session *session;
2410 	struct perf_data_file file = {
2411 		.path = input_name,
2412 		.mode = PERF_DATA_MODE_READ,
2413 	};
2414 	char *temp;
2415 	int i = 0;
2416 
2417 	session = perf_session__new(&file, false, NULL);
2418 	if (!session)
2419 		return -1;
2420 
2421 	snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2422 
2423 	scripts_dir = opendir(scripts_path);
2424 	if (!scripts_dir) {
2425 		perf_session__delete(session);
2426 		return -1;
2427 	}
2428 
2429 	for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2430 		scnprintf(lang_path, MAXPATHLEN, "%s/%s", scripts_path,
2431 			  lang_dirent->d_name);
2432 #ifdef NO_LIBPERL
2433 		if (strstr(lang_path, "perl"))
2434 			continue;
2435 #endif
2436 #ifdef NO_LIBPYTHON
2437 		if (strstr(lang_path, "python"))
2438 			continue;
2439 #endif
2440 
2441 		lang_dir = opendir(lang_path);
2442 		if (!lang_dir)
2443 			continue;
2444 
2445 		for_each_script(lang_path, lang_dir, script_dirent) {
2446 			/* Skip those real time scripts: xxxtop.p[yl] */
2447 			if (strstr(script_dirent->d_name, "top."))
2448 				continue;
2449 			sprintf(scripts_path_array[i], "%s/%s", lang_path,
2450 				script_dirent->d_name);
2451 			temp = strchr(script_dirent->d_name, '.');
2452 			snprintf(scripts_array[i],
2453 				(temp - script_dirent->d_name) + 1,
2454 				"%s", script_dirent->d_name);
2455 
2456 			if (check_ev_match(lang_path,
2457 					scripts_array[i], session))
2458 				continue;
2459 
2460 			i++;
2461 		}
2462 		closedir(lang_dir);
2463 	}
2464 
2465 	closedir(scripts_dir);
2466 	perf_session__delete(session);
2467 	return i;
2468 }
2469 
get_script_path(const char * script_root,const char * suffix)2470 static char *get_script_path(const char *script_root, const char *suffix)
2471 {
2472 	struct dirent *script_dirent, *lang_dirent;
2473 	char scripts_path[MAXPATHLEN];
2474 	char script_path[MAXPATHLEN];
2475 	DIR *scripts_dir, *lang_dir;
2476 	char lang_path[MAXPATHLEN];
2477 	char *__script_root;
2478 
2479 	snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2480 
2481 	scripts_dir = opendir(scripts_path);
2482 	if (!scripts_dir)
2483 		return NULL;
2484 
2485 	for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2486 		scnprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
2487 			  lang_dirent->d_name);
2488 		lang_dir = opendir(lang_path);
2489 		if (!lang_dir)
2490 			continue;
2491 
2492 		for_each_script(lang_path, lang_dir, script_dirent) {
2493 			__script_root = get_script_root(script_dirent, suffix);
2494 			if (__script_root && !strcmp(script_root, __script_root)) {
2495 				free(__script_root);
2496 				closedir(lang_dir);
2497 				closedir(scripts_dir);
2498 				scnprintf(script_path, MAXPATHLEN, "%s/%s",
2499 					  lang_path, script_dirent->d_name);
2500 				return strdup(script_path);
2501 			}
2502 			free(__script_root);
2503 		}
2504 		closedir(lang_dir);
2505 	}
2506 	closedir(scripts_dir);
2507 
2508 	return NULL;
2509 }
2510 
is_top_script(const char * script_path)2511 static bool is_top_script(const char *script_path)
2512 {
2513 	return ends_with(script_path, "top") == NULL ? false : true;
2514 }
2515 
has_required_arg(char * script_path)2516 static int has_required_arg(char *script_path)
2517 {
2518 	struct script_desc *desc;
2519 	int n_args = 0;
2520 	char *p;
2521 
2522 	desc = script_desc__new(NULL);
2523 
2524 	if (read_script_info(desc, script_path))
2525 		goto out;
2526 
2527 	if (!desc->args)
2528 		goto out;
2529 
2530 	for (p = desc->args; *p; p++)
2531 		if (*p == '<')
2532 			n_args++;
2533 out:
2534 	script_desc__delete(desc);
2535 
2536 	return n_args;
2537 }
2538 
have_cmd(int argc,const char ** argv)2539 static int have_cmd(int argc, const char **argv)
2540 {
2541 	char **__argv = malloc(sizeof(const char *) * argc);
2542 
2543 	if (!__argv) {
2544 		pr_err("malloc failed\n");
2545 		return -1;
2546 	}
2547 
2548 	memcpy(__argv, argv, sizeof(const char *) * argc);
2549 	argc = parse_options(argc, (const char **)__argv, record_options,
2550 			     NULL, PARSE_OPT_STOP_AT_NON_OPTION);
2551 	free(__argv);
2552 
2553 	system_wide = (argc == 0);
2554 
2555 	return 0;
2556 }
2557 
script__setup_sample_type(struct perf_script * script)2558 static void script__setup_sample_type(struct perf_script *script)
2559 {
2560 	struct perf_session *session = script->session;
2561 	u64 sample_type = perf_evlist__combined_sample_type(session->evlist);
2562 
2563 	if (symbol_conf.use_callchain || symbol_conf.cumulate_callchain) {
2564 		if ((sample_type & PERF_SAMPLE_REGS_USER) &&
2565 		    (sample_type & PERF_SAMPLE_STACK_USER)) {
2566 			callchain_param.record_mode = CALLCHAIN_DWARF;
2567 			dwarf_callchain_users = true;
2568 		} else if (sample_type & PERF_SAMPLE_BRANCH_STACK)
2569 			callchain_param.record_mode = CALLCHAIN_LBR;
2570 		else
2571 			callchain_param.record_mode = CALLCHAIN_FP;
2572 	}
2573 }
2574 
process_stat_round_event(struct perf_tool * tool __maybe_unused,union perf_event * event,struct perf_session * session)2575 static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
2576 				    union perf_event *event,
2577 				    struct perf_session *session)
2578 {
2579 	struct stat_round_event *round = &event->stat_round;
2580 	struct perf_evsel *counter;
2581 
2582 	evlist__for_each_entry(session->evlist, counter) {
2583 		perf_stat_process_counter(&stat_config, counter);
2584 		process_stat(counter, round->time);
2585 	}
2586 
2587 	process_stat_interval(round->time);
2588 	return 0;
2589 }
2590 
process_stat_config_event(struct perf_tool * tool __maybe_unused,union perf_event * event,struct perf_session * session __maybe_unused)2591 static int process_stat_config_event(struct perf_tool *tool __maybe_unused,
2592 				     union perf_event *event,
2593 				     struct perf_session *session __maybe_unused)
2594 {
2595 	perf_event__read_stat_config(&stat_config, &event->stat_config);
2596 	return 0;
2597 }
2598 
set_maps(struct perf_script * script)2599 static int set_maps(struct perf_script *script)
2600 {
2601 	struct perf_evlist *evlist = script->session->evlist;
2602 
2603 	if (!script->cpus || !script->threads)
2604 		return 0;
2605 
2606 	if (WARN_ONCE(script->allocated, "stats double allocation\n"))
2607 		return -EINVAL;
2608 
2609 	perf_evlist__set_maps(evlist, script->cpus, script->threads);
2610 
2611 	if (perf_evlist__alloc_stats(evlist, true))
2612 		return -ENOMEM;
2613 
2614 	script->allocated = true;
2615 	return 0;
2616 }
2617 
2618 static
process_thread_map_event(struct perf_tool * tool,union perf_event * event,struct perf_session * session __maybe_unused)2619 int process_thread_map_event(struct perf_tool *tool,
2620 			     union perf_event *event,
2621 			     struct perf_session *session __maybe_unused)
2622 {
2623 	struct perf_script *script = container_of(tool, struct perf_script, tool);
2624 
2625 	if (script->threads) {
2626 		pr_warning("Extra thread map event, ignoring.\n");
2627 		return 0;
2628 	}
2629 
2630 	script->threads = thread_map__new_event(&event->thread_map);
2631 	if (!script->threads)
2632 		return -ENOMEM;
2633 
2634 	return set_maps(script);
2635 }
2636 
2637 static
process_cpu_map_event(struct perf_tool * tool __maybe_unused,union perf_event * event,struct perf_session * session __maybe_unused)2638 int process_cpu_map_event(struct perf_tool *tool __maybe_unused,
2639 			  union perf_event *event,
2640 			  struct perf_session *session __maybe_unused)
2641 {
2642 	struct perf_script *script = container_of(tool, struct perf_script, tool);
2643 
2644 	if (script->cpus) {
2645 		pr_warning("Extra cpu map event, ignoring.\n");
2646 		return 0;
2647 	}
2648 
2649 	script->cpus = cpu_map__new_data(&event->cpu_map.data);
2650 	if (!script->cpus)
2651 		return -ENOMEM;
2652 
2653 	return set_maps(script);
2654 }
2655 
cmd_script(int argc,const char ** argv)2656 int cmd_script(int argc, const char **argv)
2657 {
2658 	bool show_full_info = false;
2659 	bool header = false;
2660 	bool header_only = false;
2661 	bool script_started = false;
2662 	char *rec_script_path = NULL;
2663 	char *rep_script_path = NULL;
2664 	struct perf_session *session;
2665 	struct itrace_synth_opts itrace_synth_opts = { .set = false, };
2666 	char *script_path = NULL;
2667 	const char **__argv;
2668 	int i, j, err = 0;
2669 	struct perf_script script = {
2670 		.tool = {
2671 			.sample		 = process_sample_event,
2672 			.mmap		 = perf_event__process_mmap,
2673 			.mmap2		 = perf_event__process_mmap2,
2674 			.comm		 = perf_event__process_comm,
2675 			.namespaces	 = perf_event__process_namespaces,
2676 			.exit		 = perf_event__process_exit,
2677 			.fork		 = perf_event__process_fork,
2678 			.attr		 = process_attr,
2679 			.event_update   = perf_event__process_event_update,
2680 			.tracing_data	 = perf_event__process_tracing_data,
2681 			.feature	 = perf_event__process_feature,
2682 			.build_id	 = perf_event__process_build_id,
2683 			.id_index	 = perf_event__process_id_index,
2684 			.auxtrace_info	 = perf_event__process_auxtrace_info,
2685 			.auxtrace	 = perf_event__process_auxtrace,
2686 			.auxtrace_error	 = perf_event__process_auxtrace_error,
2687 			.stat		 = perf_event__process_stat_event,
2688 			.stat_round	 = process_stat_round_event,
2689 			.stat_config	 = process_stat_config_event,
2690 			.thread_map	 = process_thread_map_event,
2691 			.cpu_map	 = process_cpu_map_event,
2692 			.ordered_events	 = true,
2693 			.ordering_requires_timestamps = true,
2694 		},
2695 	};
2696 	struct perf_data_file file = {
2697 		.mode = PERF_DATA_MODE_READ,
2698 	};
2699 	const struct option options[] = {
2700 	OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
2701 		    "dump raw trace in ASCII"),
2702 	OPT_INCR('v', "verbose", &verbose,
2703 		 "be more verbose (show symbol address, etc)"),
2704 	OPT_BOOLEAN('L', "Latency", &latency_format,
2705 		    "show latency attributes (irqs/preemption disabled, etc)"),
2706 	OPT_CALLBACK_NOOPT('l', "list", NULL, NULL, "list available scripts",
2707 			   list_available_scripts),
2708 	OPT_CALLBACK('s', "script", NULL, "name",
2709 		     "script file name (lang:script name, script name, or *)",
2710 		     parse_scriptname),
2711 	OPT_STRING('g', "gen-script", &generate_script_lang, "lang",
2712 		   "generate perf-script.xx script in specified language"),
2713 	OPT_STRING('i', "input", &input_name, "file", "input file name"),
2714 	OPT_BOOLEAN('d', "debug-mode", &debug_mode,
2715 		   "do various checks like samples ordering and lost events"),
2716 	OPT_BOOLEAN(0, "header", &header, "Show data header."),
2717 	OPT_BOOLEAN(0, "header-only", &header_only, "Show only data header."),
2718 	OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
2719 		   "file", "vmlinux pathname"),
2720 	OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
2721 		   "file", "kallsyms pathname"),
2722 	OPT_BOOLEAN('G', "hide-call-graph", &no_callchain,
2723 		    "When printing symbols do not display call chain"),
2724 	OPT_CALLBACK(0, "symfs", NULL, "directory",
2725 		     "Look for files with symbols relative to this directory",
2726 		     symbol__config_symfs),
2727 	OPT_CALLBACK('F', "fields", NULL, "str",
2728 		     "comma separated output fields prepend with 'type:'. "
2729 		     "+field to add and -field to remove."
2730 		     "Valid types: hw,sw,trace,raw,synth. "
2731 		     "Fields: comm,tid,pid,time,cpu,event,trace,ip,sym,dso,"
2732 		     "addr,symoff,period,iregs,brstack,brstacksym,flags,"
2733 		     "bpf-output,callindent,insn,insnlen,brstackinsn,synth,phys_addr",
2734 		     parse_output_fields),
2735 	OPT_BOOLEAN('a', "all-cpus", &system_wide,
2736 		    "system-wide collection from all CPUs"),
2737 	OPT_STRING('S', "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
2738 		   "only consider these symbols"),
2739 	OPT_STRING(0, "stop-bt", &symbol_conf.bt_stop_list_str, "symbol[,symbol...]",
2740 		   "Stop display of callgraph at these symbols"),
2741 	OPT_STRING('C', "cpu", &cpu_list, "cpu", "list of cpus to profile"),
2742 	OPT_STRING('c', "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
2743 		   "only display events for these comms"),
2744 	OPT_STRING(0, "pid", &symbol_conf.pid_list_str, "pid[,pid...]",
2745 		   "only consider symbols in these pids"),
2746 	OPT_STRING(0, "tid", &symbol_conf.tid_list_str, "tid[,tid...]",
2747 		   "only consider symbols in these tids"),
2748 	OPT_UINTEGER(0, "max-stack", &scripting_max_stack,
2749 		     "Set the maximum stack depth when parsing the callchain, "
2750 		     "anything beyond the specified depth will be ignored. "
2751 		     "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
2752 	OPT_BOOLEAN('I', "show-info", &show_full_info,
2753 		    "display extended information from perf.data file"),
2754 	OPT_BOOLEAN('\0', "show-kernel-path", &symbol_conf.show_kernel_path,
2755 		    "Show the path of [kernel.kallsyms]"),
2756 	OPT_BOOLEAN('\0', "show-task-events", &script.show_task_events,
2757 		    "Show the fork/comm/exit events"),
2758 	OPT_BOOLEAN('\0', "show-mmap-events", &script.show_mmap_events,
2759 		    "Show the mmap events"),
2760 	OPT_BOOLEAN('\0', "show-switch-events", &script.show_switch_events,
2761 		    "Show context switch events (if recorded)"),
2762 	OPT_BOOLEAN('\0', "show-namespace-events", &script.show_namespace_events,
2763 		    "Show namespace events (if recorded)"),
2764 	OPT_BOOLEAN('f', "force", &symbol_conf.force, "don't complain, do it"),
2765 	OPT_INTEGER(0, "max-blocks", &max_blocks,
2766 		    "Maximum number of code blocks to dump with brstackinsn"),
2767 	OPT_BOOLEAN(0, "ns", &nanosecs,
2768 		    "Use 9 decimal places when displaying time"),
2769 	OPT_CALLBACK_OPTARG(0, "itrace", &itrace_synth_opts, NULL, "opts",
2770 			    "Instruction Tracing options",
2771 			    itrace_parse_synth_opts),
2772 	OPT_BOOLEAN(0, "full-source-path", &srcline_full_filename,
2773 			"Show full source file name path for source lines"),
2774 	OPT_BOOLEAN(0, "demangle", &symbol_conf.demangle,
2775 			"Enable symbol demangling"),
2776 	OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel,
2777 			"Enable kernel symbol demangling"),
2778 	OPT_STRING(0, "time", &script.time_str, "str",
2779 		   "Time span of interest (start,stop)"),
2780 	OPT_BOOLEAN(0, "inline", &symbol_conf.inline_name,
2781 		    "Show inline function"),
2782 	OPT_END()
2783 	};
2784 	const char * const script_subcommands[] = { "record", "report", NULL };
2785 	const char *script_usage[] = {
2786 		"perf script [<options>]",
2787 		"perf script [<options>] record <script> [<record-options>] <command>",
2788 		"perf script [<options>] report <script> [script-args]",
2789 		"perf script [<options>] <script> [<record-options>] <command>",
2790 		"perf script [<options>] <top-script> [script-args]",
2791 		NULL
2792 	};
2793 
2794 	setup_scripting();
2795 
2796 	argc = parse_options_subcommand(argc, argv, options, script_subcommands, script_usage,
2797 			     PARSE_OPT_STOP_AT_NON_OPTION);
2798 
2799 	file.path = input_name;
2800 	file.force = symbol_conf.force;
2801 
2802 	if (argc > 1 && !strncmp(argv[0], "rec", strlen("rec"))) {
2803 		rec_script_path = get_script_path(argv[1], RECORD_SUFFIX);
2804 		if (!rec_script_path)
2805 			return cmd_record(argc, argv);
2806 	}
2807 
2808 	if (argc > 1 && !strncmp(argv[0], "rep", strlen("rep"))) {
2809 		rep_script_path = get_script_path(argv[1], REPORT_SUFFIX);
2810 		if (!rep_script_path) {
2811 			fprintf(stderr,
2812 				"Please specify a valid report script"
2813 				"(see 'perf script -l' for listing)\n");
2814 			return -1;
2815 		}
2816 	}
2817 
2818 	if (itrace_synth_opts.callchain &&
2819 	    itrace_synth_opts.callchain_sz > scripting_max_stack)
2820 		scripting_max_stack = itrace_synth_opts.callchain_sz;
2821 
2822 	/* make sure PERF_EXEC_PATH is set for scripts */
2823 	set_argv_exec_path(get_argv_exec_path());
2824 
2825 	if (argc && !script_name && !rec_script_path && !rep_script_path) {
2826 		int live_pipe[2];
2827 		int rep_args;
2828 		pid_t pid;
2829 
2830 		rec_script_path = get_script_path(argv[0], RECORD_SUFFIX);
2831 		rep_script_path = get_script_path(argv[0], REPORT_SUFFIX);
2832 
2833 		if (!rec_script_path && !rep_script_path) {
2834 			usage_with_options_msg(script_usage, options,
2835 				"Couldn't find script `%s'\n\n See perf"
2836 				" script -l for available scripts.\n", argv[0]);
2837 		}
2838 
2839 		if (is_top_script(argv[0])) {
2840 			rep_args = argc - 1;
2841 		} else {
2842 			int rec_args;
2843 
2844 			rep_args = has_required_arg(rep_script_path);
2845 			rec_args = (argc - 1) - rep_args;
2846 			if (rec_args < 0) {
2847 				usage_with_options_msg(script_usage, options,
2848 					"`%s' script requires options."
2849 					"\n\n See perf script -l for available "
2850 					"scripts and options.\n", argv[0]);
2851 			}
2852 		}
2853 
2854 		if (pipe(live_pipe) < 0) {
2855 			perror("failed to create pipe");
2856 			return -1;
2857 		}
2858 
2859 		pid = fork();
2860 		if (pid < 0) {
2861 			perror("failed to fork");
2862 			return -1;
2863 		}
2864 
2865 		if (!pid) {
2866 			j = 0;
2867 
2868 			dup2(live_pipe[1], 1);
2869 			close(live_pipe[0]);
2870 
2871 			if (is_top_script(argv[0])) {
2872 				system_wide = true;
2873 			} else if (!system_wide) {
2874 				if (have_cmd(argc - rep_args, &argv[rep_args]) != 0) {
2875 					err = -1;
2876 					goto out;
2877 				}
2878 			}
2879 
2880 			__argv = malloc((argc + 6) * sizeof(const char *));
2881 			if (!__argv) {
2882 				pr_err("malloc failed\n");
2883 				err = -ENOMEM;
2884 				goto out;
2885 			}
2886 
2887 			__argv[j++] = "/bin/sh";
2888 			__argv[j++] = rec_script_path;
2889 			if (system_wide)
2890 				__argv[j++] = "-a";
2891 			__argv[j++] = "-q";
2892 			__argv[j++] = "-o";
2893 			__argv[j++] = "-";
2894 			for (i = rep_args + 1; i < argc; i++)
2895 				__argv[j++] = argv[i];
2896 			__argv[j++] = NULL;
2897 
2898 			execvp("/bin/sh", (char **)__argv);
2899 			free(__argv);
2900 			exit(-1);
2901 		}
2902 
2903 		dup2(live_pipe[0], 0);
2904 		close(live_pipe[1]);
2905 
2906 		__argv = malloc((argc + 4) * sizeof(const char *));
2907 		if (!__argv) {
2908 			pr_err("malloc failed\n");
2909 			err = -ENOMEM;
2910 			goto out;
2911 		}
2912 
2913 		j = 0;
2914 		__argv[j++] = "/bin/sh";
2915 		__argv[j++] = rep_script_path;
2916 		for (i = 1; i < rep_args + 1; i++)
2917 			__argv[j++] = argv[i];
2918 		__argv[j++] = "-i";
2919 		__argv[j++] = "-";
2920 		__argv[j++] = NULL;
2921 
2922 		execvp("/bin/sh", (char **)__argv);
2923 		free(__argv);
2924 		exit(-1);
2925 	}
2926 
2927 	if (rec_script_path)
2928 		script_path = rec_script_path;
2929 	if (rep_script_path)
2930 		script_path = rep_script_path;
2931 
2932 	if (script_path) {
2933 		j = 0;
2934 
2935 		if (!rec_script_path)
2936 			system_wide = false;
2937 		else if (!system_wide) {
2938 			if (have_cmd(argc - 1, &argv[1]) != 0) {
2939 				err = -1;
2940 				goto out;
2941 			}
2942 		}
2943 
2944 		__argv = malloc((argc + 2) * sizeof(const char *));
2945 		if (!__argv) {
2946 			pr_err("malloc failed\n");
2947 			err = -ENOMEM;
2948 			goto out;
2949 		}
2950 
2951 		__argv[j++] = "/bin/sh";
2952 		__argv[j++] = script_path;
2953 		if (system_wide)
2954 			__argv[j++] = "-a";
2955 		for (i = 2; i < argc; i++)
2956 			__argv[j++] = argv[i];
2957 		__argv[j++] = NULL;
2958 
2959 		execvp("/bin/sh", (char **)__argv);
2960 		free(__argv);
2961 		exit(-1);
2962 	}
2963 
2964 	if (!script_name)
2965 		setup_pager();
2966 
2967 	session = perf_session__new(&file, false, &script.tool);
2968 	if (session == NULL)
2969 		return -1;
2970 
2971 	if (header || header_only) {
2972 		script.tool.show_feat_hdr = SHOW_FEAT_HEADER;
2973 		perf_session__fprintf_info(session, stdout, show_full_info);
2974 		if (header_only)
2975 			goto out_delete;
2976 	}
2977 	if (show_full_info)
2978 		script.tool.show_feat_hdr = SHOW_FEAT_HEADER_FULL_INFO;
2979 
2980 	if (symbol__init(&session->header.env) < 0)
2981 		goto out_delete;
2982 
2983 	script.session = session;
2984 	script__setup_sample_type(&script);
2985 
2986 	if (output[PERF_TYPE_HARDWARE].fields & PERF_OUTPUT_CALLINDENT)
2987 		itrace_synth_opts.thread_stack = true;
2988 
2989 	session->itrace_synth_opts = &itrace_synth_opts;
2990 
2991 	if (cpu_list) {
2992 		err = perf_session__cpu_bitmap(session, cpu_list, cpu_bitmap);
2993 		if (err < 0)
2994 			goto out_delete;
2995 		itrace_synth_opts.cpu_bitmap = cpu_bitmap;
2996 	}
2997 
2998 	if (!no_callchain)
2999 		symbol_conf.use_callchain = true;
3000 	else
3001 		symbol_conf.use_callchain = false;
3002 
3003 	if (session->tevent.pevent &&
3004 	    pevent_set_function_resolver(session->tevent.pevent,
3005 					 machine__resolve_kernel_addr,
3006 					 &session->machines.host) < 0) {
3007 		pr_err("%s: failed to set libtraceevent function resolver\n", __func__);
3008 		return -1;
3009 	}
3010 
3011 	if (generate_script_lang) {
3012 		struct stat perf_stat;
3013 		int input;
3014 
3015 		if (output_set_by_user()) {
3016 			fprintf(stderr,
3017 				"custom fields not supported for generated scripts");
3018 			err = -EINVAL;
3019 			goto out_delete;
3020 		}
3021 
3022 		input = open(file.path, O_RDONLY);	/* input_name */
3023 		if (input < 0) {
3024 			err = -errno;
3025 			perror("failed to open file");
3026 			goto out_delete;
3027 		}
3028 
3029 		err = fstat(input, &perf_stat);
3030 		if (err < 0) {
3031 			perror("failed to stat file");
3032 			goto out_delete;
3033 		}
3034 
3035 		if (!perf_stat.st_size) {
3036 			fprintf(stderr, "zero-sized file, nothing to do!\n");
3037 			goto out_delete;
3038 		}
3039 
3040 		scripting_ops = script_spec__lookup(generate_script_lang);
3041 		if (!scripting_ops) {
3042 			fprintf(stderr, "invalid language specifier");
3043 			err = -ENOENT;
3044 			goto out_delete;
3045 		}
3046 
3047 		err = scripting_ops->generate_script(session->tevent.pevent,
3048 						     "perf-script");
3049 		goto out_delete;
3050 	}
3051 
3052 	if (script_name) {
3053 		err = scripting_ops->start_script(script_name, argc, argv);
3054 		if (err)
3055 			goto out_delete;
3056 		pr_debug("perf script started with script %s\n\n", script_name);
3057 		script_started = true;
3058 	}
3059 
3060 
3061 	err = perf_session__check_output_opt(session);
3062 	if (err < 0)
3063 		goto out_delete;
3064 
3065 	/* needs to be parsed after looking up reference time */
3066 	if (perf_time__parse_str(&script.ptime, script.time_str) != 0) {
3067 		pr_err("Invalid time string\n");
3068 		return -EINVAL;
3069 	}
3070 
3071 	err = __cmd_script(&script);
3072 
3073 	flush_scripting();
3074 
3075 out_delete:
3076 	perf_evlist__free_stats(session->evlist);
3077 	perf_session__delete(session);
3078 
3079 	if (script_started)
3080 		cleanup_scripting();
3081 out:
3082 	return err;
3083 }
3084