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