1 // SPDX-License-Identifier: GPL-2.0
5 #include "util/cache.h"
6 #include "util/debug.h"
7 #include <subcmd/exec-cmd.h>
8 #include "util/header.h"
9 #include <subcmd/parse-options.h>
10 #include "util/perf_regs.h"
11 #include "util/session.h"
12 #include "util/tool.h"
13 #include "util/symbol.h"
14 #include "util/thread.h"
15 #include "util/trace-event.h"
16 #include "util/util.h"
17 #include "util/evlist.h"
18 #include "util/evsel.h"
19 #include "util/sort.h"
20 #include "util/data.h"
21 #include "util/auxtrace.h"
22 #include "util/cpumap.h"
23 #include "util/thread_map.h"
24 #include "util/stat.h"
25 #include "util/string2.h"
26 #include "util/thread-stack.h"
27 #include "util/time-utils.h"
28 #include "print_binary.h"
29 #include <linux/bitmap.h>
30 #include <linux/kernel.h>
31 #include <linux/stringify.h>
32 #include <linux/time64.h>
34 #include "util/mem-events.h"
35 #include "util/dump-insn.h"
40 #include <sys/param.h>
41 #include <sys/types.h>
45 #include "sane_ctype.h"
47 static char const *script_name;
48 static char const *generate_script_lang;
49 static bool debug_mode;
50 static u64 last_timestamp;
51 static u64 nr_unordered;
52 static bool no_callchain;
53 static bool latency_format;
54 static bool system_wide;
55 static bool print_flags;
57 static const char *cpu_list;
58 static DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
59 static struct perf_stat_config stat_config;
60 static int max_blocks;
62 unsigned int scripting_max_stack = PERF_MAX_STACK_DEPTH;
64 enum perf_output_field {
65 PERF_OUTPUT_COMM = 1U << 0,
66 PERF_OUTPUT_TID = 1U << 1,
67 PERF_OUTPUT_PID = 1U << 2,
68 PERF_OUTPUT_TIME = 1U << 3,
69 PERF_OUTPUT_CPU = 1U << 4,
70 PERF_OUTPUT_EVNAME = 1U << 5,
71 PERF_OUTPUT_TRACE = 1U << 6,
72 PERF_OUTPUT_IP = 1U << 7,
73 PERF_OUTPUT_SYM = 1U << 8,
74 PERF_OUTPUT_DSO = 1U << 9,
75 PERF_OUTPUT_ADDR = 1U << 10,
76 PERF_OUTPUT_SYMOFFSET = 1U << 11,
77 PERF_OUTPUT_SRCLINE = 1U << 12,
78 PERF_OUTPUT_PERIOD = 1U << 13,
79 PERF_OUTPUT_IREGS = 1U << 14,
80 PERF_OUTPUT_BRSTACK = 1U << 15,
81 PERF_OUTPUT_BRSTACKSYM = 1U << 16,
82 PERF_OUTPUT_DATA_SRC = 1U << 17,
83 PERF_OUTPUT_WEIGHT = 1U << 18,
84 PERF_OUTPUT_BPF_OUTPUT = 1U << 19,
85 PERF_OUTPUT_CALLINDENT = 1U << 20,
86 PERF_OUTPUT_INSN = 1U << 21,
87 PERF_OUTPUT_INSNLEN = 1U << 22,
88 PERF_OUTPUT_BRSTACKINSN = 1U << 23,
89 PERF_OUTPUT_BRSTACKOFF = 1U << 24,
90 PERF_OUTPUT_SYNTH = 1U << 25,
91 PERF_OUTPUT_PHYS_ADDR = 1U << 26,
92 PERF_OUTPUT_UREGS = 1U << 27,
95 struct output_option {
97 enum perf_output_field field;
98 } all_output_options[] = {
99 {.str = "comm", .field = PERF_OUTPUT_COMM},
100 {.str = "tid", .field = PERF_OUTPUT_TID},
101 {.str = "pid", .field = PERF_OUTPUT_PID},
102 {.str = "time", .field = PERF_OUTPUT_TIME},
103 {.str = "cpu", .field = PERF_OUTPUT_CPU},
104 {.str = "event", .field = PERF_OUTPUT_EVNAME},
105 {.str = "trace", .field = PERF_OUTPUT_TRACE},
106 {.str = "ip", .field = PERF_OUTPUT_IP},
107 {.str = "sym", .field = PERF_OUTPUT_SYM},
108 {.str = "dso", .field = PERF_OUTPUT_DSO},
109 {.str = "addr", .field = PERF_OUTPUT_ADDR},
110 {.str = "symoff", .field = PERF_OUTPUT_SYMOFFSET},
111 {.str = "srcline", .field = PERF_OUTPUT_SRCLINE},
112 {.str = "period", .field = PERF_OUTPUT_PERIOD},
113 {.str = "iregs", .field = PERF_OUTPUT_IREGS},
114 {.str = "uregs", .field = PERF_OUTPUT_UREGS},
115 {.str = "brstack", .field = PERF_OUTPUT_BRSTACK},
116 {.str = "brstacksym", .field = PERF_OUTPUT_BRSTACKSYM},
117 {.str = "data_src", .field = PERF_OUTPUT_DATA_SRC},
118 {.str = "weight", .field = PERF_OUTPUT_WEIGHT},
119 {.str = "bpf-output", .field = PERF_OUTPUT_BPF_OUTPUT},
120 {.str = "callindent", .field = PERF_OUTPUT_CALLINDENT},
121 {.str = "insn", .field = PERF_OUTPUT_INSN},
122 {.str = "insnlen", .field = PERF_OUTPUT_INSNLEN},
123 {.str = "brstackinsn", .field = PERF_OUTPUT_BRSTACKINSN},
124 {.str = "brstackoff", .field = PERF_OUTPUT_BRSTACKOFF},
125 {.str = "synth", .field = PERF_OUTPUT_SYNTH},
126 {.str = "phys_addr", .field = PERF_OUTPUT_PHYS_ADDR},
130 OUTPUT_TYPE_SYNTH = PERF_TYPE_MAX,
134 /* default set to maintain compatibility with current format */
138 unsigned int print_ip_opts;
141 } output[OUTPUT_TYPE_MAX] = {
143 [PERF_TYPE_HARDWARE] = {
146 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
147 PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
148 PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
149 PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
152 .invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
155 [PERF_TYPE_SOFTWARE] = {
158 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
159 PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
160 PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
161 PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
162 PERF_OUTPUT_PERIOD | PERF_OUTPUT_BPF_OUTPUT,
164 .invalid_fields = PERF_OUTPUT_TRACE,
167 [PERF_TYPE_TRACEPOINT] = {
170 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
171 PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
172 PERF_OUTPUT_EVNAME | PERF_OUTPUT_TRACE
178 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
179 PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
180 PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
181 PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
182 PERF_OUTPUT_PERIOD | PERF_OUTPUT_ADDR |
183 PERF_OUTPUT_DATA_SRC | PERF_OUTPUT_WEIGHT |
184 PERF_OUTPUT_PHYS_ADDR,
186 .invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
189 [PERF_TYPE_BREAKPOINT] = {
192 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
193 PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
194 PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
195 PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
198 .invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
201 [OUTPUT_TYPE_SYNTH] = {
204 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
205 PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
206 PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
207 PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
210 .invalid_fields = PERF_OUTPUT_TRACE | PERF_OUTPUT_BPF_OUTPUT,
214 struct perf_evsel_script {
220 static struct perf_evsel_script *perf_evsel_script__new(struct perf_evsel *evsel,
221 struct perf_data *data)
223 struct perf_evsel_script *es = malloc(sizeof(*es));
226 if (asprintf(&es->filename, "%s.%s.dump", data->file.path, perf_evsel__name(evsel)) < 0)
228 es->fp = fopen(es->filename, "w");
230 goto out_free_filename;
236 zfree(&es->filename);
242 static void perf_evsel_script__delete(struct perf_evsel_script *es)
244 zfree(&es->filename);
250 static int perf_evsel_script__fprintf(struct perf_evsel_script *es, FILE *fp)
254 fstat(fileno(es->fp), &st);
255 return fprintf(fp, "[ perf script: Wrote %.3f MB %s (%" PRIu64 " samples) ]\n",
256 st.st_size / 1024.0 / 1024.0, es->filename, es->samples);
259 static inline int output_type(unsigned int type)
262 case PERF_TYPE_SYNTH:
263 return OUTPUT_TYPE_SYNTH;
269 static inline unsigned int attr_type(unsigned int type)
272 case OUTPUT_TYPE_SYNTH:
273 return PERF_TYPE_SYNTH;
279 static bool output_set_by_user(void)
282 for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
283 if (output[j].user_set)
289 static const char *output_field2str(enum perf_output_field field)
291 int i, imax = ARRAY_SIZE(all_output_options);
292 const char *str = "";
294 for (i = 0; i < imax; ++i) {
295 if (all_output_options[i].field == field) {
296 str = all_output_options[i].str;
303 #define PRINT_FIELD(x) (output[output_type(attr->type)].fields & PERF_OUTPUT_##x)
305 static int perf_evsel__do_check_stype(struct perf_evsel *evsel,
306 u64 sample_type, const char *sample_msg,
307 enum perf_output_field field,
310 struct perf_event_attr *attr = &evsel->attr;
311 int type = output_type(attr->type);
314 if (attr->sample_type & sample_type)
317 if (output[type].user_set) {
320 evname = perf_evsel__name(evsel);
321 pr_err("Samples for '%s' event do not have %s attribute set. "
322 "Cannot print '%s' field.\n",
323 evname, sample_msg, output_field2str(field));
327 /* user did not ask for it explicitly so remove from the default list */
328 output[type].fields &= ~field;
329 evname = perf_evsel__name(evsel);
330 pr_debug("Samples for '%s' event do not have %s attribute set. "
331 "Skipping '%s' field.\n",
332 evname, sample_msg, output_field2str(field));
337 static int perf_evsel__check_stype(struct perf_evsel *evsel,
338 u64 sample_type, const char *sample_msg,
339 enum perf_output_field field)
341 return perf_evsel__do_check_stype(evsel, sample_type, sample_msg, field,
345 static int perf_evsel__check_attr(struct perf_evsel *evsel,
346 struct perf_session *session)
348 struct perf_event_attr *attr = &evsel->attr;
351 if (perf_header__has_feat(&session->header, HEADER_STAT))
354 allow_user_set = perf_header__has_feat(&session->header,
357 if (PRINT_FIELD(TRACE) &&
358 !perf_session__has_traces(session, "record -R"))
361 if (PRINT_FIELD(IP)) {
362 if (perf_evsel__check_stype(evsel, PERF_SAMPLE_IP, "IP",
367 if (PRINT_FIELD(ADDR) &&
368 perf_evsel__do_check_stype(evsel, PERF_SAMPLE_ADDR, "ADDR",
369 PERF_OUTPUT_ADDR, allow_user_set))
372 if (PRINT_FIELD(DATA_SRC) &&
373 perf_evsel__check_stype(evsel, PERF_SAMPLE_DATA_SRC, "DATA_SRC",
374 PERF_OUTPUT_DATA_SRC))
377 if (PRINT_FIELD(WEIGHT) &&
378 perf_evsel__check_stype(evsel, PERF_SAMPLE_WEIGHT, "WEIGHT",
382 if (PRINT_FIELD(SYM) && !PRINT_FIELD(IP) && !PRINT_FIELD(ADDR)) {
383 pr_err("Display of symbols requested but neither sample IP nor "
384 "sample address\nis selected. Hence, no addresses to convert "
388 if (PRINT_FIELD(SYMOFFSET) && !PRINT_FIELD(SYM)) {
389 pr_err("Display of offsets requested but symbol is not"
393 if (PRINT_FIELD(DSO) && !PRINT_FIELD(IP) && !PRINT_FIELD(ADDR) &&
394 !PRINT_FIELD(BRSTACK) && !PRINT_FIELD(BRSTACKSYM) && !PRINT_FIELD(BRSTACKOFF)) {
395 pr_err("Display of DSO requested but no address to convert. Select\n"
396 "sample IP, sample address, brstack, brstacksym, or brstackoff.\n");
399 if (PRINT_FIELD(SRCLINE) && !PRINT_FIELD(IP)) {
400 pr_err("Display of source line number requested but sample IP is not\n"
401 "selected. Hence, no address to lookup the source line number.\n");
404 if (PRINT_FIELD(BRSTACKINSN) &&
405 !(perf_evlist__combined_branch_type(session->evlist) &
406 PERF_SAMPLE_BRANCH_ANY)) {
407 pr_err("Display of branch stack assembler requested, but non all-branch filter set\n"
408 "Hint: run 'perf record -b ...'\n");
411 if ((PRINT_FIELD(PID) || PRINT_FIELD(TID)) &&
412 perf_evsel__check_stype(evsel, PERF_SAMPLE_TID, "TID",
413 PERF_OUTPUT_TID|PERF_OUTPUT_PID))
416 if (PRINT_FIELD(TIME) &&
417 perf_evsel__check_stype(evsel, PERF_SAMPLE_TIME, "TIME",
421 if (PRINT_FIELD(CPU) &&
422 perf_evsel__do_check_stype(evsel, PERF_SAMPLE_CPU, "CPU",
423 PERF_OUTPUT_CPU, allow_user_set))
426 if (PRINT_FIELD(PERIOD) &&
427 perf_evsel__check_stype(evsel, PERF_SAMPLE_PERIOD, "PERIOD",
431 if (PRINT_FIELD(IREGS) &&
432 perf_evsel__check_stype(evsel, PERF_SAMPLE_REGS_INTR, "IREGS",
436 if (PRINT_FIELD(UREGS) &&
437 perf_evsel__check_stype(evsel, PERF_SAMPLE_REGS_USER, "UREGS",
441 if (PRINT_FIELD(PHYS_ADDR) &&
442 perf_evsel__check_stype(evsel, PERF_SAMPLE_PHYS_ADDR, "PHYS_ADDR",
443 PERF_OUTPUT_PHYS_ADDR))
449 static void set_print_ip_opts(struct perf_event_attr *attr)
451 unsigned int type = output_type(attr->type);
453 output[type].print_ip_opts = 0;
455 output[type].print_ip_opts |= EVSEL__PRINT_IP;
457 if (PRINT_FIELD(SYM))
458 output[type].print_ip_opts |= EVSEL__PRINT_SYM;
460 if (PRINT_FIELD(DSO))
461 output[type].print_ip_opts |= EVSEL__PRINT_DSO;
463 if (PRINT_FIELD(SYMOFFSET))
464 output[type].print_ip_opts |= EVSEL__PRINT_SYMOFFSET;
466 if (PRINT_FIELD(SRCLINE))
467 output[type].print_ip_opts |= EVSEL__PRINT_SRCLINE;
471 * verify all user requested events exist and the samples
472 * have the expected data
474 static int perf_session__check_output_opt(struct perf_session *session)
477 struct perf_evsel *evsel;
479 for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
480 evsel = perf_session__find_first_evtype(session, attr_type(j));
483 * even if fields is set to 0 (ie., show nothing) event must
484 * exist if user explicitly includes it on the command line
486 if (!evsel && output[j].user_set && !output[j].wildcard_set &&
487 j != OUTPUT_TYPE_SYNTH) {
488 pr_err("%s events do not exist. "
489 "Remove corresponding -F option to proceed.\n",
494 if (evsel && output[j].fields &&
495 perf_evsel__check_attr(evsel, session))
501 set_print_ip_opts(&evsel->attr);
505 bool use_callchain = false;
506 bool not_pipe = false;
508 evlist__for_each_entry(session->evlist, evsel) {
510 if (evsel->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
511 use_callchain = true;
515 if (not_pipe && !use_callchain)
516 symbol_conf.use_callchain = false;
520 * set default for tracepoints to print symbols only
521 * if callchains are present
523 if (symbol_conf.use_callchain &&
524 !output[PERF_TYPE_TRACEPOINT].user_set) {
525 struct perf_event_attr *attr;
527 j = PERF_TYPE_TRACEPOINT;
529 evlist__for_each_entry(session->evlist, evsel) {
530 if (evsel->attr.type != j)
535 if (attr->sample_type & PERF_SAMPLE_CALLCHAIN) {
536 output[j].fields |= PERF_OUTPUT_IP;
537 output[j].fields |= PERF_OUTPUT_SYM;
538 output[j].fields |= PERF_OUTPUT_DSO;
539 set_print_ip_opts(attr);
549 static int perf_sample__fprintf_iregs(struct perf_sample *sample,
550 struct perf_event_attr *attr, FILE *fp)
552 struct regs_dump *regs = &sample->intr_regs;
553 uint64_t mask = attr->sample_regs_intr;
560 for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
561 u64 val = regs->regs[i++];
562 printed += fprintf(fp, "%5s:0x%"PRIx64" ", perf_reg_name(r), val);
568 static int perf_sample__fprintf_uregs(struct perf_sample *sample,
569 struct perf_event_attr *attr, FILE *fp)
571 struct regs_dump *regs = &sample->user_regs;
572 uint64_t mask = attr->sample_regs_user;
576 if (!regs || !regs->regs)
579 printed += fprintf(fp, " ABI:%" PRIu64 " ", regs->abi);
581 for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
582 u64 val = regs->regs[i++];
583 printed += fprintf(fp, "%5s:0x%"PRIx64" ", perf_reg_name(r), val);
589 static int perf_sample__fprintf_start(struct perf_sample *sample,
590 struct thread *thread,
591 struct perf_evsel *evsel, FILE *fp)
593 struct perf_event_attr *attr = &evsel->attr;
595 unsigned long long nsecs;
598 if (PRINT_FIELD(COMM)) {
600 printed += fprintf(fp, "%8.8s ", thread__comm_str(thread));
601 else if (PRINT_FIELD(IP) && symbol_conf.use_callchain)
602 printed += fprintf(fp, "%s ", thread__comm_str(thread));
604 printed += fprintf(fp, "%16s ", thread__comm_str(thread));
607 if (PRINT_FIELD(PID) && PRINT_FIELD(TID))
608 printed += fprintf(fp, "%5d/%-5d ", sample->pid, sample->tid);
609 else if (PRINT_FIELD(PID))
610 printed += fprintf(fp, "%5d ", sample->pid);
611 else if (PRINT_FIELD(TID))
612 printed += fprintf(fp, "%5d ", sample->tid);
614 if (PRINT_FIELD(CPU)) {
616 printed += fprintf(fp, "%3d ", sample->cpu);
618 printed += fprintf(fp, "[%03d] ", sample->cpu);
621 if (PRINT_FIELD(TIME)) {
622 nsecs = sample->time;
623 secs = nsecs / NSEC_PER_SEC;
624 nsecs -= secs * NSEC_PER_SEC;
627 printed += fprintf(fp, "%5lu.%09llu: ", secs, nsecs);
629 char sample_time[32];
630 timestamp__scnprintf_usec(sample->time, sample_time, sizeof(sample_time));
631 printed += fprintf(fp, "%12s: ", sample_time);
639 mispred_str(struct branch_entry *br)
641 if (!(br->flags.mispred || br->flags.predicted))
644 return br->flags.predicted ? 'P' : 'M';
647 static int perf_sample__fprintf_brstack(struct perf_sample *sample,
648 struct thread *thread,
649 struct perf_event_attr *attr, FILE *fp)
651 struct branch_stack *br = sample->branch_stack;
652 struct addr_location alf, alt;
659 for (i = 0; i < br->nr; i++) {
660 from = br->entries[i].from;
661 to = br->entries[i].to;
663 if (PRINT_FIELD(DSO)) {
664 memset(&alf, 0, sizeof(alf));
665 memset(&alt, 0, sizeof(alt));
666 thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, from, &alf);
667 thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, to, &alt);
670 printed += fprintf(fp, " 0x%"PRIx64, from);
671 if (PRINT_FIELD(DSO)) {
672 printed += fprintf(fp, "(");
673 printed += map__fprintf_dsoname(alf.map, fp);
674 printed += fprintf(fp, ")");
677 printed += fprintf(fp, "/0x%"PRIx64, to);
678 if (PRINT_FIELD(DSO)) {
679 printed += fprintf(fp, "(");
680 printed += map__fprintf_dsoname(alt.map, fp);
681 printed += fprintf(fp, ")");
684 printed += fprintf(fp, "/%c/%c/%c/%d ",
685 mispred_str( br->entries + i),
686 br->entries[i].flags.in_tx? 'X' : '-',
687 br->entries[i].flags.abort? 'A' : '-',
688 br->entries[i].flags.cycles);
694 static int perf_sample__fprintf_brstacksym(struct perf_sample *sample,
695 struct thread *thread,
696 struct perf_event_attr *attr, FILE *fp)
698 struct branch_stack *br = sample->branch_stack;
699 struct addr_location alf, alt;
706 for (i = 0; i < br->nr; i++) {
708 memset(&alf, 0, sizeof(alf));
709 memset(&alt, 0, sizeof(alt));
710 from = br->entries[i].from;
711 to = br->entries[i].to;
713 thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, from, &alf);
715 alf.sym = map__find_symbol(alf.map, alf.addr);
717 thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, to, &alt);
719 alt.sym = map__find_symbol(alt.map, alt.addr);
721 printed += symbol__fprintf_symname_offs(alf.sym, &alf, fp);
722 if (PRINT_FIELD(DSO)) {
723 printed += fprintf(fp, "(");
724 printed += map__fprintf_dsoname(alf.map, fp);
725 printed += fprintf(fp, ")");
727 printed += fprintf(fp, "%c", '/');
728 printed += symbol__fprintf_symname_offs(alt.sym, &alt, fp);
729 if (PRINT_FIELD(DSO)) {
730 printed += fprintf(fp, "(");
731 printed += map__fprintf_dsoname(alt.map, fp);
732 printed += fprintf(fp, ")");
734 printed += fprintf(fp, "/%c/%c/%c/%d ",
735 mispred_str( br->entries + i),
736 br->entries[i].flags.in_tx? 'X' : '-',
737 br->entries[i].flags.abort? 'A' : '-',
738 br->entries[i].flags.cycles);
744 static int perf_sample__fprintf_brstackoff(struct perf_sample *sample,
745 struct thread *thread,
746 struct perf_event_attr *attr, FILE *fp)
748 struct branch_stack *br = sample->branch_stack;
749 struct addr_location alf, alt;
756 for (i = 0; i < br->nr; i++) {
758 memset(&alf, 0, sizeof(alf));
759 memset(&alt, 0, sizeof(alt));
760 from = br->entries[i].from;
761 to = br->entries[i].to;
763 thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, from, &alf);
764 if (alf.map && !alf.map->dso->adjust_symbols)
765 from = map__map_ip(alf.map, from);
767 thread__find_addr_map(thread, sample->cpumode, MAP__FUNCTION, to, &alt);
768 if (alt.map && !alt.map->dso->adjust_symbols)
769 to = map__map_ip(alt.map, to);
771 printed += fprintf(fp, " 0x%"PRIx64, from);
772 if (PRINT_FIELD(DSO)) {
773 printed += fprintf(fp, "(");
774 printed += map__fprintf_dsoname(alf.map, fp);
775 printed += fprintf(fp, ")");
777 printed += fprintf(fp, "/0x%"PRIx64, to);
778 if (PRINT_FIELD(DSO)) {
779 printed += fprintf(fp, "(");
780 printed += map__fprintf_dsoname(alt.map, fp);
781 printed += fprintf(fp, ")");
783 printed += fprintf(fp, "/%c/%c/%c/%d ",
784 mispred_str(br->entries + i),
785 br->entries[i].flags.in_tx ? 'X' : '-',
786 br->entries[i].flags.abort ? 'A' : '-',
787 br->entries[i].flags.cycles);
792 #define MAXBB 16384UL
794 static int grab_bb(u8 *buffer, u64 start, u64 end,
795 struct machine *machine, struct thread *thread,
796 bool *is64bit, u8 *cpumode, bool last)
799 struct addr_location al;
805 kernel = machine__kernel_ip(machine, start);
807 *cpumode = PERF_RECORD_MISC_KERNEL;
809 *cpumode = PERF_RECORD_MISC_USER;
812 * Block overlaps between kernel and user.
813 * This can happen due to ring filtering
814 * On Intel CPUs the entry into the kernel is filtered,
815 * but the exit is not. Let the caller patch it up.
817 if (kernel != machine__kernel_ip(machine, end)) {
818 pr_debug("\tblock %" PRIx64 "-%" PRIx64 " transfers between kernel and user\n", start, end);
822 memset(&al, 0, sizeof(al));
823 if (end - start > MAXBB - MAXINSN) {
825 pr_debug("\tbrstack does not reach to final jump (%" PRIx64 "-%" PRIx64 ")\n", start, end);
827 pr_debug("\tblock %" PRIx64 "-%" PRIx64 " (%" PRIu64 ") too long to dump\n", start, end, end - start);
831 thread__find_addr_map(thread, *cpumode, MAP__FUNCTION, start, &al);
832 if (!al.map || !al.map->dso) {
833 pr_debug("\tcannot resolve %" PRIx64 "-%" PRIx64 "\n", start, end);
836 if (al.map->dso->data.status == DSO_DATA_STATUS_ERROR) {
837 pr_debug("\tcannot resolve %" PRIx64 "-%" PRIx64 "\n", start, end);
841 /* Load maps to ensure dso->is_64_bit has been updated */
844 offset = al.map->map_ip(al.map, start);
845 len = dso__data_read_offset(al.map->dso, machine, offset, (u8 *)buffer,
846 end - start + MAXINSN);
848 *is64bit = al.map->dso->is_64_bit;
850 pr_debug("\tcannot fetch code for block at %" PRIx64 "-%" PRIx64 "\n",
855 static int ip__fprintf_jump(uint64_t ip, struct branch_entry *en,
856 struct perf_insn *x, u8 *inbuf, int len,
859 int printed = fprintf(fp, "\t%016" PRIx64 "\t%-30s\t#%s%s%s%s", ip,
860 dump_insn(x, ip, inbuf, len, NULL),
861 en->flags.predicted ? " PRED" : "",
862 en->flags.mispred ? " MISPRED" : "",
863 en->flags.in_tx ? " INTX" : "",
864 en->flags.abort ? " ABORT" : "");
865 if (en->flags.cycles) {
866 printed += fprintf(fp, " %d cycles", en->flags.cycles);
868 printed += fprintf(fp, " %.2f IPC", (float)insn / en->flags.cycles);
870 return printed + fprintf(fp, "\n");
873 static int ip__fprintf_sym(uint64_t addr, struct thread *thread,
874 u8 cpumode, int cpu, struct symbol **lastsym,
875 struct perf_event_attr *attr, FILE *fp)
877 struct addr_location al;
878 int off, printed = 0;
880 memset(&al, 0, sizeof(al));
882 thread__find_addr_map(thread, cpumode, MAP__FUNCTION, addr, &al);
884 thread__find_addr_map(thread, cpumode, MAP__VARIABLE,
886 if ((*lastsym) && al.addr >= (*lastsym)->start && al.addr < (*lastsym)->end)
892 al.sym = map__find_symbol(al.map, al.addr);
897 if (al.addr < al.sym->end)
898 off = al.addr - al.sym->start;
900 off = al.addr - al.map->start - al.sym->start;
901 printed += fprintf(fp, "\t%s", al.sym->name);
903 printed += fprintf(fp, "%+d", off);
904 printed += fprintf(fp, ":");
905 if (PRINT_FIELD(SRCLINE))
906 printed += map__fprintf_srcline(al.map, al.addr, "\t", fp);
907 printed += fprintf(fp, "\n");
913 static int perf_sample__fprintf_brstackinsn(struct perf_sample *sample,
914 struct thread *thread,
915 struct perf_event_attr *attr,
916 struct machine *machine, FILE *fp)
918 struct branch_stack *br = sample->branch_stack;
920 int i, insn, len, nr, ilen, printed = 0;
924 struct symbol *lastsym = NULL;
929 if (max_blocks && nr > max_blocks + 1)
935 printed += fprintf(fp, "%c", '\n');
937 /* Handle first from jump, of which we don't know the entry. */
938 len = grab_bb(buffer, br->entries[nr-1].from,
939 br->entries[nr-1].from,
940 machine, thread, &x.is64bit, &x.cpumode, false);
942 printed += ip__fprintf_sym(br->entries[nr - 1].from, thread,
943 x.cpumode, x.cpu, &lastsym, attr, fp);
944 printed += ip__fprintf_jump(br->entries[nr - 1].from, &br->entries[nr - 1],
945 &x, buffer, len, 0, fp);
948 /* Print all blocks */
949 for (i = nr - 2; i >= 0; i--) {
950 if (br->entries[i].from || br->entries[i].to)
951 pr_debug("%d: %" PRIx64 "-%" PRIx64 "\n", i,
954 start = br->entries[i + 1].to;
955 end = br->entries[i].from;
957 len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, false);
958 /* Patch up missing kernel transfers due to ring filters */
959 if (len == -ENXIO && i > 0) {
960 end = br->entries[--i].from;
961 pr_debug("\tpatching up to %" PRIx64 "-%" PRIx64 "\n", start, end);
962 len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, false);
968 for (off = 0;; off += ilen) {
969 uint64_t ip = start + off;
971 printed += ip__fprintf_sym(ip, thread, x.cpumode, x.cpu, &lastsym, attr, fp);
973 printed += ip__fprintf_jump(ip, &br->entries[i], &x, buffer + off, len - off, insn, fp);
976 printed += fprintf(fp, "\t%016" PRIx64 "\t%s\n", ip,
977 dump_insn(&x, ip, buffer + off, len - off, &ilen));
986 * Hit the branch? In this case we are already done, and the target
987 * has not been executed yet.
989 if (br->entries[0].from == sample->ip)
991 if (br->entries[0].flags.abort)
995 * Print final block upto sample
997 start = br->entries[0].to;
999 len = grab_bb(buffer, start, end, machine, thread, &x.is64bit, &x.cpumode, true);
1000 printed += ip__fprintf_sym(start, thread, x.cpumode, x.cpu, &lastsym, attr, fp);
1002 /* Print at least last IP if basic block did not work */
1003 len = grab_bb(buffer, sample->ip, sample->ip,
1004 machine, thread, &x.is64bit, &x.cpumode, false);
1008 printed += fprintf(fp, "\t%016" PRIx64 "\t%s\n", sample->ip,
1009 dump_insn(&x, sample->ip, buffer, len, NULL));
1012 for (off = 0; off <= end - start; off += ilen) {
1013 printed += fprintf(fp, "\t%016" PRIx64 "\t%s\n", start + off,
1014 dump_insn(&x, start + off, buffer + off, len - off, &ilen));
1022 static int perf_sample__fprintf_addr(struct perf_sample *sample,
1023 struct thread *thread,
1024 struct perf_event_attr *attr, FILE *fp)
1026 struct addr_location al;
1027 int printed = fprintf(fp, "%16" PRIx64, sample->addr);
1029 if (!sample_addr_correlates_sym(attr))
1032 thread__resolve(thread, &al, sample);
1034 if (PRINT_FIELD(SYM)) {
1035 printed += fprintf(fp, " ");
1036 if (PRINT_FIELD(SYMOFFSET))
1037 printed += symbol__fprintf_symname_offs(al.sym, &al, fp);
1039 printed += symbol__fprintf_symname(al.sym, fp);
1042 if (PRINT_FIELD(DSO)) {
1043 printed += fprintf(fp, " (");
1044 printed += map__fprintf_dsoname(al.map, fp);
1045 printed += fprintf(fp, ")");
1051 static int perf_sample__fprintf_callindent(struct perf_sample *sample,
1052 struct perf_evsel *evsel,
1053 struct thread *thread,
1054 struct addr_location *al, FILE *fp)
1056 struct perf_event_attr *attr = &evsel->attr;
1057 size_t depth = thread_stack__depth(thread);
1058 struct addr_location addr_al;
1059 const char *name = NULL;
1065 * The 'return' has already been popped off the stack so the depth has
1066 * to be adjusted to match the 'call'.
1068 if (thread->ts && sample->flags & PERF_IP_FLAG_RETURN)
1071 if (sample->flags & (PERF_IP_FLAG_CALL | PERF_IP_FLAG_TRACE_BEGIN)) {
1072 if (sample_addr_correlates_sym(attr)) {
1073 thread__resolve(thread, &addr_al, sample);
1075 name = addr_al.sym->name;
1081 } else if (sample->flags & (PERF_IP_FLAG_RETURN | PERF_IP_FLAG_TRACE_END)) {
1083 name = al->sym->name;
1089 len = fprintf(fp, "%*s%s", (int)depth * 4, "", name);
1091 len = fprintf(fp, "%*s%16" PRIx64, (int)depth * 4, "", ip);
1097 * Try to keep the output length from changing frequently so that the
1098 * output lines up more nicely.
1100 if (len > spacing || (len && len < spacing - 52))
1101 spacing = round_up(len + 4, 32);
1104 len += fprintf(fp, "%*s", spacing - len, "");
1109 static int perf_sample__fprintf_insn(struct perf_sample *sample,
1110 struct perf_event_attr *attr,
1111 struct thread *thread,
1112 struct machine *machine, FILE *fp)
1116 if (PRINT_FIELD(INSNLEN))
1117 printed += fprintf(fp, " ilen: %d", sample->insn_len);
1118 if (PRINT_FIELD(INSN)) {
1121 printed += fprintf(fp, " insn:");
1122 for (i = 0; i < sample->insn_len; i++)
1123 printed += fprintf(fp, " %02x", (unsigned char)sample->insn[i]);
1125 if (PRINT_FIELD(BRSTACKINSN))
1126 printed += perf_sample__fprintf_brstackinsn(sample, thread, attr, machine, fp);
1131 static int perf_sample__fprintf_bts(struct perf_sample *sample,
1132 struct perf_evsel *evsel,
1133 struct thread *thread,
1134 struct addr_location *al,
1135 struct machine *machine, FILE *fp)
1137 struct perf_event_attr *attr = &evsel->attr;
1138 unsigned int type = output_type(attr->type);
1139 bool print_srcline_last = false;
1142 if (PRINT_FIELD(CALLINDENT))
1143 printed += perf_sample__fprintf_callindent(sample, evsel, thread, al, fp);
1145 /* print branch_from information */
1146 if (PRINT_FIELD(IP)) {
1147 unsigned int print_opts = output[type].print_ip_opts;
1148 struct callchain_cursor *cursor = NULL;
1150 if (symbol_conf.use_callchain && sample->callchain &&
1151 thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
1152 sample, NULL, NULL, scripting_max_stack) == 0)
1153 cursor = &callchain_cursor;
1155 if (cursor == NULL) {
1156 printed += fprintf(fp, " ");
1157 if (print_opts & EVSEL__PRINT_SRCLINE) {
1158 print_srcline_last = true;
1159 print_opts &= ~EVSEL__PRINT_SRCLINE;
1162 printed += fprintf(fp, "\n");
1164 printed += sample__fprintf_sym(sample, al, 0, print_opts, cursor, fp);
1167 /* print branch_to information */
1168 if (PRINT_FIELD(ADDR) ||
1169 ((evsel->attr.sample_type & PERF_SAMPLE_ADDR) &&
1170 !output[type].user_set)) {
1171 printed += fprintf(fp, " => ");
1172 printed += perf_sample__fprintf_addr(sample, thread, attr, fp);
1175 if (print_srcline_last)
1176 printed += map__fprintf_srcline(al->map, al->addr, "\n ", fp);
1178 printed += perf_sample__fprintf_insn(sample, attr, thread, machine, fp);
1179 return printed + fprintf(fp, "\n");
1185 } sample_flags[] = {
1186 {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL, "call"},
1187 {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN, "return"},
1188 {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CONDITIONAL, "jcc"},
1189 {PERF_IP_FLAG_BRANCH, "jmp"},
1190 {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_INTERRUPT, "int"},
1191 {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN | PERF_IP_FLAG_INTERRUPT, "iret"},
1192 {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_SYSCALLRET, "syscall"},
1193 {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_RETURN | PERF_IP_FLAG_SYSCALLRET, "sysret"},
1194 {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_ASYNC, "async"},
1195 {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_CALL | PERF_IP_FLAG_ASYNC | PERF_IP_FLAG_INTERRUPT, "hw int"},
1196 {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TX_ABORT, "tx abrt"},
1197 {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TRACE_BEGIN, "tr strt"},
1198 {PERF_IP_FLAG_BRANCH | PERF_IP_FLAG_TRACE_END, "tr end"},
1202 static int perf_sample__fprintf_flags(u32 flags, FILE *fp)
1204 const char *chars = PERF_IP_FLAG_CHARS;
1205 const int n = strlen(PERF_IP_FLAG_CHARS);
1206 bool in_tx = flags & PERF_IP_FLAG_IN_TX;
1207 const char *name = NULL;
1211 for (i = 0; sample_flags[i].name ; i++) {
1212 if (sample_flags[i].flags == (flags & ~PERF_IP_FLAG_IN_TX)) {
1213 name = sample_flags[i].name;
1218 for (i = 0; i < n; i++, flags >>= 1) {
1220 str[pos++] = chars[i];
1222 for (; i < 32; i++, flags >>= 1) {
1229 return fprintf(fp, " %-7s%4s ", name, in_tx ? "(x)" : "");
1231 return fprintf(fp, " %-11s ", str);
1234 struct printer_data {
1240 static int sample__fprintf_bpf_output(enum binary_printer_ops op,
1242 void *extra, FILE *fp)
1244 unsigned char ch = (unsigned char)val;
1245 struct printer_data *printer_data = extra;
1249 case BINARY_PRINT_DATA_BEGIN:
1250 printed += fprintf(fp, "\n");
1252 case BINARY_PRINT_LINE_BEGIN:
1253 printed += fprintf(fp, "%17s", !printer_data->line_no ? "BPF output:" :
1256 case BINARY_PRINT_ADDR:
1257 printed += fprintf(fp, " %04x:", val);
1259 case BINARY_PRINT_NUM_DATA:
1260 printed += fprintf(fp, " %02x", val);
1262 case BINARY_PRINT_NUM_PAD:
1263 printed += fprintf(fp, " ");
1265 case BINARY_PRINT_SEP:
1266 printed += fprintf(fp, " ");
1268 case BINARY_PRINT_CHAR_DATA:
1269 if (printer_data->hit_nul && ch)
1270 printer_data->is_printable = false;
1273 printed += fprintf(fp, "%c", '.');
1275 if (!printer_data->is_printable)
1279 printer_data->hit_nul = true;
1281 printer_data->is_printable = false;
1283 printed += fprintf(fp, "%c", ch);
1286 case BINARY_PRINT_CHAR_PAD:
1287 printed += fprintf(fp, " ");
1289 case BINARY_PRINT_LINE_END:
1290 printed += fprintf(fp, "\n");
1291 printer_data->line_no++;
1293 case BINARY_PRINT_DATA_END:
1301 static int perf_sample__fprintf_bpf_output(struct perf_sample *sample, FILE *fp)
1303 unsigned int nr_bytes = sample->raw_size;
1304 struct printer_data printer_data = {0, false, true};
1305 int printed = binary__fprintf(sample->raw_data, nr_bytes, 8,
1306 sample__fprintf_bpf_output, &printer_data, fp);
1308 if (printer_data.is_printable && printer_data.hit_nul)
1309 printed += fprintf(fp, "%17s \"%s\"\n", "BPF string:", (char *)(sample->raw_data));
1314 static int perf_sample__fprintf_spacing(int len, int spacing, FILE *fp)
1316 if (len > 0 && len < spacing)
1317 return fprintf(fp, "%*s", spacing - len, "");
1322 static int perf_sample__fprintf_pt_spacing(int len, FILE *fp)
1324 return perf_sample__fprintf_spacing(len, 34, fp);
1327 static int perf_sample__fprintf_synth_ptwrite(struct perf_sample *sample, FILE *fp)
1329 struct perf_synth_intel_ptwrite *data = perf_sample__synth_ptr(sample);
1332 if (perf_sample__bad_synth_size(sample, *data))
1335 len = fprintf(fp, " IP: %u payload: %#" PRIx64 " ",
1336 data->ip, le64_to_cpu(data->payload));
1337 return len + perf_sample__fprintf_pt_spacing(len, fp);
1340 static int perf_sample__fprintf_synth_mwait(struct perf_sample *sample, FILE *fp)
1342 struct perf_synth_intel_mwait *data = perf_sample__synth_ptr(sample);
1345 if (perf_sample__bad_synth_size(sample, *data))
1348 len = fprintf(fp, " hints: %#x extensions: %#x ",
1349 data->hints, data->extensions);
1350 return len + perf_sample__fprintf_pt_spacing(len, fp);
1353 static int perf_sample__fprintf_synth_pwre(struct perf_sample *sample, FILE *fp)
1355 struct perf_synth_intel_pwre *data = perf_sample__synth_ptr(sample);
1358 if (perf_sample__bad_synth_size(sample, *data))
1361 len = fprintf(fp, " hw: %u cstate: %u sub-cstate: %u ",
1362 data->hw, data->cstate, data->subcstate);
1363 return len + perf_sample__fprintf_pt_spacing(len, fp);
1366 static int perf_sample__fprintf_synth_exstop(struct perf_sample *sample, FILE *fp)
1368 struct perf_synth_intel_exstop *data = perf_sample__synth_ptr(sample);
1371 if (perf_sample__bad_synth_size(sample, *data))
1374 len = fprintf(fp, " IP: %u ", data->ip);
1375 return len + perf_sample__fprintf_pt_spacing(len, fp);
1378 static int perf_sample__fprintf_synth_pwrx(struct perf_sample *sample, FILE *fp)
1380 struct perf_synth_intel_pwrx *data = perf_sample__synth_ptr(sample);
1383 if (perf_sample__bad_synth_size(sample, *data))
1386 len = fprintf(fp, " deepest cstate: %u last cstate: %u wake reason: %#x ",
1387 data->deepest_cstate, data->last_cstate,
1389 return len + perf_sample__fprintf_pt_spacing(len, fp);
1392 static int perf_sample__fprintf_synth_cbr(struct perf_sample *sample, FILE *fp)
1394 struct perf_synth_intel_cbr *data = perf_sample__synth_ptr(sample);
1395 unsigned int percent, freq;
1398 if (perf_sample__bad_synth_size(sample, *data))
1401 freq = (le32_to_cpu(data->freq) + 500) / 1000;
1402 len = fprintf(fp, " cbr: %2u freq: %4u MHz ", data->cbr, freq);
1403 if (data->max_nonturbo) {
1404 percent = (5 + (1000 * data->cbr) / data->max_nonturbo) / 10;
1405 len += fprintf(fp, "(%3u%%) ", percent);
1407 return len + perf_sample__fprintf_pt_spacing(len, fp);
1410 static int perf_sample__fprintf_synth(struct perf_sample *sample,
1411 struct perf_evsel *evsel, FILE *fp)
1413 switch (evsel->attr.config) {
1414 case PERF_SYNTH_INTEL_PTWRITE:
1415 return perf_sample__fprintf_synth_ptwrite(sample, fp);
1416 case PERF_SYNTH_INTEL_MWAIT:
1417 return perf_sample__fprintf_synth_mwait(sample, fp);
1418 case PERF_SYNTH_INTEL_PWRE:
1419 return perf_sample__fprintf_synth_pwre(sample, fp);
1420 case PERF_SYNTH_INTEL_EXSTOP:
1421 return perf_sample__fprintf_synth_exstop(sample, fp);
1422 case PERF_SYNTH_INTEL_PWRX:
1423 return perf_sample__fprintf_synth_pwrx(sample, fp);
1424 case PERF_SYNTH_INTEL_CBR:
1425 return perf_sample__fprintf_synth_cbr(sample, fp);
1433 struct perf_script {
1434 struct perf_tool tool;
1435 struct perf_session *session;
1436 bool show_task_events;
1437 bool show_mmap_events;
1438 bool show_switch_events;
1439 bool show_namespace_events;
1441 bool per_event_dump;
1442 struct cpu_map *cpus;
1443 struct thread_map *threads;
1445 const char *time_str;
1446 struct perf_time_interval ptime;
1449 static int perf_evlist__max_name_len(struct perf_evlist *evlist)
1451 struct perf_evsel *evsel;
1454 evlist__for_each_entry(evlist, evsel) {
1455 int len = strlen(perf_evsel__name(evsel));
1457 max = MAX(len, max);
1463 static int data_src__fprintf(u64 data_src, FILE *fp)
1465 struct mem_info mi = { .data_src.val = data_src };
1471 perf_script__meminfo_scnprintf(decode, 100, &mi);
1473 len = scnprintf(out, 100, "%16" PRIx64 " %s", data_src, decode);
1477 return fprintf(fp, "%-*s", maxlen, out);
1480 static void process_event(struct perf_script *script,
1481 struct perf_sample *sample, struct perf_evsel *evsel,
1482 struct addr_location *al,
1483 struct machine *machine)
1485 struct thread *thread = al->thread;
1486 struct perf_event_attr *attr = &evsel->attr;
1487 unsigned int type = output_type(attr->type);
1488 struct perf_evsel_script *es = evsel->priv;
1491 if (output[type].fields == 0)
1496 perf_sample__fprintf_start(sample, thread, evsel, fp);
1498 if (PRINT_FIELD(PERIOD))
1499 fprintf(fp, "%10" PRIu64 " ", sample->period);
1501 if (PRINT_FIELD(EVNAME)) {
1502 const char *evname = perf_evsel__name(evsel);
1504 if (!script->name_width)
1505 script->name_width = perf_evlist__max_name_len(script->session->evlist);
1507 fprintf(fp, "%*s: ", script->name_width, evname ?: "[unknown]");
1511 perf_sample__fprintf_flags(sample->flags, fp);
1513 if (is_bts_event(attr)) {
1514 perf_sample__fprintf_bts(sample, evsel, thread, al, machine, fp);
1518 if (PRINT_FIELD(TRACE)) {
1519 event_format__fprintf(evsel->tp_format, sample->cpu,
1520 sample->raw_data, sample->raw_size, fp);
1523 if (attr->type == PERF_TYPE_SYNTH && PRINT_FIELD(SYNTH))
1524 perf_sample__fprintf_synth(sample, evsel, fp);
1526 if (PRINT_FIELD(ADDR))
1527 perf_sample__fprintf_addr(sample, thread, attr, fp);
1529 if (PRINT_FIELD(DATA_SRC))
1530 data_src__fprintf(sample->data_src, fp);
1532 if (PRINT_FIELD(WEIGHT))
1533 fprintf(fp, "%16" PRIu64, sample->weight);
1535 if (PRINT_FIELD(IP)) {
1536 struct callchain_cursor *cursor = NULL;
1538 if (symbol_conf.use_callchain && sample->callchain &&
1539 thread__resolve_callchain(al->thread, &callchain_cursor, evsel,
1540 sample, NULL, NULL, scripting_max_stack) == 0)
1541 cursor = &callchain_cursor;
1543 fputc(cursor ? '\n' : ' ', fp);
1544 sample__fprintf_sym(sample, al, 0, output[type].print_ip_opts, cursor, fp);
1547 if (PRINT_FIELD(IREGS))
1548 perf_sample__fprintf_iregs(sample, attr, fp);
1550 if (PRINT_FIELD(UREGS))
1551 perf_sample__fprintf_uregs(sample, attr, fp);
1553 if (PRINT_FIELD(BRSTACK))
1554 perf_sample__fprintf_brstack(sample, thread, attr, fp);
1555 else if (PRINT_FIELD(BRSTACKSYM))
1556 perf_sample__fprintf_brstacksym(sample, thread, attr, fp);
1557 else if (PRINT_FIELD(BRSTACKOFF))
1558 perf_sample__fprintf_brstackoff(sample, thread, attr, fp);
1560 if (perf_evsel__is_bpf_output(evsel) && PRINT_FIELD(BPF_OUTPUT))
1561 perf_sample__fprintf_bpf_output(sample, fp);
1562 perf_sample__fprintf_insn(sample, attr, thread, machine, fp);
1564 if (PRINT_FIELD(PHYS_ADDR))
1565 fprintf(fp, "%16" PRIx64, sample->phys_addr);
1569 static struct scripting_ops *scripting_ops;
1571 static void __process_stat(struct perf_evsel *counter, u64 tstamp)
1573 int nthreads = thread_map__nr(counter->threads);
1574 int ncpus = perf_evsel__nr_cpus(counter);
1576 static int header_printed;
1578 if (counter->system_wide)
1581 if (!header_printed) {
1582 printf("%3s %8s %15s %15s %15s %15s %s\n",
1583 "CPU", "THREAD", "VAL", "ENA", "RUN", "TIME", "EVENT");
1587 for (thread = 0; thread < nthreads; thread++) {
1588 for (cpu = 0; cpu < ncpus; cpu++) {
1589 struct perf_counts_values *counts;
1591 counts = perf_counts(counter->counts, cpu, thread);
1593 printf("%3d %8d %15" PRIu64 " %15" PRIu64 " %15" PRIu64 " %15" PRIu64 " %s\n",
1594 counter->cpus->map[cpu],
1595 thread_map__pid(counter->threads, thread),
1600 perf_evsel__name(counter));
1605 static void process_stat(struct perf_evsel *counter, u64 tstamp)
1607 if (scripting_ops && scripting_ops->process_stat)
1608 scripting_ops->process_stat(&stat_config, counter, tstamp);
1610 __process_stat(counter, tstamp);
1613 static void process_stat_interval(u64 tstamp)
1615 if (scripting_ops && scripting_ops->process_stat_interval)
1616 scripting_ops->process_stat_interval(tstamp);
1619 static void setup_scripting(void)
1621 setup_perl_scripting();
1622 setup_python_scripting();
1625 static int flush_scripting(void)
1627 return scripting_ops ? scripting_ops->flush_script() : 0;
1630 static int cleanup_scripting(void)
1632 pr_debug("\nperf script stopped\n");
1634 return scripting_ops ? scripting_ops->stop_script() : 0;
1637 static int process_sample_event(struct perf_tool *tool,
1638 union perf_event *event,
1639 struct perf_sample *sample,
1640 struct perf_evsel *evsel,
1641 struct machine *machine)
1643 struct perf_script *scr = container_of(tool, struct perf_script, tool);
1644 struct addr_location al;
1646 if (perf_time__skip_sample(&scr->ptime, sample->time))
1650 if (sample->time < last_timestamp) {
1651 pr_err("Samples misordered, previous: %" PRIu64
1652 " this: %" PRIu64 "\n", last_timestamp,
1656 last_timestamp = sample->time;
1660 if (machine__resolve(machine, &al, sample) < 0) {
1661 pr_err("problem processing %d event, skipping it.\n",
1662 event->header.type);
1669 if (cpu_list && !test_bit(sample->cpu, cpu_bitmap))
1673 scripting_ops->process_event(event, sample, evsel, &al);
1675 process_event(scr, sample, evsel, &al, machine);
1678 addr_location__put(&al);
1682 static int process_attr(struct perf_tool *tool, union perf_event *event,
1683 struct perf_evlist **pevlist)
1685 struct perf_script *scr = container_of(tool, struct perf_script, tool);
1686 struct perf_evlist *evlist;
1687 struct perf_evsel *evsel, *pos;
1690 err = perf_event__process_attr(tool, event, pevlist);
1695 evsel = perf_evlist__last(*pevlist);
1697 if (evsel->attr.type >= PERF_TYPE_MAX &&
1698 evsel->attr.type != PERF_TYPE_SYNTH)
1701 evlist__for_each_entry(evlist, pos) {
1702 if (pos->attr.type == evsel->attr.type && pos != evsel)
1706 set_print_ip_opts(&evsel->attr);
1708 if (evsel->attr.sample_type)
1709 err = perf_evsel__check_attr(evsel, scr->session);
1714 static int process_comm_event(struct perf_tool *tool,
1715 union perf_event *event,
1716 struct perf_sample *sample,
1717 struct machine *machine)
1719 struct thread *thread;
1720 struct perf_script *script = container_of(tool, struct perf_script, tool);
1721 struct perf_session *session = script->session;
1722 struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1725 thread = machine__findnew_thread(machine, event->comm.pid, event->comm.tid);
1726 if (thread == NULL) {
1727 pr_debug("problem processing COMM event, skipping it.\n");
1731 if (perf_event__process_comm(tool, event, sample, machine) < 0)
1734 if (!evsel->attr.sample_id_all) {
1737 sample->tid = event->comm.tid;
1738 sample->pid = event->comm.pid;
1740 perf_sample__fprintf_start(sample, thread, evsel, stdout);
1741 perf_event__fprintf(event, stdout);
1744 thread__put(thread);
1748 static int process_namespaces_event(struct perf_tool *tool,
1749 union perf_event *event,
1750 struct perf_sample *sample,
1751 struct machine *machine)
1753 struct thread *thread;
1754 struct perf_script *script = container_of(tool, struct perf_script, tool);
1755 struct perf_session *session = script->session;
1756 struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1759 thread = machine__findnew_thread(machine, event->namespaces.pid,
1760 event->namespaces.tid);
1761 if (thread == NULL) {
1762 pr_debug("problem processing NAMESPACES event, skipping it.\n");
1766 if (perf_event__process_namespaces(tool, event, sample, machine) < 0)
1769 if (!evsel->attr.sample_id_all) {
1772 sample->tid = event->namespaces.tid;
1773 sample->pid = event->namespaces.pid;
1775 perf_sample__fprintf_start(sample, thread, evsel, stdout);
1776 perf_event__fprintf(event, stdout);
1779 thread__put(thread);
1783 static int process_fork_event(struct perf_tool *tool,
1784 union perf_event *event,
1785 struct perf_sample *sample,
1786 struct machine *machine)
1788 struct thread *thread;
1789 struct perf_script *script = container_of(tool, struct perf_script, tool);
1790 struct perf_session *session = script->session;
1791 struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1793 if (perf_event__process_fork(tool, event, sample, machine) < 0)
1796 thread = machine__findnew_thread(machine, event->fork.pid, event->fork.tid);
1797 if (thread == NULL) {
1798 pr_debug("problem processing FORK event, skipping it.\n");
1802 if (!evsel->attr.sample_id_all) {
1804 sample->time = event->fork.time;
1805 sample->tid = event->fork.tid;
1806 sample->pid = event->fork.pid;
1808 perf_sample__fprintf_start(sample, thread, evsel, stdout);
1809 perf_event__fprintf(event, stdout);
1810 thread__put(thread);
1814 static int process_exit_event(struct perf_tool *tool,
1815 union perf_event *event,
1816 struct perf_sample *sample,
1817 struct machine *machine)
1820 struct thread *thread;
1821 struct perf_script *script = container_of(tool, struct perf_script, tool);
1822 struct perf_session *session = script->session;
1823 struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1825 thread = machine__findnew_thread(machine, event->fork.pid, event->fork.tid);
1826 if (thread == NULL) {
1827 pr_debug("problem processing EXIT event, skipping it.\n");
1831 if (!evsel->attr.sample_id_all) {
1834 sample->tid = event->fork.tid;
1835 sample->pid = event->fork.pid;
1837 perf_sample__fprintf_start(sample, thread, evsel, stdout);
1838 perf_event__fprintf(event, stdout);
1840 if (perf_event__process_exit(tool, event, sample, machine) < 0)
1843 thread__put(thread);
1847 static int process_mmap_event(struct perf_tool *tool,
1848 union perf_event *event,
1849 struct perf_sample *sample,
1850 struct machine *machine)
1852 struct thread *thread;
1853 struct perf_script *script = container_of(tool, struct perf_script, tool);
1854 struct perf_session *session = script->session;
1855 struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1857 if (perf_event__process_mmap(tool, event, sample, machine) < 0)
1860 thread = machine__findnew_thread(machine, event->mmap.pid, event->mmap.tid);
1861 if (thread == NULL) {
1862 pr_debug("problem processing MMAP event, skipping it.\n");
1866 if (!evsel->attr.sample_id_all) {
1869 sample->tid = event->mmap.tid;
1870 sample->pid = event->mmap.pid;
1872 perf_sample__fprintf_start(sample, thread, evsel, stdout);
1873 perf_event__fprintf(event, stdout);
1874 thread__put(thread);
1878 static int process_mmap2_event(struct perf_tool *tool,
1879 union perf_event *event,
1880 struct perf_sample *sample,
1881 struct machine *machine)
1883 struct thread *thread;
1884 struct perf_script *script = container_of(tool, struct perf_script, tool);
1885 struct perf_session *session = script->session;
1886 struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1888 if (perf_event__process_mmap2(tool, event, sample, machine) < 0)
1891 thread = machine__findnew_thread(machine, event->mmap2.pid, event->mmap2.tid);
1892 if (thread == NULL) {
1893 pr_debug("problem processing MMAP2 event, skipping it.\n");
1897 if (!evsel->attr.sample_id_all) {
1900 sample->tid = event->mmap2.tid;
1901 sample->pid = event->mmap2.pid;
1903 perf_sample__fprintf_start(sample, thread, evsel, stdout);
1904 perf_event__fprintf(event, stdout);
1905 thread__put(thread);
1909 static int process_switch_event(struct perf_tool *tool,
1910 union perf_event *event,
1911 struct perf_sample *sample,
1912 struct machine *machine)
1914 struct thread *thread;
1915 struct perf_script *script = container_of(tool, struct perf_script, tool);
1916 struct perf_session *session = script->session;
1917 struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
1919 if (perf_event__process_switch(tool, event, sample, machine) < 0)
1922 thread = machine__findnew_thread(machine, sample->pid,
1924 if (thread == NULL) {
1925 pr_debug("problem processing SWITCH event, skipping it.\n");
1929 perf_sample__fprintf_start(sample, thread, evsel, stdout);
1930 perf_event__fprintf(event, stdout);
1931 thread__put(thread);
1935 static void sig_handler(int sig __maybe_unused)
1940 static void perf_script__fclose_per_event_dump(struct perf_script *script)
1942 struct perf_evlist *evlist = script->session->evlist;
1943 struct perf_evsel *evsel;
1945 evlist__for_each_entry(evlist, evsel) {
1948 perf_evsel_script__delete(evsel->priv);
1953 static int perf_script__fopen_per_event_dump(struct perf_script *script)
1955 struct perf_evsel *evsel;
1957 evlist__for_each_entry(script->session->evlist, evsel) {
1958 evsel->priv = perf_evsel_script__new(evsel, script->session->data);
1959 if (evsel->priv == NULL)
1960 goto out_err_fclose;
1966 perf_script__fclose_per_event_dump(script);
1970 static int perf_script__setup_per_event_dump(struct perf_script *script)
1972 struct perf_evsel *evsel;
1973 static struct perf_evsel_script es_stdout;
1975 if (script->per_event_dump)
1976 return perf_script__fopen_per_event_dump(script);
1978 es_stdout.fp = stdout;
1980 evlist__for_each_entry(script->session->evlist, evsel)
1981 evsel->priv = &es_stdout;
1986 static void perf_script__exit_per_event_dump_stats(struct perf_script *script)
1988 struct perf_evsel *evsel;
1990 evlist__for_each_entry(script->session->evlist, evsel) {
1991 struct perf_evsel_script *es = evsel->priv;
1993 perf_evsel_script__fprintf(es, stdout);
1994 perf_evsel_script__delete(es);
1999 static int __cmd_script(struct perf_script *script)
2003 signal(SIGINT, sig_handler);
2005 /* override event processing functions */
2006 if (script->show_task_events) {
2007 script->tool.comm = process_comm_event;
2008 script->tool.fork = process_fork_event;
2009 script->tool.exit = process_exit_event;
2011 if (script->show_mmap_events) {
2012 script->tool.mmap = process_mmap_event;
2013 script->tool.mmap2 = process_mmap2_event;
2015 if (script->show_switch_events)
2016 script->tool.context_switch = process_switch_event;
2017 if (script->show_namespace_events)
2018 script->tool.namespaces = process_namespaces_event;
2020 if (perf_script__setup_per_event_dump(script)) {
2021 pr_err("Couldn't create the per event dump files\n");
2025 ret = perf_session__process_events(script->session);
2027 if (script->per_event_dump)
2028 perf_script__exit_per_event_dump_stats(script);
2031 pr_err("Misordered timestamps: %" PRIu64 "\n", nr_unordered);
2036 struct script_spec {
2037 struct list_head node;
2038 struct scripting_ops *ops;
2042 static LIST_HEAD(script_specs);
2044 static struct script_spec *script_spec__new(const char *spec,
2045 struct scripting_ops *ops)
2047 struct script_spec *s = malloc(sizeof(*s) + strlen(spec) + 1);
2050 strcpy(s->spec, spec);
2057 static void script_spec__add(struct script_spec *s)
2059 list_add_tail(&s->node, &script_specs);
2062 static struct script_spec *script_spec__find(const char *spec)
2064 struct script_spec *s;
2066 list_for_each_entry(s, &script_specs, node)
2067 if (strcasecmp(s->spec, spec) == 0)
2072 int script_spec_register(const char *spec, struct scripting_ops *ops)
2074 struct script_spec *s;
2076 s = script_spec__find(spec);
2080 s = script_spec__new(spec, ops);
2084 script_spec__add(s);
2089 static struct scripting_ops *script_spec__lookup(const char *spec)
2091 struct script_spec *s = script_spec__find(spec);
2098 static void list_available_languages(void)
2100 struct script_spec *s;
2102 fprintf(stderr, "\n");
2103 fprintf(stderr, "Scripting language extensions (used in "
2104 "perf script -s [spec:]script.[spec]):\n\n");
2106 list_for_each_entry(s, &script_specs, node)
2107 fprintf(stderr, " %-42s [%s]\n", s->spec, s->ops->name);
2109 fprintf(stderr, "\n");
2112 static int parse_scriptname(const struct option *opt __maybe_unused,
2113 const char *str, int unset __maybe_unused)
2115 char spec[PATH_MAX];
2116 const char *script, *ext;
2119 if (strcmp(str, "lang") == 0) {
2120 list_available_languages();
2124 script = strchr(str, ':');
2127 if (len >= PATH_MAX) {
2128 fprintf(stderr, "invalid language specifier");
2131 strncpy(spec, str, len);
2133 scripting_ops = script_spec__lookup(spec);
2134 if (!scripting_ops) {
2135 fprintf(stderr, "invalid language specifier");
2141 ext = strrchr(script, '.');
2143 fprintf(stderr, "invalid script extension");
2146 scripting_ops = script_spec__lookup(++ext);
2147 if (!scripting_ops) {
2148 fprintf(stderr, "invalid script extension");
2153 script_name = strdup(script);
2158 static int parse_output_fields(const struct option *opt __maybe_unused,
2159 const char *arg, int unset __maybe_unused)
2161 char *tok, *strtok_saveptr = NULL;
2162 int i, imax = ARRAY_SIZE(all_output_options);
2165 char *str = strdup(arg);
2167 enum { DEFAULT, SET, ADD, REMOVE } change = DEFAULT;
2172 /* first word can state for which event type the user is specifying
2173 * the fields. If no type exists, the specified fields apply to all
2174 * event types found in the file minus the invalid fields for a type.
2176 tok = strchr(str, ':');
2180 if (!strcmp(str, "hw"))
2181 type = PERF_TYPE_HARDWARE;
2182 else if (!strcmp(str, "sw"))
2183 type = PERF_TYPE_SOFTWARE;
2184 else if (!strcmp(str, "trace"))
2185 type = PERF_TYPE_TRACEPOINT;
2186 else if (!strcmp(str, "raw"))
2187 type = PERF_TYPE_RAW;
2188 else if (!strcmp(str, "break"))
2189 type = PERF_TYPE_BREAKPOINT;
2190 else if (!strcmp(str, "synth"))
2191 type = OUTPUT_TYPE_SYNTH;
2193 fprintf(stderr, "Invalid event type in field string.\n");
2198 if (output[type].user_set)
2199 pr_warning("Overriding previous field request for %s events.\n",
2202 output[type].fields = 0;
2203 output[type].user_set = true;
2204 output[type].wildcard_set = false;
2208 if (strlen(str) == 0) {
2210 "Cannot set fields to 'none' for all event types.\n");
2215 /* Don't override defaults for +- */
2216 if (strchr(str, '+') || strchr(str, '-'))
2219 if (output_set_by_user())
2220 pr_warning("Overriding previous field request for all events.\n");
2222 for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
2223 output[j].fields = 0;
2224 output[j].user_set = true;
2225 output[j].wildcard_set = true;
2230 for (tok = strtok_r(tok, ",", &strtok_saveptr); tok; tok = strtok_r(NULL, ",", &strtok_saveptr)) {
2236 } else if (*tok == '-') {
2242 if (change != SET && change != DEFAULT)
2247 for (i = 0; i < imax; ++i) {
2248 if (strcmp(tok, all_output_options[i].str) == 0)
2251 if (i == imax && strcmp(tok, "flags") == 0) {
2252 print_flags = change == REMOVE ? false : true;
2256 fprintf(stderr, "Invalid field requested.\n");
2262 /* add user option to all events types for
2265 for (j = 0; j < OUTPUT_TYPE_MAX; ++j) {
2266 if (output[j].invalid_fields & all_output_options[i].field) {
2267 pr_warning("\'%s\' not valid for %s events. Ignoring.\n",
2268 all_output_options[i].str, event_type(j));
2270 if (change == REMOVE)
2271 output[j].fields &= ~all_output_options[i].field;
2273 output[j].fields |= all_output_options[i].field;
2277 if (output[type].invalid_fields & all_output_options[i].field) {
2278 fprintf(stderr, "\'%s\' not valid for %s events.\n",
2279 all_output_options[i].str, event_type(type));
2284 output[type].fields |= all_output_options[i].field;
2289 if (output[type].fields == 0) {
2290 pr_debug("No fields requested for %s type. "
2291 "Events will not be displayed.\n", event_type(type));
2297 fprintf(stderr, "Cannot mix +-field with overridden fields\n");
2304 /* Helper function for filesystems that return a dent->d_type DT_UNKNOWN */
2305 static int is_directory(const char *base_path, const struct dirent *dent)
2307 char path[PATH_MAX];
2310 sprintf(path, "%s/%s", base_path, dent->d_name);
2311 if (stat(path, &st))
2314 return S_ISDIR(st.st_mode);
2317 #define for_each_lang(scripts_path, scripts_dir, lang_dirent) \
2318 while ((lang_dirent = readdir(scripts_dir)) != NULL) \
2319 if ((lang_dirent->d_type == DT_DIR || \
2320 (lang_dirent->d_type == DT_UNKNOWN && \
2321 is_directory(scripts_path, lang_dirent))) && \
2322 (strcmp(lang_dirent->d_name, ".")) && \
2323 (strcmp(lang_dirent->d_name, "..")))
2325 #define for_each_script(lang_path, lang_dir, script_dirent) \
2326 while ((script_dirent = readdir(lang_dir)) != NULL) \
2327 if (script_dirent->d_type != DT_DIR && \
2328 (script_dirent->d_type != DT_UNKNOWN || \
2329 !is_directory(lang_path, script_dirent)))
2332 #define RECORD_SUFFIX "-record"
2333 #define REPORT_SUFFIX "-report"
2335 struct script_desc {
2336 struct list_head node;
2342 static LIST_HEAD(script_descs);
2344 static struct script_desc *script_desc__new(const char *name)
2346 struct script_desc *s = zalloc(sizeof(*s));
2348 if (s != NULL && name)
2349 s->name = strdup(name);
2354 static void script_desc__delete(struct script_desc *s)
2357 zfree(&s->half_liner);
2362 static void script_desc__add(struct script_desc *s)
2364 list_add_tail(&s->node, &script_descs);
2367 static struct script_desc *script_desc__find(const char *name)
2369 struct script_desc *s;
2371 list_for_each_entry(s, &script_descs, node)
2372 if (strcasecmp(s->name, name) == 0)
2377 static struct script_desc *script_desc__findnew(const char *name)
2379 struct script_desc *s = script_desc__find(name);
2384 s = script_desc__new(name);
2388 script_desc__add(s);
2393 static const char *ends_with(const char *str, const char *suffix)
2395 size_t suffix_len = strlen(suffix);
2396 const char *p = str;
2398 if (strlen(str) > suffix_len) {
2399 p = str + strlen(str) - suffix_len;
2400 if (!strncmp(p, suffix, suffix_len))
2407 static int read_script_info(struct script_desc *desc, const char *filename)
2409 char line[BUFSIZ], *p;
2412 fp = fopen(filename, "r");
2416 while (fgets(line, sizeof(line), fp)) {
2423 if (strlen(p) && *p == '!')
2427 if (strlen(p) && p[strlen(p) - 1] == '\n')
2428 p[strlen(p) - 1] = '\0';
2430 if (!strncmp(p, "description:", strlen("description:"))) {
2431 p += strlen("description:");
2432 desc->half_liner = strdup(ltrim(p));
2436 if (!strncmp(p, "args:", strlen("args:"))) {
2437 p += strlen("args:");
2438 desc->args = strdup(ltrim(p));
2448 static char *get_script_root(struct dirent *script_dirent, const char *suffix)
2450 char *script_root, *str;
2452 script_root = strdup(script_dirent->d_name);
2456 str = (char *)ends_with(script_root, suffix);
2466 static int list_available_scripts(const struct option *opt __maybe_unused,
2467 const char *s __maybe_unused,
2468 int unset __maybe_unused)
2470 struct dirent *script_dirent, *lang_dirent;
2471 char scripts_path[MAXPATHLEN];
2472 DIR *scripts_dir, *lang_dir;
2473 char script_path[MAXPATHLEN];
2474 char lang_path[MAXPATHLEN];
2475 struct script_desc *desc;
2476 char first_half[BUFSIZ];
2479 snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2481 scripts_dir = opendir(scripts_path);
2484 "open(%s) failed.\n"
2485 "Check \"PERF_EXEC_PATH\" env to set scripts dir.\n",
2490 for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2491 snprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
2492 lang_dirent->d_name);
2493 lang_dir = opendir(lang_path);
2497 for_each_script(lang_path, lang_dir, script_dirent) {
2498 script_root = get_script_root(script_dirent, REPORT_SUFFIX);
2500 desc = script_desc__findnew(script_root);
2501 snprintf(script_path, MAXPATHLEN, "%s/%s",
2502 lang_path, script_dirent->d_name);
2503 read_script_info(desc, script_path);
2509 fprintf(stdout, "List of available trace scripts:\n");
2510 list_for_each_entry(desc, &script_descs, node) {
2511 sprintf(first_half, "%s %s", desc->name,
2512 desc->args ? desc->args : "");
2513 fprintf(stdout, " %-36s %s\n", first_half,
2514 desc->half_liner ? desc->half_liner : "");
2521 * Some scripts specify the required events in their "xxx-record" file,
2522 * this function will check if the events in perf.data match those
2523 * mentioned in the "xxx-record".
2525 * Fixme: All existing "xxx-record" are all in good formats "-e event ",
2526 * which is covered well now. And new parsing code should be added to
2527 * cover the future complexing formats like event groups etc.
2529 static int check_ev_match(char *dir_name, char *scriptname,
2530 struct perf_session *session)
2532 char filename[MAXPATHLEN], evname[128];
2533 char line[BUFSIZ], *p;
2534 struct perf_evsel *pos;
2538 sprintf(filename, "%s/bin/%s-record", dir_name, scriptname);
2540 fp = fopen(filename, "r");
2544 while (fgets(line, sizeof(line), fp)) {
2550 p = strstr(p, "-e");
2556 len = strcspn(p, " \t");
2560 snprintf(evname, len + 1, "%s", p);
2563 evlist__for_each_entry(session->evlist, pos) {
2564 if (!strcmp(perf_evsel__name(pos), evname)) {
2582 * Return -1 if none is found, otherwise the actual scripts number.
2584 * Currently the only user of this function is the script browser, which
2585 * will list all statically runnable scripts, select one, execute it and
2586 * show the output in a perf browser.
2588 int find_scripts(char **scripts_array, char **scripts_path_array)
2590 struct dirent *script_dirent, *lang_dirent;
2591 char scripts_path[MAXPATHLEN], lang_path[MAXPATHLEN];
2592 DIR *scripts_dir, *lang_dir;
2593 struct perf_session *session;
2594 struct perf_data data = {
2598 .mode = PERF_DATA_MODE_READ,
2603 session = perf_session__new(&data, false, NULL);
2607 snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2609 scripts_dir = opendir(scripts_path);
2611 perf_session__delete(session);
2615 for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2616 snprintf(lang_path, MAXPATHLEN, "%s/%s", scripts_path,
2617 lang_dirent->d_name);
2619 if (strstr(lang_path, "perl"))
2623 if (strstr(lang_path, "python"))
2627 lang_dir = opendir(lang_path);
2631 for_each_script(lang_path, lang_dir, script_dirent) {
2632 /* Skip those real time scripts: xxxtop.p[yl] */
2633 if (strstr(script_dirent->d_name, "top."))
2635 sprintf(scripts_path_array[i], "%s/%s", lang_path,
2636 script_dirent->d_name);
2637 temp = strchr(script_dirent->d_name, '.');
2638 snprintf(scripts_array[i],
2639 (temp - script_dirent->d_name) + 1,
2640 "%s", script_dirent->d_name);
2642 if (check_ev_match(lang_path,
2643 scripts_array[i], session))
2651 closedir(scripts_dir);
2652 perf_session__delete(session);
2656 static char *get_script_path(const char *script_root, const char *suffix)
2658 struct dirent *script_dirent, *lang_dirent;
2659 char scripts_path[MAXPATHLEN];
2660 char script_path[MAXPATHLEN];
2661 DIR *scripts_dir, *lang_dir;
2662 char lang_path[MAXPATHLEN];
2663 char *__script_root;
2665 snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
2667 scripts_dir = opendir(scripts_path);
2671 for_each_lang(scripts_path, scripts_dir, lang_dirent) {
2672 snprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
2673 lang_dirent->d_name);
2674 lang_dir = opendir(lang_path);
2678 for_each_script(lang_path, lang_dir, script_dirent) {
2679 __script_root = get_script_root(script_dirent, suffix);
2680 if (__script_root && !strcmp(script_root, __script_root)) {
2681 free(__script_root);
2683 closedir(scripts_dir);
2684 snprintf(script_path, MAXPATHLEN, "%s/%s",
2685 lang_path, script_dirent->d_name);
2686 return strdup(script_path);
2688 free(__script_root);
2692 closedir(scripts_dir);
2697 static bool is_top_script(const char *script_path)
2699 return ends_with(script_path, "top") == NULL ? false : true;
2702 static int has_required_arg(char *script_path)
2704 struct script_desc *desc;
2708 desc = script_desc__new(NULL);
2710 if (read_script_info(desc, script_path))
2716 for (p = desc->args; *p; p++)
2720 script_desc__delete(desc);
2725 static int have_cmd(int argc, const char **argv)
2727 char **__argv = malloc(sizeof(const char *) * argc);
2730 pr_err("malloc failed\n");
2734 memcpy(__argv, argv, sizeof(const char *) * argc);
2735 argc = parse_options(argc, (const char **)__argv, record_options,
2736 NULL, PARSE_OPT_STOP_AT_NON_OPTION);
2739 system_wide = (argc == 0);
2744 static void script__setup_sample_type(struct perf_script *script)
2746 struct perf_session *session = script->session;
2747 u64 sample_type = perf_evlist__combined_sample_type(session->evlist);
2749 if (symbol_conf.use_callchain || symbol_conf.cumulate_callchain) {
2750 if ((sample_type & PERF_SAMPLE_REGS_USER) &&
2751 (sample_type & PERF_SAMPLE_STACK_USER))
2752 callchain_param.record_mode = CALLCHAIN_DWARF;
2753 else if (sample_type & PERF_SAMPLE_BRANCH_STACK)
2754 callchain_param.record_mode = CALLCHAIN_LBR;
2756 callchain_param.record_mode = CALLCHAIN_FP;
2760 static int process_stat_round_event(struct perf_tool *tool __maybe_unused,
2761 union perf_event *event,
2762 struct perf_session *session)
2764 struct stat_round_event *round = &event->stat_round;
2765 struct perf_evsel *counter;
2767 evlist__for_each_entry(session->evlist, counter) {
2768 perf_stat_process_counter(&stat_config, counter);
2769 process_stat(counter, round->time);
2772 process_stat_interval(round->time);
2776 static int process_stat_config_event(struct perf_tool *tool __maybe_unused,
2777 union perf_event *event,
2778 struct perf_session *session __maybe_unused)
2780 perf_event__read_stat_config(&stat_config, &event->stat_config);
2784 static int set_maps(struct perf_script *script)
2786 struct perf_evlist *evlist = script->session->evlist;
2788 if (!script->cpus || !script->threads)
2791 if (WARN_ONCE(script->allocated, "stats double allocation\n"))
2794 perf_evlist__set_maps(evlist, script->cpus, script->threads);
2796 if (perf_evlist__alloc_stats(evlist, true))
2799 script->allocated = true;
2804 int process_thread_map_event(struct perf_tool *tool,
2805 union perf_event *event,
2806 struct perf_session *session __maybe_unused)
2808 struct perf_script *script = container_of(tool, struct perf_script, tool);
2810 if (script->threads) {
2811 pr_warning("Extra thread map event, ignoring.\n");
2815 script->threads = thread_map__new_event(&event->thread_map);
2816 if (!script->threads)
2819 return set_maps(script);
2823 int process_cpu_map_event(struct perf_tool *tool __maybe_unused,
2824 union perf_event *event,
2825 struct perf_session *session __maybe_unused)
2827 struct perf_script *script = container_of(tool, struct perf_script, tool);
2830 pr_warning("Extra cpu map event, ignoring.\n");
2834 script->cpus = cpu_map__new_data(&event->cpu_map.data);
2838 return set_maps(script);
2841 int cmd_script(int argc, const char **argv)
2843 bool show_full_info = false;
2844 bool header = false;
2845 bool header_only = false;
2846 bool script_started = false;
2847 char *rec_script_path = NULL;
2848 char *rep_script_path = NULL;
2849 struct perf_session *session;
2850 struct itrace_synth_opts itrace_synth_opts = { .set = false, };
2851 char *script_path = NULL;
2852 const char **__argv;
2854 struct perf_script script = {
2856 .sample = process_sample_event,
2857 .mmap = perf_event__process_mmap,
2858 .mmap2 = perf_event__process_mmap2,
2859 .comm = perf_event__process_comm,
2860 .namespaces = perf_event__process_namespaces,
2861 .exit = perf_event__process_exit,
2862 .fork = perf_event__process_fork,
2863 .attr = process_attr,
2864 .event_update = perf_event__process_event_update,
2865 .tracing_data = perf_event__process_tracing_data,
2866 .feature = perf_event__process_feature,
2867 .build_id = perf_event__process_build_id,
2868 .id_index = perf_event__process_id_index,
2869 .auxtrace_info = perf_event__process_auxtrace_info,
2870 .auxtrace = perf_event__process_auxtrace,
2871 .auxtrace_error = perf_event__process_auxtrace_error,
2872 .stat = perf_event__process_stat_event,
2873 .stat_round = process_stat_round_event,
2874 .stat_config = process_stat_config_event,
2875 .thread_map = process_thread_map_event,
2876 .cpu_map = process_cpu_map_event,
2877 .ordered_events = true,
2878 .ordering_requires_timestamps = true,
2881 struct perf_data data = {
2882 .mode = PERF_DATA_MODE_READ,
2884 const struct option options[] = {
2885 OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
2886 "dump raw trace in ASCII"),
2887 OPT_INCR('v', "verbose", &verbose,
2888 "be more verbose (show symbol address, etc)"),
2889 OPT_BOOLEAN('L', "Latency", &latency_format,
2890 "show latency attributes (irqs/preemption disabled, etc)"),
2891 OPT_CALLBACK_NOOPT('l', "list", NULL, NULL, "list available scripts",
2892 list_available_scripts),
2893 OPT_CALLBACK('s', "script", NULL, "name",
2894 "script file name (lang:script name, script name, or *)",
2896 OPT_STRING('g', "gen-script", &generate_script_lang, "lang",
2897 "generate perf-script.xx script in specified language"),
2898 OPT_STRING('i', "input", &input_name, "file", "input file name"),
2899 OPT_BOOLEAN('d', "debug-mode", &debug_mode,
2900 "do various checks like samples ordering and lost events"),
2901 OPT_BOOLEAN(0, "header", &header, "Show data header."),
2902 OPT_BOOLEAN(0, "header-only", &header_only, "Show only data header."),
2903 OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
2904 "file", "vmlinux pathname"),
2905 OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
2906 "file", "kallsyms pathname"),
2907 OPT_BOOLEAN('G', "hide-call-graph", &no_callchain,
2908 "When printing symbols do not display call chain"),
2909 OPT_CALLBACK(0, "symfs", NULL, "directory",
2910 "Look for files with symbols relative to this directory",
2911 symbol__config_symfs),
2912 OPT_CALLBACK('F', "fields", NULL, "str",
2913 "comma separated output fields prepend with 'type:'. "
2914 "+field to add and -field to remove."
2915 "Valid types: hw,sw,trace,raw,synth. "
2916 "Fields: comm,tid,pid,time,cpu,event,trace,ip,sym,dso,"
2917 "addr,symoff,period,iregs,uregs,brstack,brstacksym,flags,"
2918 "bpf-output,callindent,insn,insnlen,brstackinsn,synth,phys_addr",
2919 parse_output_fields),
2920 OPT_BOOLEAN('a', "all-cpus", &system_wide,
2921 "system-wide collection from all CPUs"),
2922 OPT_STRING('S', "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
2923 "only consider these symbols"),
2924 OPT_STRING(0, "stop-bt", &symbol_conf.bt_stop_list_str, "symbol[,symbol...]",
2925 "Stop display of callgraph at these symbols"),
2926 OPT_STRING('C', "cpu", &cpu_list, "cpu", "list of cpus to profile"),
2927 OPT_STRING('c', "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
2928 "only display events for these comms"),
2929 OPT_STRING(0, "pid", &symbol_conf.pid_list_str, "pid[,pid...]",
2930 "only consider symbols in these pids"),
2931 OPT_STRING(0, "tid", &symbol_conf.tid_list_str, "tid[,tid...]",
2932 "only consider symbols in these tids"),
2933 OPT_UINTEGER(0, "max-stack", &scripting_max_stack,
2934 "Set the maximum stack depth when parsing the callchain, "
2935 "anything beyond the specified depth will be ignored. "
2936 "Default: kernel.perf_event_max_stack or " __stringify(PERF_MAX_STACK_DEPTH)),
2937 OPT_BOOLEAN('I', "show-info", &show_full_info,
2938 "display extended information from perf.data file"),
2939 OPT_BOOLEAN('\0', "show-kernel-path", &symbol_conf.show_kernel_path,
2940 "Show the path of [kernel.kallsyms]"),
2941 OPT_BOOLEAN('\0', "show-task-events", &script.show_task_events,
2942 "Show the fork/comm/exit events"),
2943 OPT_BOOLEAN('\0', "show-mmap-events", &script.show_mmap_events,
2944 "Show the mmap events"),
2945 OPT_BOOLEAN('\0', "show-switch-events", &script.show_switch_events,
2946 "Show context switch events (if recorded)"),
2947 OPT_BOOLEAN('\0', "show-namespace-events", &script.show_namespace_events,
2948 "Show namespace events (if recorded)"),
2949 OPT_BOOLEAN('\0', "per-event-dump", &script.per_event_dump,
2950 "Dump trace output to files named by the monitored events"),
2951 OPT_BOOLEAN('f', "force", &symbol_conf.force, "don't complain, do it"),
2952 OPT_INTEGER(0, "max-blocks", &max_blocks,
2953 "Maximum number of code blocks to dump with brstackinsn"),
2954 OPT_BOOLEAN(0, "ns", &nanosecs,
2955 "Use 9 decimal places when displaying time"),
2956 OPT_CALLBACK_OPTARG(0, "itrace", &itrace_synth_opts, NULL, "opts",
2957 "Instruction Tracing options",
2958 itrace_parse_synth_opts),
2959 OPT_BOOLEAN(0, "full-source-path", &srcline_full_filename,
2960 "Show full source file name path for source lines"),
2961 OPT_BOOLEAN(0, "demangle", &symbol_conf.demangle,
2962 "Enable symbol demangling"),
2963 OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel,
2964 "Enable kernel symbol demangling"),
2965 OPT_STRING(0, "time", &script.time_str, "str",
2966 "Time span of interest (start,stop)"),
2967 OPT_BOOLEAN(0, "inline", &symbol_conf.inline_name,
2968 "Show inline function"),
2971 const char * const script_subcommands[] = { "record", "report", NULL };
2972 const char *script_usage[] = {
2973 "perf script [<options>]",
2974 "perf script [<options>] record <script> [<record-options>] <command>",
2975 "perf script [<options>] report <script> [script-args]",
2976 "perf script [<options>] <script> [<record-options>] <command>",
2977 "perf script [<options>] <top-script> [script-args]",
2981 perf_set_singlethreaded();
2985 argc = parse_options_subcommand(argc, argv, options, script_subcommands, script_usage,
2986 PARSE_OPT_STOP_AT_NON_OPTION);
2988 data.file.path = input_name;
2989 data.force = symbol_conf.force;
2991 if (argc > 1 && !strncmp(argv[0], "rec", strlen("rec"))) {
2992 rec_script_path = get_script_path(argv[1], RECORD_SUFFIX);
2993 if (!rec_script_path)
2994 return cmd_record(argc, argv);
2997 if (argc > 1 && !strncmp(argv[0], "rep", strlen("rep"))) {
2998 rep_script_path = get_script_path(argv[1], REPORT_SUFFIX);
2999 if (!rep_script_path) {
3001 "Please specify a valid report script"
3002 "(see 'perf script -l' for listing)\n");
3007 if (itrace_synth_opts.callchain &&
3008 itrace_synth_opts.callchain_sz > scripting_max_stack)
3009 scripting_max_stack = itrace_synth_opts.callchain_sz;
3011 /* make sure PERF_EXEC_PATH is set for scripts */
3012 set_argv_exec_path(get_argv_exec_path());
3014 if (argc && !script_name && !rec_script_path && !rep_script_path) {
3019 rec_script_path = get_script_path(argv[0], RECORD_SUFFIX);
3020 rep_script_path = get_script_path(argv[0], REPORT_SUFFIX);
3022 if (!rec_script_path && !rep_script_path) {
3023 usage_with_options_msg(script_usage, options,
3024 "Couldn't find script `%s'\n\n See perf"
3025 " script -l for available scripts.\n", argv[0]);
3028 if (is_top_script(argv[0])) {
3029 rep_args = argc - 1;
3033 rep_args = has_required_arg(rep_script_path);
3034 rec_args = (argc - 1) - rep_args;
3036 usage_with_options_msg(script_usage, options,
3037 "`%s' script requires options."
3038 "\n\n See perf script -l for available "
3039 "scripts and options.\n", argv[0]);
3043 if (pipe(live_pipe) < 0) {
3044 perror("failed to create pipe");
3050 perror("failed to fork");
3057 dup2(live_pipe[1], 1);
3058 close(live_pipe[0]);
3060 if (is_top_script(argv[0])) {
3062 } else if (!system_wide) {
3063 if (have_cmd(argc - rep_args, &argv[rep_args]) != 0) {
3069 __argv = malloc((argc + 6) * sizeof(const char *));
3071 pr_err("malloc failed\n");
3076 __argv[j++] = "/bin/sh";
3077 __argv[j++] = rec_script_path;
3083 for (i = rep_args + 1; i < argc; i++)
3084 __argv[j++] = argv[i];
3087 execvp("/bin/sh", (char **)__argv);
3092 dup2(live_pipe[0], 0);
3093 close(live_pipe[1]);
3095 __argv = malloc((argc + 4) * sizeof(const char *));
3097 pr_err("malloc failed\n");
3103 __argv[j++] = "/bin/sh";
3104 __argv[j++] = rep_script_path;
3105 for (i = 1; i < rep_args + 1; i++)
3106 __argv[j++] = argv[i];
3111 execvp("/bin/sh", (char **)__argv);
3116 if (rec_script_path)
3117 script_path = rec_script_path;
3118 if (rep_script_path)
3119 script_path = rep_script_path;
3124 if (!rec_script_path)
3125 system_wide = false;
3126 else if (!system_wide) {
3127 if (have_cmd(argc - 1, &argv[1]) != 0) {
3133 __argv = malloc((argc + 2) * sizeof(const char *));
3135 pr_err("malloc failed\n");
3140 __argv[j++] = "/bin/sh";
3141 __argv[j++] = script_path;
3144 for (i = 2; i < argc; i++)
3145 __argv[j++] = argv[i];
3148 execvp("/bin/sh", (char **)__argv);
3156 session = perf_session__new(&data, false, &script.tool);
3157 if (session == NULL)
3160 if (header || header_only) {
3161 script.tool.show_feat_hdr = SHOW_FEAT_HEADER;
3162 perf_session__fprintf_info(session, stdout, show_full_info);
3167 script.tool.show_feat_hdr = SHOW_FEAT_HEADER_FULL_INFO;
3169 if (symbol__init(&session->header.env) < 0)
3172 script.session = session;
3173 script__setup_sample_type(&script);
3175 if (output[PERF_TYPE_HARDWARE].fields & PERF_OUTPUT_CALLINDENT)
3176 itrace_synth_opts.thread_stack = true;
3178 session->itrace_synth_opts = &itrace_synth_opts;
3181 err = perf_session__cpu_bitmap(session, cpu_list, cpu_bitmap);
3184 itrace_synth_opts.cpu_bitmap = cpu_bitmap;
3188 symbol_conf.use_callchain = true;
3190 symbol_conf.use_callchain = false;
3192 if (session->tevent.pevent &&
3193 pevent_set_function_resolver(session->tevent.pevent,
3194 machine__resolve_kernel_addr,
3195 &session->machines.host) < 0) {
3196 pr_err("%s: failed to set libtraceevent function resolver\n", __func__);
3201 if (generate_script_lang) {
3202 struct stat perf_stat;
3205 if (output_set_by_user()) {
3207 "custom fields not supported for generated scripts");
3212 input = open(data.file.path, O_RDONLY); /* input_name */
3215 perror("failed to open file");
3219 err = fstat(input, &perf_stat);
3221 perror("failed to stat file");
3225 if (!perf_stat.st_size) {
3226 fprintf(stderr, "zero-sized file, nothing to do!\n");
3230 scripting_ops = script_spec__lookup(generate_script_lang);
3231 if (!scripting_ops) {
3232 fprintf(stderr, "invalid language specifier");
3237 err = scripting_ops->generate_script(session->tevent.pevent,
3243 err = scripting_ops->start_script(script_name, argc, argv);
3246 pr_debug("perf script started with script %s\n\n", script_name);
3247 script_started = true;
3251 err = perf_session__check_output_opt(session);
3255 /* needs to be parsed after looking up reference time */
3256 if (perf_time__parse_str(&script.ptime, script.time_str) != 0) {
3257 pr_err("Invalid time string\n");
3262 err = __cmd_script(&script);
3267 perf_evlist__free_stats(session->evlist);
3268 perf_session__delete(session);
3271 cleanup_scripting();