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