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