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