perf script: Process cpu/threads maps
[linux-2.6-microblaze.git] / tools / perf / builtin-script.c
1 #include "builtin.h"
2
3 #include "perf.h"
4 #include "util/cache.h"
5 #include "util/debug.h"
6 #include <subcmd/exec-cmd.h>
7 #include "util/header.h"
8 #include <subcmd/parse-options.h>
9 #include "util/perf_regs.h"
10 #include "util/session.h"
11 #include "util/tool.h"
12 #include "util/symbol.h"
13 #include "util/thread.h"
14 #include "util/trace-event.h"
15 #include "util/util.h"
16 #include "util/evlist.h"
17 #include "util/evsel.h"
18 #include "util/sort.h"
19 #include "util/data.h"
20 #include "util/auxtrace.h"
21 #include "util/cpumap.h"
22 #include "util/thread_map.h"
23 #include "util/stat.h"
24 #include <linux/bitmap.h>
25 #include "asm/bug.h"
26
27 static char const               *script_name;
28 static char const               *generate_script_lang;
29 static bool                     debug_mode;
30 static u64                      last_timestamp;
31 static u64                      nr_unordered;
32 static bool                     no_callchain;
33 static bool                     latency_format;
34 static bool                     system_wide;
35 static bool                     print_flags;
36 static bool                     nanosecs;
37 static const char               *cpu_list;
38 static DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
39
40 unsigned int scripting_max_stack = PERF_MAX_STACK_DEPTH;
41
42 enum perf_output_field {
43         PERF_OUTPUT_COMM            = 1U << 0,
44         PERF_OUTPUT_TID             = 1U << 1,
45         PERF_OUTPUT_PID             = 1U << 2,
46         PERF_OUTPUT_TIME            = 1U << 3,
47         PERF_OUTPUT_CPU             = 1U << 4,
48         PERF_OUTPUT_EVNAME          = 1U << 5,
49         PERF_OUTPUT_TRACE           = 1U << 6,
50         PERF_OUTPUT_IP              = 1U << 7,
51         PERF_OUTPUT_SYM             = 1U << 8,
52         PERF_OUTPUT_DSO             = 1U << 9,
53         PERF_OUTPUT_ADDR            = 1U << 10,
54         PERF_OUTPUT_SYMOFFSET       = 1U << 11,
55         PERF_OUTPUT_SRCLINE         = 1U << 12,
56         PERF_OUTPUT_PERIOD          = 1U << 13,
57         PERF_OUTPUT_IREGS           = 1U << 14,
58         PERF_OUTPUT_BRSTACK         = 1U << 15,
59         PERF_OUTPUT_BRSTACKSYM      = 1U << 16,
60 };
61
62 struct output_option {
63         const char *str;
64         enum perf_output_field field;
65 } all_output_options[] = {
66         {.str = "comm",  .field = PERF_OUTPUT_COMM},
67         {.str = "tid",   .field = PERF_OUTPUT_TID},
68         {.str = "pid",   .field = PERF_OUTPUT_PID},
69         {.str = "time",  .field = PERF_OUTPUT_TIME},
70         {.str = "cpu",   .field = PERF_OUTPUT_CPU},
71         {.str = "event", .field = PERF_OUTPUT_EVNAME},
72         {.str = "trace", .field = PERF_OUTPUT_TRACE},
73         {.str = "ip",    .field = PERF_OUTPUT_IP},
74         {.str = "sym",   .field = PERF_OUTPUT_SYM},
75         {.str = "dso",   .field = PERF_OUTPUT_DSO},
76         {.str = "addr",  .field = PERF_OUTPUT_ADDR},
77         {.str = "symoff", .field = PERF_OUTPUT_SYMOFFSET},
78         {.str = "srcline", .field = PERF_OUTPUT_SRCLINE},
79         {.str = "period", .field = PERF_OUTPUT_PERIOD},
80         {.str = "iregs", .field = PERF_OUTPUT_IREGS},
81         {.str = "brstack", .field = PERF_OUTPUT_BRSTACK},
82         {.str = "brstacksym", .field = PERF_OUTPUT_BRSTACKSYM},
83 };
84
85 /* default set to maintain compatibility with current format */
86 static struct {
87         bool user_set;
88         bool wildcard_set;
89         unsigned int print_ip_opts;
90         u64 fields;
91         u64 invalid_fields;
92 } output[PERF_TYPE_MAX] = {
93
94         [PERF_TYPE_HARDWARE] = {
95                 .user_set = false,
96
97                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
98                               PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
99                               PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
100                               PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
101                               PERF_OUTPUT_PERIOD,
102
103                 .invalid_fields = PERF_OUTPUT_TRACE,
104         },
105
106         [PERF_TYPE_SOFTWARE] = {
107                 .user_set = false,
108
109                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
110                               PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
111                               PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
112                               PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
113                               PERF_OUTPUT_PERIOD,
114
115                 .invalid_fields = PERF_OUTPUT_TRACE,
116         },
117
118         [PERF_TYPE_TRACEPOINT] = {
119                 .user_set = false,
120
121                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
122                                   PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
123                                   PERF_OUTPUT_EVNAME | PERF_OUTPUT_TRACE,
124         },
125
126         [PERF_TYPE_RAW] = {
127                 .user_set = false,
128
129                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
130                               PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
131                               PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
132                               PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
133                               PERF_OUTPUT_PERIOD,
134
135                 .invalid_fields = PERF_OUTPUT_TRACE,
136         },
137
138         [PERF_TYPE_BREAKPOINT] = {
139                 .user_set = false,
140
141                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
142                               PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
143                               PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
144                               PERF_OUTPUT_SYM | PERF_OUTPUT_DSO |
145                               PERF_OUTPUT_PERIOD,
146
147                 .invalid_fields = PERF_OUTPUT_TRACE,
148         },
149 };
150
151 static bool output_set_by_user(void)
152 {
153         int j;
154         for (j = 0; j < PERF_TYPE_MAX; ++j) {
155                 if (output[j].user_set)
156                         return true;
157         }
158         return false;
159 }
160
161 static const char *output_field2str(enum perf_output_field field)
162 {
163         int i, imax = ARRAY_SIZE(all_output_options);
164         const char *str = "";
165
166         for (i = 0; i < imax; ++i) {
167                 if (all_output_options[i].field == field) {
168                         str = all_output_options[i].str;
169                         break;
170                 }
171         }
172         return str;
173 }
174
175 #define PRINT_FIELD(x)  (output[attr->type].fields & PERF_OUTPUT_##x)
176
177 static int perf_evsel__do_check_stype(struct perf_evsel *evsel,
178                                       u64 sample_type, const char *sample_msg,
179                                       enum perf_output_field field,
180                                       bool allow_user_set)
181 {
182         struct perf_event_attr *attr = &evsel->attr;
183         int type = attr->type;
184         const char *evname;
185
186         if (attr->sample_type & sample_type)
187                 return 0;
188
189         if (output[type].user_set) {
190                 if (allow_user_set)
191                         return 0;
192                 evname = perf_evsel__name(evsel);
193                 pr_err("Samples for '%s' event do not have %s attribute set. "
194                        "Cannot print '%s' field.\n",
195                        evname, sample_msg, output_field2str(field));
196                 return -1;
197         }
198
199         /* user did not ask for it explicitly so remove from the default list */
200         output[type].fields &= ~field;
201         evname = perf_evsel__name(evsel);
202         pr_debug("Samples for '%s' event do not have %s attribute set. "
203                  "Skipping '%s' field.\n",
204                  evname, sample_msg, output_field2str(field));
205
206         return 0;
207 }
208
209 static int perf_evsel__check_stype(struct perf_evsel *evsel,
210                                    u64 sample_type, const char *sample_msg,
211                                    enum perf_output_field field)
212 {
213         return perf_evsel__do_check_stype(evsel, sample_type, sample_msg, field,
214                                           false);
215 }
216
217 static int perf_evsel__check_attr(struct perf_evsel *evsel,
218                                   struct perf_session *session)
219 {
220         struct perf_event_attr *attr = &evsel->attr;
221         bool allow_user_set;
222
223         allow_user_set = perf_header__has_feat(&session->header,
224                                                HEADER_AUXTRACE);
225
226         if (PRINT_FIELD(TRACE) &&
227                 !perf_session__has_traces(session, "record -R"))
228                 return -EINVAL;
229
230         if (PRINT_FIELD(IP)) {
231                 if (perf_evsel__check_stype(evsel, PERF_SAMPLE_IP, "IP",
232                                             PERF_OUTPUT_IP))
233                         return -EINVAL;
234         }
235
236         if (PRINT_FIELD(ADDR) &&
237                 perf_evsel__do_check_stype(evsel, PERF_SAMPLE_ADDR, "ADDR",
238                                            PERF_OUTPUT_ADDR, allow_user_set))
239                 return -EINVAL;
240
241         if (PRINT_FIELD(SYM) && !PRINT_FIELD(IP) && !PRINT_FIELD(ADDR)) {
242                 pr_err("Display of symbols requested but neither sample IP nor "
243                            "sample address\nis selected. Hence, no addresses to convert "
244                        "to symbols.\n");
245                 return -EINVAL;
246         }
247         if (PRINT_FIELD(SYMOFFSET) && !PRINT_FIELD(SYM)) {
248                 pr_err("Display of offsets requested but symbol is not"
249                        "selected.\n");
250                 return -EINVAL;
251         }
252         if (PRINT_FIELD(DSO) && !PRINT_FIELD(IP) && !PRINT_FIELD(ADDR)) {
253                 pr_err("Display of DSO requested but neither sample IP nor "
254                            "sample address\nis selected. Hence, no addresses to convert "
255                        "to DSO.\n");
256                 return -EINVAL;
257         }
258         if (PRINT_FIELD(SRCLINE) && !PRINT_FIELD(IP)) {
259                 pr_err("Display of source line number requested but sample IP is not\n"
260                        "selected. Hence, no address to lookup the source line number.\n");
261                 return -EINVAL;
262         }
263
264         if ((PRINT_FIELD(PID) || PRINT_FIELD(TID)) &&
265                 perf_evsel__check_stype(evsel, PERF_SAMPLE_TID, "TID",
266                                         PERF_OUTPUT_TID|PERF_OUTPUT_PID))
267                 return -EINVAL;
268
269         if (PRINT_FIELD(TIME) &&
270                 perf_evsel__check_stype(evsel, PERF_SAMPLE_TIME, "TIME",
271                                         PERF_OUTPUT_TIME))
272                 return -EINVAL;
273
274         if (PRINT_FIELD(CPU) &&
275                 perf_evsel__do_check_stype(evsel, PERF_SAMPLE_CPU, "CPU",
276                                            PERF_OUTPUT_CPU, allow_user_set))
277                 return -EINVAL;
278
279         if (PRINT_FIELD(PERIOD) &&
280                 perf_evsel__check_stype(evsel, PERF_SAMPLE_PERIOD, "PERIOD",
281                                         PERF_OUTPUT_PERIOD))
282                 return -EINVAL;
283
284         if (PRINT_FIELD(IREGS) &&
285                 perf_evsel__check_stype(evsel, PERF_SAMPLE_REGS_INTR, "IREGS",
286                                         PERF_OUTPUT_IREGS))
287                 return -EINVAL;
288
289         return 0;
290 }
291
292 static void set_print_ip_opts(struct perf_event_attr *attr)
293 {
294         unsigned int type = attr->type;
295
296         output[type].print_ip_opts = 0;
297         if (PRINT_FIELD(IP))
298                 output[type].print_ip_opts |= PRINT_IP_OPT_IP;
299
300         if (PRINT_FIELD(SYM))
301                 output[type].print_ip_opts |= PRINT_IP_OPT_SYM;
302
303         if (PRINT_FIELD(DSO))
304                 output[type].print_ip_opts |= PRINT_IP_OPT_DSO;
305
306         if (PRINT_FIELD(SYMOFFSET))
307                 output[type].print_ip_opts |= PRINT_IP_OPT_SYMOFFSET;
308
309         if (PRINT_FIELD(SRCLINE))
310                 output[type].print_ip_opts |= PRINT_IP_OPT_SRCLINE;
311 }
312
313 /*
314  * verify all user requested events exist and the samples
315  * have the expected data
316  */
317 static int perf_session__check_output_opt(struct perf_session *session)
318 {
319         int j;
320         struct perf_evsel *evsel;
321
322         for (j = 0; j < PERF_TYPE_MAX; ++j) {
323                 evsel = perf_session__find_first_evtype(session, j);
324
325                 /*
326                  * even if fields is set to 0 (ie., show nothing) event must
327                  * exist if user explicitly includes it on the command line
328                  */
329                 if (!evsel && output[j].user_set && !output[j].wildcard_set) {
330                         pr_err("%s events do not exist. "
331                                "Remove corresponding -f option to proceed.\n",
332                                event_type(j));
333                         return -1;
334                 }
335
336                 if (evsel && output[j].fields &&
337                         perf_evsel__check_attr(evsel, session))
338                         return -1;
339
340                 if (evsel == NULL)
341                         continue;
342
343                 set_print_ip_opts(&evsel->attr);
344         }
345
346         if (!no_callchain) {
347                 bool use_callchain = false;
348
349                 evlist__for_each(session->evlist, evsel) {
350                         if (evsel->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
351                                 use_callchain = true;
352                                 break;
353                         }
354                 }
355                 if (!use_callchain)
356                         symbol_conf.use_callchain = false;
357         }
358
359         /*
360          * set default for tracepoints to print symbols only
361          * if callchains are present
362          */
363         if (symbol_conf.use_callchain &&
364             !output[PERF_TYPE_TRACEPOINT].user_set) {
365                 struct perf_event_attr *attr;
366
367                 j = PERF_TYPE_TRACEPOINT;
368                 evsel = perf_session__find_first_evtype(session, j);
369                 if (evsel == NULL)
370                         goto out;
371
372                 attr = &evsel->attr;
373
374                 if (attr->sample_type & PERF_SAMPLE_CALLCHAIN) {
375                         output[j].fields |= PERF_OUTPUT_IP;
376                         output[j].fields |= PERF_OUTPUT_SYM;
377                         output[j].fields |= PERF_OUTPUT_DSO;
378                         set_print_ip_opts(attr);
379                 }
380         }
381
382 out:
383         return 0;
384 }
385
386 static void print_sample_iregs(union perf_event *event __maybe_unused,
387                           struct perf_sample *sample,
388                           struct thread *thread __maybe_unused,
389                           struct perf_event_attr *attr)
390 {
391         struct regs_dump *regs = &sample->intr_regs;
392         uint64_t mask = attr->sample_regs_intr;
393         unsigned i = 0, r;
394
395         if (!regs)
396                 return;
397
398         for_each_set_bit(r, (unsigned long *) &mask, sizeof(mask) * 8) {
399                 u64 val = regs->regs[i++];
400                 printf("%5s:0x%"PRIx64" ", perf_reg_name(r), val);
401         }
402 }
403
404 static void print_sample_start(struct perf_sample *sample,
405                                struct thread *thread,
406                                struct perf_evsel *evsel)
407 {
408         struct perf_event_attr *attr = &evsel->attr;
409         unsigned long secs;
410         unsigned long usecs;
411         unsigned long long nsecs;
412
413         if (PRINT_FIELD(COMM)) {
414                 if (latency_format)
415                         printf("%8.8s ", thread__comm_str(thread));
416                 else if (PRINT_FIELD(IP) && symbol_conf.use_callchain)
417                         printf("%s ", thread__comm_str(thread));
418                 else
419                         printf("%16s ", thread__comm_str(thread));
420         }
421
422         if (PRINT_FIELD(PID) && PRINT_FIELD(TID))
423                 printf("%5d/%-5d ", sample->pid, sample->tid);
424         else if (PRINT_FIELD(PID))
425                 printf("%5d ", sample->pid);
426         else if (PRINT_FIELD(TID))
427                 printf("%5d ", sample->tid);
428
429         if (PRINT_FIELD(CPU)) {
430                 if (latency_format)
431                         printf("%3d ", sample->cpu);
432                 else
433                         printf("[%03d] ", sample->cpu);
434         }
435
436         if (PRINT_FIELD(TIME)) {
437                 nsecs = sample->time;
438                 secs = nsecs / NSECS_PER_SEC;
439                 nsecs -= secs * NSECS_PER_SEC;
440                 usecs = nsecs / NSECS_PER_USEC;
441                 if (nanosecs)
442                         printf("%5lu.%09llu: ", secs, nsecs);
443                 else
444                         printf("%5lu.%06lu: ", secs, usecs);
445         }
446 }
447
448 static inline char
449 mispred_str(struct branch_entry *br)
450 {
451         if (!(br->flags.mispred  || br->flags.predicted))
452                 return '-';
453
454         return br->flags.predicted ? 'P' : 'M';
455 }
456
457 static void print_sample_brstack(union perf_event *event __maybe_unused,
458                           struct perf_sample *sample,
459                           struct thread *thread __maybe_unused,
460                           struct perf_event_attr *attr __maybe_unused)
461 {
462         struct branch_stack *br = sample->branch_stack;
463         u64 i;
464
465         if (!(br && br->nr))
466                 return;
467
468         for (i = 0; i < br->nr; i++) {
469                 printf(" 0x%"PRIx64"/0x%"PRIx64"/%c/%c/%c/%d ",
470                         br->entries[i].from,
471                         br->entries[i].to,
472                         mispred_str( br->entries + i),
473                         br->entries[i].flags.in_tx? 'X' : '-',
474                         br->entries[i].flags.abort? 'A' : '-',
475                         br->entries[i].flags.cycles);
476         }
477 }
478
479 static void print_sample_brstacksym(union perf_event *event __maybe_unused,
480                           struct perf_sample *sample,
481                           struct thread *thread __maybe_unused,
482                           struct perf_event_attr *attr __maybe_unused)
483 {
484         struct branch_stack *br = sample->branch_stack;
485         struct addr_location alf, alt;
486         u8 cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
487         u64 i, from, to;
488
489         if (!(br && br->nr))
490                 return;
491
492         for (i = 0; i < br->nr; i++) {
493
494                 memset(&alf, 0, sizeof(alf));
495                 memset(&alt, 0, sizeof(alt));
496                 from = br->entries[i].from;
497                 to   = br->entries[i].to;
498
499                 thread__find_addr_map(thread, cpumode, MAP__FUNCTION, from, &alf);
500                 if (alf.map)
501                         alf.sym = map__find_symbol(alf.map, alf.addr, NULL);
502
503                 thread__find_addr_map(thread, cpumode, MAP__FUNCTION, to, &alt);
504                 if (alt.map)
505                         alt.sym = map__find_symbol(alt.map, alt.addr, NULL);
506
507                 symbol__fprintf_symname_offs(alf.sym, &alf, stdout);
508                 putchar('/');
509                 symbol__fprintf_symname_offs(alt.sym, &alt, stdout);
510                 printf("/%c/%c/%c/%d ",
511                         mispred_str( br->entries + i),
512                         br->entries[i].flags.in_tx? 'X' : '-',
513                         br->entries[i].flags.abort? 'A' : '-',
514                         br->entries[i].flags.cycles);
515         }
516 }
517
518
519 static void print_sample_addr(union perf_event *event,
520                           struct perf_sample *sample,
521                           struct thread *thread,
522                           struct perf_event_attr *attr)
523 {
524         struct addr_location al;
525
526         printf("%16" PRIx64, sample->addr);
527
528         if (!sample_addr_correlates_sym(attr))
529                 return;
530
531         perf_event__preprocess_sample_addr(event, sample, thread, &al);
532
533         if (PRINT_FIELD(SYM)) {
534                 printf(" ");
535                 if (PRINT_FIELD(SYMOFFSET))
536                         symbol__fprintf_symname_offs(al.sym, &al, stdout);
537                 else
538                         symbol__fprintf_symname(al.sym, stdout);
539         }
540
541         if (PRINT_FIELD(DSO)) {
542                 printf(" (");
543                 map__fprintf_dsoname(al.map, stdout);
544                 printf(")");
545         }
546 }
547
548 static void print_sample_bts(union perf_event *event,
549                              struct perf_sample *sample,
550                              struct perf_evsel *evsel,
551                              struct thread *thread,
552                              struct addr_location *al)
553 {
554         struct perf_event_attr *attr = &evsel->attr;
555         bool print_srcline_last = false;
556
557         /* print branch_from information */
558         if (PRINT_FIELD(IP)) {
559                 unsigned int print_opts = output[attr->type].print_ip_opts;
560
561                 if (symbol_conf.use_callchain && sample->callchain) {
562                         printf("\n");
563                 } else {
564                         printf(" ");
565                         if (print_opts & PRINT_IP_OPT_SRCLINE) {
566                                 print_srcline_last = true;
567                                 print_opts &= ~PRINT_IP_OPT_SRCLINE;
568                         }
569                 }
570                 perf_evsel__print_ip(evsel, sample, al, print_opts,
571                                      scripting_max_stack);
572         }
573
574         /* print branch_to information */
575         if (PRINT_FIELD(ADDR) ||
576             ((evsel->attr.sample_type & PERF_SAMPLE_ADDR) &&
577              !output[attr->type].user_set)) {
578                 printf(" => ");
579                 print_sample_addr(event, sample, thread, attr);
580         }
581
582         if (print_srcline_last)
583                 map__fprintf_srcline(al->map, al->addr, "\n  ", stdout);
584
585         printf("\n");
586 }
587
588 static void print_sample_flags(u32 flags)
589 {
590         const char *chars = PERF_IP_FLAG_CHARS;
591         const int n = strlen(PERF_IP_FLAG_CHARS);
592         char str[33];
593         int i, pos = 0;
594
595         for (i = 0; i < n; i++, flags >>= 1) {
596                 if (flags & 1)
597                         str[pos++] = chars[i];
598         }
599         for (; i < 32; i++, flags >>= 1) {
600                 if (flags & 1)
601                         str[pos++] = '?';
602         }
603         str[pos] = 0;
604         printf("  %-4s ", str);
605 }
606
607 struct perf_script {
608         struct perf_tool        tool;
609         struct perf_session     *session;
610         bool                    show_task_events;
611         bool                    show_mmap_events;
612         bool                    show_switch_events;
613         bool                    allocated;
614         struct cpu_map          *cpus;
615         struct thread_map       *threads;
616 };
617
618 static void process_event(struct perf_script *script __maybe_unused, union perf_event *event,
619                           struct perf_sample *sample, struct perf_evsel *evsel,
620                           struct addr_location *al)
621 {
622         struct thread *thread = al->thread;
623         struct perf_event_attr *attr = &evsel->attr;
624
625         if (output[attr->type].fields == 0)
626                 return;
627
628         print_sample_start(sample, thread, evsel);
629
630         if (PRINT_FIELD(PERIOD))
631                 printf("%10" PRIu64 " ", sample->period);
632
633         if (PRINT_FIELD(EVNAME)) {
634                 const char *evname = perf_evsel__name(evsel);
635                 printf("%s: ", evname ? evname : "[unknown]");
636         }
637
638         if (print_flags)
639                 print_sample_flags(sample->flags);
640
641         if (is_bts_event(attr)) {
642                 print_sample_bts(event, sample, evsel, thread, al);
643                 return;
644         }
645
646         if (PRINT_FIELD(TRACE))
647                 event_format__print(evsel->tp_format, sample->cpu,
648                                     sample->raw_data, sample->raw_size);
649         if (PRINT_FIELD(ADDR))
650                 print_sample_addr(event, sample, thread, attr);
651
652         if (PRINT_FIELD(IP)) {
653                 if (!symbol_conf.use_callchain)
654                         printf(" ");
655                 else
656                         printf("\n");
657
658                 perf_evsel__print_ip(evsel, sample, al,
659                                      output[attr->type].print_ip_opts,
660                                      scripting_max_stack);
661         }
662
663         if (PRINT_FIELD(IREGS))
664                 print_sample_iregs(event, sample, thread, attr);
665
666         if (PRINT_FIELD(BRSTACK))
667                 print_sample_brstack(event, sample, thread, attr);
668         else if (PRINT_FIELD(BRSTACKSYM))
669                 print_sample_brstacksym(event, sample, thread, attr);
670
671         printf("\n");
672 }
673
674 static struct scripting_ops     *scripting_ops;
675
676 static void setup_scripting(void)
677 {
678         setup_perl_scripting();
679         setup_python_scripting();
680 }
681
682 static int flush_scripting(void)
683 {
684         return scripting_ops ? scripting_ops->flush_script() : 0;
685 }
686
687 static int cleanup_scripting(void)
688 {
689         pr_debug("\nperf script stopped\n");
690
691         return scripting_ops ? scripting_ops->stop_script() : 0;
692 }
693
694 static int process_sample_event(struct perf_tool *tool,
695                                 union perf_event *event,
696                                 struct perf_sample *sample,
697                                 struct perf_evsel *evsel,
698                                 struct machine *machine)
699 {
700         struct perf_script *scr = container_of(tool, struct perf_script, tool);
701         struct addr_location al;
702
703         if (debug_mode) {
704                 if (sample->time < last_timestamp) {
705                         pr_err("Samples misordered, previous: %" PRIu64
706                                 " this: %" PRIu64 "\n", last_timestamp,
707                                 sample->time);
708                         nr_unordered++;
709                 }
710                 last_timestamp = sample->time;
711                 return 0;
712         }
713
714         if (perf_event__preprocess_sample(event, machine, &al, sample) < 0) {
715                 pr_err("problem processing %d event, skipping it.\n",
716                        event->header.type);
717                 return -1;
718         }
719
720         if (al.filtered)
721                 goto out_put;
722
723         if (cpu_list && !test_bit(sample->cpu, cpu_bitmap))
724                 goto out_put;
725
726         if (scripting_ops)
727                 scripting_ops->process_event(event, sample, evsel, &al);
728         else
729                 process_event(scr, event, sample, evsel, &al);
730
731 out_put:
732         addr_location__put(&al);
733         return 0;
734 }
735
736 static int process_attr(struct perf_tool *tool, union perf_event *event,
737                         struct perf_evlist **pevlist)
738 {
739         struct perf_script *scr = container_of(tool, struct perf_script, tool);
740         struct perf_evlist *evlist;
741         struct perf_evsel *evsel, *pos;
742         int err;
743
744         err = perf_event__process_attr(tool, event, pevlist);
745         if (err)
746                 return err;
747
748         evlist = *pevlist;
749         evsel = perf_evlist__last(*pevlist);
750
751         if (evsel->attr.type >= PERF_TYPE_MAX)
752                 return 0;
753
754         evlist__for_each(evlist, pos) {
755                 if (pos->attr.type == evsel->attr.type && pos != evsel)
756                         return 0;
757         }
758
759         set_print_ip_opts(&evsel->attr);
760
761         if (evsel->attr.sample_type)
762                 err = perf_evsel__check_attr(evsel, scr->session);
763
764         return err;
765 }
766
767 static int process_comm_event(struct perf_tool *tool,
768                               union perf_event *event,
769                               struct perf_sample *sample,
770                               struct machine *machine)
771 {
772         struct thread *thread;
773         struct perf_script *script = container_of(tool, struct perf_script, tool);
774         struct perf_session *session = script->session;
775         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
776         int ret = -1;
777
778         thread = machine__findnew_thread(machine, event->comm.pid, event->comm.tid);
779         if (thread == NULL) {
780                 pr_debug("problem processing COMM event, skipping it.\n");
781                 return -1;
782         }
783
784         if (perf_event__process_comm(tool, event, sample, machine) < 0)
785                 goto out;
786
787         if (!evsel->attr.sample_id_all) {
788                 sample->cpu = 0;
789                 sample->time = 0;
790                 sample->tid = event->comm.tid;
791                 sample->pid = event->comm.pid;
792         }
793         print_sample_start(sample, thread, evsel);
794         perf_event__fprintf(event, stdout);
795         ret = 0;
796 out:
797         thread__put(thread);
798         return ret;
799 }
800
801 static int process_fork_event(struct perf_tool *tool,
802                               union perf_event *event,
803                               struct perf_sample *sample,
804                               struct machine *machine)
805 {
806         struct thread *thread;
807         struct perf_script *script = container_of(tool, struct perf_script, tool);
808         struct perf_session *session = script->session;
809         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
810
811         if (perf_event__process_fork(tool, event, sample, machine) < 0)
812                 return -1;
813
814         thread = machine__findnew_thread(machine, event->fork.pid, event->fork.tid);
815         if (thread == NULL) {
816                 pr_debug("problem processing FORK event, skipping it.\n");
817                 return -1;
818         }
819
820         if (!evsel->attr.sample_id_all) {
821                 sample->cpu = 0;
822                 sample->time = event->fork.time;
823                 sample->tid = event->fork.tid;
824                 sample->pid = event->fork.pid;
825         }
826         print_sample_start(sample, thread, evsel);
827         perf_event__fprintf(event, stdout);
828         thread__put(thread);
829
830         return 0;
831 }
832 static int process_exit_event(struct perf_tool *tool,
833                               union perf_event *event,
834                               struct perf_sample *sample,
835                               struct machine *machine)
836 {
837         int err = 0;
838         struct thread *thread;
839         struct perf_script *script = container_of(tool, struct perf_script, tool);
840         struct perf_session *session = script->session;
841         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
842
843         thread = machine__findnew_thread(machine, event->fork.pid, event->fork.tid);
844         if (thread == NULL) {
845                 pr_debug("problem processing EXIT event, skipping it.\n");
846                 return -1;
847         }
848
849         if (!evsel->attr.sample_id_all) {
850                 sample->cpu = 0;
851                 sample->time = 0;
852                 sample->tid = event->fork.tid;
853                 sample->pid = event->fork.pid;
854         }
855         print_sample_start(sample, thread, evsel);
856         perf_event__fprintf(event, stdout);
857
858         if (perf_event__process_exit(tool, event, sample, machine) < 0)
859                 err = -1;
860
861         thread__put(thread);
862         return err;
863 }
864
865 static int process_mmap_event(struct perf_tool *tool,
866                               union perf_event *event,
867                               struct perf_sample *sample,
868                               struct machine *machine)
869 {
870         struct thread *thread;
871         struct perf_script *script = container_of(tool, struct perf_script, tool);
872         struct perf_session *session = script->session;
873         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
874
875         if (perf_event__process_mmap(tool, event, sample, machine) < 0)
876                 return -1;
877
878         thread = machine__findnew_thread(machine, event->mmap.pid, event->mmap.tid);
879         if (thread == NULL) {
880                 pr_debug("problem processing MMAP event, skipping it.\n");
881                 return -1;
882         }
883
884         if (!evsel->attr.sample_id_all) {
885                 sample->cpu = 0;
886                 sample->time = 0;
887                 sample->tid = event->mmap.tid;
888                 sample->pid = event->mmap.pid;
889         }
890         print_sample_start(sample, thread, evsel);
891         perf_event__fprintf(event, stdout);
892         thread__put(thread);
893         return 0;
894 }
895
896 static int process_mmap2_event(struct perf_tool *tool,
897                               union perf_event *event,
898                               struct perf_sample *sample,
899                               struct machine *machine)
900 {
901         struct thread *thread;
902         struct perf_script *script = container_of(tool, struct perf_script, tool);
903         struct perf_session *session = script->session;
904         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
905
906         if (perf_event__process_mmap2(tool, event, sample, machine) < 0)
907                 return -1;
908
909         thread = machine__findnew_thread(machine, event->mmap2.pid, event->mmap2.tid);
910         if (thread == NULL) {
911                 pr_debug("problem processing MMAP2 event, skipping it.\n");
912                 return -1;
913         }
914
915         if (!evsel->attr.sample_id_all) {
916                 sample->cpu = 0;
917                 sample->time = 0;
918                 sample->tid = event->mmap2.tid;
919                 sample->pid = event->mmap2.pid;
920         }
921         print_sample_start(sample, thread, evsel);
922         perf_event__fprintf(event, stdout);
923         thread__put(thread);
924         return 0;
925 }
926
927 static int process_switch_event(struct perf_tool *tool,
928                                 union perf_event *event,
929                                 struct perf_sample *sample,
930                                 struct machine *machine)
931 {
932         struct thread *thread;
933         struct perf_script *script = container_of(tool, struct perf_script, tool);
934         struct perf_session *session = script->session;
935         struct perf_evsel *evsel = perf_evlist__id2evsel(session->evlist, sample->id);
936
937         if (perf_event__process_switch(tool, event, sample, machine) < 0)
938                 return -1;
939
940         thread = machine__findnew_thread(machine, sample->pid,
941                                          sample->tid);
942         if (thread == NULL) {
943                 pr_debug("problem processing SWITCH event, skipping it.\n");
944                 return -1;
945         }
946
947         print_sample_start(sample, thread, evsel);
948         perf_event__fprintf(event, stdout);
949         thread__put(thread);
950         return 0;
951 }
952
953 static void sig_handler(int sig __maybe_unused)
954 {
955         session_done = 1;
956 }
957
958 static int __cmd_script(struct perf_script *script)
959 {
960         int ret;
961
962         signal(SIGINT, sig_handler);
963
964         /* override event processing functions */
965         if (script->show_task_events) {
966                 script->tool.comm = process_comm_event;
967                 script->tool.fork = process_fork_event;
968                 script->tool.exit = process_exit_event;
969         }
970         if (script->show_mmap_events) {
971                 script->tool.mmap = process_mmap_event;
972                 script->tool.mmap2 = process_mmap2_event;
973         }
974         if (script->show_switch_events)
975                 script->tool.context_switch = process_switch_event;
976
977         ret = perf_session__process_events(script->session);
978
979         if (debug_mode)
980                 pr_err("Misordered timestamps: %" PRIu64 "\n", nr_unordered);
981
982         return ret;
983 }
984
985 struct script_spec {
986         struct list_head        node;
987         struct scripting_ops    *ops;
988         char                    spec[0];
989 };
990
991 static LIST_HEAD(script_specs);
992
993 static struct script_spec *script_spec__new(const char *spec,
994                                             struct scripting_ops *ops)
995 {
996         struct script_spec *s = malloc(sizeof(*s) + strlen(spec) + 1);
997
998         if (s != NULL) {
999                 strcpy(s->spec, spec);
1000                 s->ops = ops;
1001         }
1002
1003         return s;
1004 }
1005
1006 static void script_spec__add(struct script_spec *s)
1007 {
1008         list_add_tail(&s->node, &script_specs);
1009 }
1010
1011 static struct script_spec *script_spec__find(const char *spec)
1012 {
1013         struct script_spec *s;
1014
1015         list_for_each_entry(s, &script_specs, node)
1016                 if (strcasecmp(s->spec, spec) == 0)
1017                         return s;
1018         return NULL;
1019 }
1020
1021 static struct script_spec *script_spec__findnew(const char *spec,
1022                                                 struct scripting_ops *ops)
1023 {
1024         struct script_spec *s = script_spec__find(spec);
1025
1026         if (s)
1027                 return s;
1028
1029         s = script_spec__new(spec, ops);
1030         if (!s)
1031                 return NULL;
1032
1033         script_spec__add(s);
1034
1035         return s;
1036 }
1037
1038 int script_spec_register(const char *spec, struct scripting_ops *ops)
1039 {
1040         struct script_spec *s;
1041
1042         s = script_spec__find(spec);
1043         if (s)
1044                 return -1;
1045
1046         s = script_spec__findnew(spec, ops);
1047         if (!s)
1048                 return -1;
1049
1050         return 0;
1051 }
1052
1053 static struct scripting_ops *script_spec__lookup(const char *spec)
1054 {
1055         struct script_spec *s = script_spec__find(spec);
1056         if (!s)
1057                 return NULL;
1058
1059         return s->ops;
1060 }
1061
1062 static void list_available_languages(void)
1063 {
1064         struct script_spec *s;
1065
1066         fprintf(stderr, "\n");
1067         fprintf(stderr, "Scripting language extensions (used in "
1068                 "perf script -s [spec:]script.[spec]):\n\n");
1069
1070         list_for_each_entry(s, &script_specs, node)
1071                 fprintf(stderr, "  %-42s [%s]\n", s->spec, s->ops->name);
1072
1073         fprintf(stderr, "\n");
1074 }
1075
1076 static int parse_scriptname(const struct option *opt __maybe_unused,
1077                             const char *str, int unset __maybe_unused)
1078 {
1079         char spec[PATH_MAX];
1080         const char *script, *ext;
1081         int len;
1082
1083         if (strcmp(str, "lang") == 0) {
1084                 list_available_languages();
1085                 exit(0);
1086         }
1087
1088         script = strchr(str, ':');
1089         if (script) {
1090                 len = script - str;
1091                 if (len >= PATH_MAX) {
1092                         fprintf(stderr, "invalid language specifier");
1093                         return -1;
1094                 }
1095                 strncpy(spec, str, len);
1096                 spec[len] = '\0';
1097                 scripting_ops = script_spec__lookup(spec);
1098                 if (!scripting_ops) {
1099                         fprintf(stderr, "invalid language specifier");
1100                         return -1;
1101                 }
1102                 script++;
1103         } else {
1104                 script = str;
1105                 ext = strrchr(script, '.');
1106                 if (!ext) {
1107                         fprintf(stderr, "invalid script extension");
1108                         return -1;
1109                 }
1110                 scripting_ops = script_spec__lookup(++ext);
1111                 if (!scripting_ops) {
1112                         fprintf(stderr, "invalid script extension");
1113                         return -1;
1114                 }
1115         }
1116
1117         script_name = strdup(script);
1118
1119         return 0;
1120 }
1121
1122 static int parse_output_fields(const struct option *opt __maybe_unused,
1123                             const char *arg, int unset __maybe_unused)
1124 {
1125         char *tok;
1126         int i, imax = ARRAY_SIZE(all_output_options);
1127         int j;
1128         int rc = 0;
1129         char *str = strdup(arg);
1130         int type = -1;
1131
1132         if (!str)
1133                 return -ENOMEM;
1134
1135         /* first word can state for which event type the user is specifying
1136          * the fields. If no type exists, the specified fields apply to all
1137          * event types found in the file minus the invalid fields for a type.
1138          */
1139         tok = strchr(str, ':');
1140         if (tok) {
1141                 *tok = '\0';
1142                 tok++;
1143                 if (!strcmp(str, "hw"))
1144                         type = PERF_TYPE_HARDWARE;
1145                 else if (!strcmp(str, "sw"))
1146                         type = PERF_TYPE_SOFTWARE;
1147                 else if (!strcmp(str, "trace"))
1148                         type = PERF_TYPE_TRACEPOINT;
1149                 else if (!strcmp(str, "raw"))
1150                         type = PERF_TYPE_RAW;
1151                 else if (!strcmp(str, "break"))
1152                         type = PERF_TYPE_BREAKPOINT;
1153                 else {
1154                         fprintf(stderr, "Invalid event type in field string.\n");
1155                         rc = -EINVAL;
1156                         goto out;
1157                 }
1158
1159                 if (output[type].user_set)
1160                         pr_warning("Overriding previous field request for %s events.\n",
1161                                    event_type(type));
1162
1163                 output[type].fields = 0;
1164                 output[type].user_set = true;
1165                 output[type].wildcard_set = false;
1166
1167         } else {
1168                 tok = str;
1169                 if (strlen(str) == 0) {
1170                         fprintf(stderr,
1171                                 "Cannot set fields to 'none' for all event types.\n");
1172                         rc = -EINVAL;
1173                         goto out;
1174                 }
1175
1176                 if (output_set_by_user())
1177                         pr_warning("Overriding previous field request for all events.\n");
1178
1179                 for (j = 0; j < PERF_TYPE_MAX; ++j) {
1180                         output[j].fields = 0;
1181                         output[j].user_set = true;
1182                         output[j].wildcard_set = true;
1183                 }
1184         }
1185
1186         for (tok = strtok(tok, ","); tok; tok = strtok(NULL, ",")) {
1187                 for (i = 0; i < imax; ++i) {
1188                         if (strcmp(tok, all_output_options[i].str) == 0)
1189                                 break;
1190                 }
1191                 if (i == imax && strcmp(tok, "flags") == 0) {
1192                         print_flags = true;
1193                         continue;
1194                 }
1195                 if (i == imax) {
1196                         fprintf(stderr, "Invalid field requested.\n");
1197                         rc = -EINVAL;
1198                         goto out;
1199                 }
1200
1201                 if (type == -1) {
1202                         /* add user option to all events types for
1203                          * which it is valid
1204                          */
1205                         for (j = 0; j < PERF_TYPE_MAX; ++j) {
1206                                 if (output[j].invalid_fields & all_output_options[i].field) {
1207                                         pr_warning("\'%s\' not valid for %s events. Ignoring.\n",
1208                                                    all_output_options[i].str, event_type(j));
1209                                 } else
1210                                         output[j].fields |= all_output_options[i].field;
1211                         }
1212                 } else {
1213                         if (output[type].invalid_fields & all_output_options[i].field) {
1214                                 fprintf(stderr, "\'%s\' not valid for %s events.\n",
1215                                          all_output_options[i].str, event_type(type));
1216
1217                                 rc = -EINVAL;
1218                                 goto out;
1219                         }
1220                         output[type].fields |= all_output_options[i].field;
1221                 }
1222         }
1223
1224         if (type >= 0) {
1225                 if (output[type].fields == 0) {
1226                         pr_debug("No fields requested for %s type. "
1227                                  "Events will not be displayed.\n", event_type(type));
1228                 }
1229         }
1230
1231 out:
1232         free(str);
1233         return rc;
1234 }
1235
1236 /* Helper function for filesystems that return a dent->d_type DT_UNKNOWN */
1237 static int is_directory(const char *base_path, const struct dirent *dent)
1238 {
1239         char path[PATH_MAX];
1240         struct stat st;
1241
1242         sprintf(path, "%s/%s", base_path, dent->d_name);
1243         if (stat(path, &st))
1244                 return 0;
1245
1246         return S_ISDIR(st.st_mode);
1247 }
1248
1249 #define for_each_lang(scripts_path, scripts_dir, lang_dirent, lang_next)\
1250         while (!readdir_r(scripts_dir, &lang_dirent, &lang_next) &&     \
1251                lang_next)                                               \
1252                 if ((lang_dirent.d_type == DT_DIR ||                    \
1253                      (lang_dirent.d_type == DT_UNKNOWN &&               \
1254                       is_directory(scripts_path, &lang_dirent))) &&     \
1255                     (strcmp(lang_dirent.d_name, ".")) &&                \
1256                     (strcmp(lang_dirent.d_name, "..")))
1257
1258 #define for_each_script(lang_path, lang_dir, script_dirent, script_next)\
1259         while (!readdir_r(lang_dir, &script_dirent, &script_next) &&    \
1260                script_next)                                             \
1261                 if (script_dirent.d_type != DT_DIR &&                   \
1262                     (script_dirent.d_type != DT_UNKNOWN ||              \
1263                      !is_directory(lang_path, &script_dirent)))
1264
1265
1266 #define RECORD_SUFFIX                   "-record"
1267 #define REPORT_SUFFIX                   "-report"
1268
1269 struct script_desc {
1270         struct list_head        node;
1271         char                    *name;
1272         char                    *half_liner;
1273         char                    *args;
1274 };
1275
1276 static LIST_HEAD(script_descs);
1277
1278 static struct script_desc *script_desc__new(const char *name)
1279 {
1280         struct script_desc *s = zalloc(sizeof(*s));
1281
1282         if (s != NULL && name)
1283                 s->name = strdup(name);
1284
1285         return s;
1286 }
1287
1288 static void script_desc__delete(struct script_desc *s)
1289 {
1290         zfree(&s->name);
1291         zfree(&s->half_liner);
1292         zfree(&s->args);
1293         free(s);
1294 }
1295
1296 static void script_desc__add(struct script_desc *s)
1297 {
1298         list_add_tail(&s->node, &script_descs);
1299 }
1300
1301 static struct script_desc *script_desc__find(const char *name)
1302 {
1303         struct script_desc *s;
1304
1305         list_for_each_entry(s, &script_descs, node)
1306                 if (strcasecmp(s->name, name) == 0)
1307                         return s;
1308         return NULL;
1309 }
1310
1311 static struct script_desc *script_desc__findnew(const char *name)
1312 {
1313         struct script_desc *s = script_desc__find(name);
1314
1315         if (s)
1316                 return s;
1317
1318         s = script_desc__new(name);
1319         if (!s)
1320                 goto out_delete_desc;
1321
1322         script_desc__add(s);
1323
1324         return s;
1325
1326 out_delete_desc:
1327         script_desc__delete(s);
1328
1329         return NULL;
1330 }
1331
1332 static const char *ends_with(const char *str, const char *suffix)
1333 {
1334         size_t suffix_len = strlen(suffix);
1335         const char *p = str;
1336
1337         if (strlen(str) > suffix_len) {
1338                 p = str + strlen(str) - suffix_len;
1339                 if (!strncmp(p, suffix, suffix_len))
1340                         return p;
1341         }
1342
1343         return NULL;
1344 }
1345
1346 static int read_script_info(struct script_desc *desc, const char *filename)
1347 {
1348         char line[BUFSIZ], *p;
1349         FILE *fp;
1350
1351         fp = fopen(filename, "r");
1352         if (!fp)
1353                 return -1;
1354
1355         while (fgets(line, sizeof(line), fp)) {
1356                 p = ltrim(line);
1357                 if (strlen(p) == 0)
1358                         continue;
1359                 if (*p != '#')
1360                         continue;
1361                 p++;
1362                 if (strlen(p) && *p == '!')
1363                         continue;
1364
1365                 p = ltrim(p);
1366                 if (strlen(p) && p[strlen(p) - 1] == '\n')
1367                         p[strlen(p) - 1] = '\0';
1368
1369                 if (!strncmp(p, "description:", strlen("description:"))) {
1370                         p += strlen("description:");
1371                         desc->half_liner = strdup(ltrim(p));
1372                         continue;
1373                 }
1374
1375                 if (!strncmp(p, "args:", strlen("args:"))) {
1376                         p += strlen("args:");
1377                         desc->args = strdup(ltrim(p));
1378                         continue;
1379                 }
1380         }
1381
1382         fclose(fp);
1383
1384         return 0;
1385 }
1386
1387 static char *get_script_root(struct dirent *script_dirent, const char *suffix)
1388 {
1389         char *script_root, *str;
1390
1391         script_root = strdup(script_dirent->d_name);
1392         if (!script_root)
1393                 return NULL;
1394
1395         str = (char *)ends_with(script_root, suffix);
1396         if (!str) {
1397                 free(script_root);
1398                 return NULL;
1399         }
1400
1401         *str = '\0';
1402         return script_root;
1403 }
1404
1405 static int list_available_scripts(const struct option *opt __maybe_unused,
1406                                   const char *s __maybe_unused,
1407                                   int unset __maybe_unused)
1408 {
1409         struct dirent *script_next, *lang_next, script_dirent, lang_dirent;
1410         char scripts_path[MAXPATHLEN];
1411         DIR *scripts_dir, *lang_dir;
1412         char script_path[MAXPATHLEN];
1413         char lang_path[MAXPATHLEN];
1414         struct script_desc *desc;
1415         char first_half[BUFSIZ];
1416         char *script_root;
1417
1418         snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
1419
1420         scripts_dir = opendir(scripts_path);
1421         if (!scripts_dir)
1422                 return -1;
1423
1424         for_each_lang(scripts_path, scripts_dir, lang_dirent, lang_next) {
1425                 snprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
1426                          lang_dirent.d_name);
1427                 lang_dir = opendir(lang_path);
1428                 if (!lang_dir)
1429                         continue;
1430
1431                 for_each_script(lang_path, lang_dir, script_dirent, script_next) {
1432                         script_root = get_script_root(&script_dirent, REPORT_SUFFIX);
1433                         if (script_root) {
1434                                 desc = script_desc__findnew(script_root);
1435                                 snprintf(script_path, MAXPATHLEN, "%s/%s",
1436                                          lang_path, script_dirent.d_name);
1437                                 read_script_info(desc, script_path);
1438                                 free(script_root);
1439                         }
1440                 }
1441         }
1442
1443         fprintf(stdout, "List of available trace scripts:\n");
1444         list_for_each_entry(desc, &script_descs, node) {
1445                 sprintf(first_half, "%s %s", desc->name,
1446                         desc->args ? desc->args : "");
1447                 fprintf(stdout, "  %-36s %s\n", first_half,
1448                         desc->half_liner ? desc->half_liner : "");
1449         }
1450
1451         exit(0);
1452 }
1453
1454 /*
1455  * Some scripts specify the required events in their "xxx-record" file,
1456  * this function will check if the events in perf.data match those
1457  * mentioned in the "xxx-record".
1458  *
1459  * Fixme: All existing "xxx-record" are all in good formats "-e event ",
1460  * which is covered well now. And new parsing code should be added to
1461  * cover the future complexing formats like event groups etc.
1462  */
1463 static int check_ev_match(char *dir_name, char *scriptname,
1464                         struct perf_session *session)
1465 {
1466         char filename[MAXPATHLEN], evname[128];
1467         char line[BUFSIZ], *p;
1468         struct perf_evsel *pos;
1469         int match, len;
1470         FILE *fp;
1471
1472         sprintf(filename, "%s/bin/%s-record", dir_name, scriptname);
1473
1474         fp = fopen(filename, "r");
1475         if (!fp)
1476                 return -1;
1477
1478         while (fgets(line, sizeof(line), fp)) {
1479                 p = ltrim(line);
1480                 if (*p == '#')
1481                         continue;
1482
1483                 while (strlen(p)) {
1484                         p = strstr(p, "-e");
1485                         if (!p)
1486                                 break;
1487
1488                         p += 2;
1489                         p = ltrim(p);
1490                         len = strcspn(p, " \t");
1491                         if (!len)
1492                                 break;
1493
1494                         snprintf(evname, len + 1, "%s", p);
1495
1496                         match = 0;
1497                         evlist__for_each(session->evlist, pos) {
1498                                 if (!strcmp(perf_evsel__name(pos), evname)) {
1499                                         match = 1;
1500                                         break;
1501                                 }
1502                         }
1503
1504                         if (!match) {
1505                                 fclose(fp);
1506                                 return -1;
1507                         }
1508                 }
1509         }
1510
1511         fclose(fp);
1512         return 0;
1513 }
1514
1515 /*
1516  * Return -1 if none is found, otherwise the actual scripts number.
1517  *
1518  * Currently the only user of this function is the script browser, which
1519  * will list all statically runnable scripts, select one, execute it and
1520  * show the output in a perf browser.
1521  */
1522 int find_scripts(char **scripts_array, char **scripts_path_array)
1523 {
1524         struct dirent *script_next, *lang_next, script_dirent, lang_dirent;
1525         char scripts_path[MAXPATHLEN], lang_path[MAXPATHLEN];
1526         DIR *scripts_dir, *lang_dir;
1527         struct perf_session *session;
1528         struct perf_data_file file = {
1529                 .path = input_name,
1530                 .mode = PERF_DATA_MODE_READ,
1531         };
1532         char *temp;
1533         int i = 0;
1534
1535         session = perf_session__new(&file, false, NULL);
1536         if (!session)
1537                 return -1;
1538
1539         snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
1540
1541         scripts_dir = opendir(scripts_path);
1542         if (!scripts_dir) {
1543                 perf_session__delete(session);
1544                 return -1;
1545         }
1546
1547         for_each_lang(scripts_path, scripts_dir, lang_dirent, lang_next) {
1548                 snprintf(lang_path, MAXPATHLEN, "%s/%s", scripts_path,
1549                          lang_dirent.d_name);
1550 #ifdef NO_LIBPERL
1551                 if (strstr(lang_path, "perl"))
1552                         continue;
1553 #endif
1554 #ifdef NO_LIBPYTHON
1555                 if (strstr(lang_path, "python"))
1556                         continue;
1557 #endif
1558
1559                 lang_dir = opendir(lang_path);
1560                 if (!lang_dir)
1561                         continue;
1562
1563                 for_each_script(lang_path, lang_dir, script_dirent, script_next) {
1564                         /* Skip those real time scripts: xxxtop.p[yl] */
1565                         if (strstr(script_dirent.d_name, "top."))
1566                                 continue;
1567                         sprintf(scripts_path_array[i], "%s/%s", lang_path,
1568                                 script_dirent.d_name);
1569                         temp = strchr(script_dirent.d_name, '.');
1570                         snprintf(scripts_array[i],
1571                                 (temp - script_dirent.d_name) + 1,
1572                                 "%s", script_dirent.d_name);
1573
1574                         if (check_ev_match(lang_path,
1575                                         scripts_array[i], session))
1576                                 continue;
1577
1578                         i++;
1579                 }
1580                 closedir(lang_dir);
1581         }
1582
1583         closedir(scripts_dir);
1584         perf_session__delete(session);
1585         return i;
1586 }
1587
1588 static char *get_script_path(const char *script_root, const char *suffix)
1589 {
1590         struct dirent *script_next, *lang_next, script_dirent, lang_dirent;
1591         char scripts_path[MAXPATHLEN];
1592         char script_path[MAXPATHLEN];
1593         DIR *scripts_dir, *lang_dir;
1594         char lang_path[MAXPATHLEN];
1595         char *__script_root;
1596
1597         snprintf(scripts_path, MAXPATHLEN, "%s/scripts", get_argv_exec_path());
1598
1599         scripts_dir = opendir(scripts_path);
1600         if (!scripts_dir)
1601                 return NULL;
1602
1603         for_each_lang(scripts_path, scripts_dir, lang_dirent, lang_next) {
1604                 snprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
1605                          lang_dirent.d_name);
1606                 lang_dir = opendir(lang_path);
1607                 if (!lang_dir)
1608                         continue;
1609
1610                 for_each_script(lang_path, lang_dir, script_dirent, script_next) {
1611                         __script_root = get_script_root(&script_dirent, suffix);
1612                         if (__script_root && !strcmp(script_root, __script_root)) {
1613                                 free(__script_root);
1614                                 closedir(lang_dir);
1615                                 closedir(scripts_dir);
1616                                 snprintf(script_path, MAXPATHLEN, "%s/%s",
1617                                          lang_path, script_dirent.d_name);
1618                                 return strdup(script_path);
1619                         }
1620                         free(__script_root);
1621                 }
1622                 closedir(lang_dir);
1623         }
1624         closedir(scripts_dir);
1625
1626         return NULL;
1627 }
1628
1629 static bool is_top_script(const char *script_path)
1630 {
1631         return ends_with(script_path, "top") == NULL ? false : true;
1632 }
1633
1634 static int has_required_arg(char *script_path)
1635 {
1636         struct script_desc *desc;
1637         int n_args = 0;
1638         char *p;
1639
1640         desc = script_desc__new(NULL);
1641
1642         if (read_script_info(desc, script_path))
1643                 goto out;
1644
1645         if (!desc->args)
1646                 goto out;
1647
1648         for (p = desc->args; *p; p++)
1649                 if (*p == '<')
1650                         n_args++;
1651 out:
1652         script_desc__delete(desc);
1653
1654         return n_args;
1655 }
1656
1657 static int have_cmd(int argc, const char **argv)
1658 {
1659         char **__argv = malloc(sizeof(const char *) * argc);
1660
1661         if (!__argv) {
1662                 pr_err("malloc failed\n");
1663                 return -1;
1664         }
1665
1666         memcpy(__argv, argv, sizeof(const char *) * argc);
1667         argc = parse_options(argc, (const char **)__argv, record_options,
1668                              NULL, PARSE_OPT_STOP_AT_NON_OPTION);
1669         free(__argv);
1670
1671         system_wide = (argc == 0);
1672
1673         return 0;
1674 }
1675
1676 static void script__setup_sample_type(struct perf_script *script)
1677 {
1678         struct perf_session *session = script->session;
1679         u64 sample_type = perf_evlist__combined_sample_type(session->evlist);
1680
1681         if (symbol_conf.use_callchain || symbol_conf.cumulate_callchain) {
1682                 if ((sample_type & PERF_SAMPLE_REGS_USER) &&
1683                     (sample_type & PERF_SAMPLE_STACK_USER))
1684                         callchain_param.record_mode = CALLCHAIN_DWARF;
1685                 else if (sample_type & PERF_SAMPLE_BRANCH_STACK)
1686                         callchain_param.record_mode = CALLCHAIN_LBR;
1687                 else
1688                         callchain_param.record_mode = CALLCHAIN_FP;
1689         }
1690 }
1691
1692 static int set_maps(struct perf_script *script)
1693 {
1694         struct perf_evlist *evlist = script->session->evlist;
1695
1696         if (!script->cpus || !script->threads)
1697                 return 0;
1698
1699         if (WARN_ONCE(script->allocated, "stats double allocation\n"))
1700                 return -EINVAL;
1701
1702         perf_evlist__set_maps(evlist, script->cpus, script->threads);
1703
1704         if (perf_evlist__alloc_stats(evlist, true))
1705                 return -ENOMEM;
1706
1707         script->allocated = true;
1708         return 0;
1709 }
1710
1711 static
1712 int process_thread_map_event(struct perf_tool *tool,
1713                              union perf_event *event,
1714                              struct perf_session *session __maybe_unused)
1715 {
1716         struct perf_script *script = container_of(tool, struct perf_script, tool);
1717
1718         if (script->threads) {
1719                 pr_warning("Extra thread map event, ignoring.\n");
1720                 return 0;
1721         }
1722
1723         script->threads = thread_map__new_event(&event->thread_map);
1724         if (!script->threads)
1725                 return -ENOMEM;
1726
1727         return set_maps(script);
1728 }
1729
1730 static
1731 int process_cpu_map_event(struct perf_tool *tool __maybe_unused,
1732                           union perf_event *event,
1733                           struct perf_session *session __maybe_unused)
1734 {
1735         struct perf_script *script = container_of(tool, struct perf_script, tool);
1736
1737         if (script->cpus) {
1738                 pr_warning("Extra cpu map event, ignoring.\n");
1739                 return 0;
1740         }
1741
1742         script->cpus = cpu_map__new_data(&event->cpu_map.data);
1743         if (!script->cpus)
1744                 return -ENOMEM;
1745
1746         return set_maps(script);
1747 }
1748
1749 int cmd_script(int argc, const char **argv, const char *prefix __maybe_unused)
1750 {
1751         bool show_full_info = false;
1752         bool header = false;
1753         bool header_only = false;
1754         bool script_started = false;
1755         char *rec_script_path = NULL;
1756         char *rep_script_path = NULL;
1757         struct perf_session *session;
1758         struct itrace_synth_opts itrace_synth_opts = { .set = false, };
1759         char *script_path = NULL;
1760         const char **__argv;
1761         int i, j, err = 0;
1762         struct perf_script script = {
1763                 .tool = {
1764                         .sample          = process_sample_event,
1765                         .mmap            = perf_event__process_mmap,
1766                         .mmap2           = perf_event__process_mmap2,
1767                         .comm            = perf_event__process_comm,
1768                         .exit            = perf_event__process_exit,
1769                         .fork            = perf_event__process_fork,
1770                         .attr            = process_attr,
1771                         .tracing_data    = perf_event__process_tracing_data,
1772                         .build_id        = perf_event__process_build_id,
1773                         .id_index        = perf_event__process_id_index,
1774                         .auxtrace_info   = perf_event__process_auxtrace_info,
1775                         .auxtrace        = perf_event__process_auxtrace,
1776                         .auxtrace_error  = perf_event__process_auxtrace_error,
1777                         .thread_map      = process_thread_map_event,
1778                         .cpu_map         = process_cpu_map_event,
1779                         .ordered_events  = true,
1780                         .ordering_requires_timestamps = true,
1781                 },
1782         };
1783         struct perf_data_file file = {
1784                 .mode = PERF_DATA_MODE_READ,
1785         };
1786         const struct option options[] = {
1787         OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
1788                     "dump raw trace in ASCII"),
1789         OPT_INCR('v', "verbose", &verbose,
1790                  "be more verbose (show symbol address, etc)"),
1791         OPT_BOOLEAN('L', "Latency", &latency_format,
1792                     "show latency attributes (irqs/preemption disabled, etc)"),
1793         OPT_CALLBACK_NOOPT('l', "list", NULL, NULL, "list available scripts",
1794                            list_available_scripts),
1795         OPT_CALLBACK('s', "script", NULL, "name",
1796                      "script file name (lang:script name, script name, or *)",
1797                      parse_scriptname),
1798         OPT_STRING('g', "gen-script", &generate_script_lang, "lang",
1799                    "generate perf-script.xx script in specified language"),
1800         OPT_STRING('i', "input", &input_name, "file", "input file name"),
1801         OPT_BOOLEAN('d', "debug-mode", &debug_mode,
1802                    "do various checks like samples ordering and lost events"),
1803         OPT_BOOLEAN(0, "header", &header, "Show data header."),
1804         OPT_BOOLEAN(0, "header-only", &header_only, "Show only data header."),
1805         OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
1806                    "file", "vmlinux pathname"),
1807         OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
1808                    "file", "kallsyms pathname"),
1809         OPT_BOOLEAN('G', "hide-call-graph", &no_callchain,
1810                     "When printing symbols do not display call chain"),
1811         OPT_STRING(0, "symfs", &symbol_conf.symfs, "directory",
1812                     "Look for files with symbols relative to this directory"),
1813         OPT_CALLBACK('F', "fields", NULL, "str",
1814                      "comma separated output fields prepend with 'type:'. "
1815                      "Valid types: hw,sw,trace,raw. "
1816                      "Fields: comm,tid,pid,time,cpu,event,trace,ip,sym,dso,"
1817                      "addr,symoff,period,iregs,brstack,brstacksym,flags", parse_output_fields),
1818         OPT_BOOLEAN('a', "all-cpus", &system_wide,
1819                     "system-wide collection from all CPUs"),
1820         OPT_STRING('S', "symbols", &symbol_conf.sym_list_str, "symbol[,symbol...]",
1821                    "only consider these symbols"),
1822         OPT_STRING('C', "cpu", &cpu_list, "cpu", "list of cpus to profile"),
1823         OPT_STRING('c', "comms", &symbol_conf.comm_list_str, "comm[,comm...]",
1824                    "only display events for these comms"),
1825         OPT_STRING(0, "pid", &symbol_conf.pid_list_str, "pid[,pid...]",
1826                    "only consider symbols in these pids"),
1827         OPT_STRING(0, "tid", &symbol_conf.tid_list_str, "tid[,tid...]",
1828                    "only consider symbols in these tids"),
1829         OPT_BOOLEAN('I', "show-info", &show_full_info,
1830                     "display extended information from perf.data file"),
1831         OPT_BOOLEAN('\0', "show-kernel-path", &symbol_conf.show_kernel_path,
1832                     "Show the path of [kernel.kallsyms]"),
1833         OPT_BOOLEAN('\0', "show-task-events", &script.show_task_events,
1834                     "Show the fork/comm/exit events"),
1835         OPT_BOOLEAN('\0', "show-mmap-events", &script.show_mmap_events,
1836                     "Show the mmap events"),
1837         OPT_BOOLEAN('\0', "show-switch-events", &script.show_switch_events,
1838                     "Show context switch events (if recorded)"),
1839         OPT_BOOLEAN('f', "force", &file.force, "don't complain, do it"),
1840         OPT_BOOLEAN(0, "ns", &nanosecs,
1841                     "Use 9 decimal places when displaying time"),
1842         OPT_CALLBACK_OPTARG(0, "itrace", &itrace_synth_opts, NULL, "opts",
1843                             "Instruction Tracing options",
1844                             itrace_parse_synth_opts),
1845         OPT_BOOLEAN(0, "full-source-path", &srcline_full_filename,
1846                         "Show full source file name path for source lines"),
1847         OPT_BOOLEAN(0, "demangle", &symbol_conf.demangle,
1848                         "Enable symbol demangling"),
1849         OPT_BOOLEAN(0, "demangle-kernel", &symbol_conf.demangle_kernel,
1850                         "Enable kernel symbol demangling"),
1851
1852         OPT_END()
1853         };
1854         const char * const script_subcommands[] = { "record", "report", NULL };
1855         const char *script_usage[] = {
1856                 "perf script [<options>]",
1857                 "perf script [<options>] record <script> [<record-options>] <command>",
1858                 "perf script [<options>] report <script> [script-args]",
1859                 "perf script [<options>] <script> [<record-options>] <command>",
1860                 "perf script [<options>] <top-script> [script-args]",
1861                 NULL
1862         };
1863
1864         setup_scripting();
1865
1866         argc = parse_options_subcommand(argc, argv, options, script_subcommands, script_usage,
1867                              PARSE_OPT_STOP_AT_NON_OPTION);
1868
1869         file.path = input_name;
1870
1871         if (argc > 1 && !strncmp(argv[0], "rec", strlen("rec"))) {
1872                 rec_script_path = get_script_path(argv[1], RECORD_SUFFIX);
1873                 if (!rec_script_path)
1874                         return cmd_record(argc, argv, NULL);
1875         }
1876
1877         if (argc > 1 && !strncmp(argv[0], "rep", strlen("rep"))) {
1878                 rep_script_path = get_script_path(argv[1], REPORT_SUFFIX);
1879                 if (!rep_script_path) {
1880                         fprintf(stderr,
1881                                 "Please specify a valid report script"
1882                                 "(see 'perf script -l' for listing)\n");
1883                         return -1;
1884                 }
1885         }
1886
1887         if (itrace_synth_opts.callchain &&
1888             itrace_synth_opts.callchain_sz > scripting_max_stack)
1889                 scripting_max_stack = itrace_synth_opts.callchain_sz;
1890
1891         /* make sure PERF_EXEC_PATH is set for scripts */
1892         set_argv_exec_path(get_argv_exec_path());
1893
1894         if (argc && !script_name && !rec_script_path && !rep_script_path) {
1895                 int live_pipe[2];
1896                 int rep_args;
1897                 pid_t pid;
1898
1899                 rec_script_path = get_script_path(argv[0], RECORD_SUFFIX);
1900                 rep_script_path = get_script_path(argv[0], REPORT_SUFFIX);
1901
1902                 if (!rec_script_path && !rep_script_path) {
1903                         usage_with_options_msg(script_usage, options,
1904                                 "Couldn't find script `%s'\n\n See perf"
1905                                 " script -l for available scripts.\n", argv[0]);
1906                 }
1907
1908                 if (is_top_script(argv[0])) {
1909                         rep_args = argc - 1;
1910                 } else {
1911                         int rec_args;
1912
1913                         rep_args = has_required_arg(rep_script_path);
1914                         rec_args = (argc - 1) - rep_args;
1915                         if (rec_args < 0) {
1916                                 usage_with_options_msg(script_usage, options,
1917                                         "`%s' script requires options."
1918                                         "\n\n See perf script -l for available "
1919                                         "scripts and options.\n", argv[0]);
1920                         }
1921                 }
1922
1923                 if (pipe(live_pipe) < 0) {
1924                         perror("failed to create pipe");
1925                         return -1;
1926                 }
1927
1928                 pid = fork();
1929                 if (pid < 0) {
1930                         perror("failed to fork");
1931                         return -1;
1932                 }
1933
1934                 if (!pid) {
1935                         j = 0;
1936
1937                         dup2(live_pipe[1], 1);
1938                         close(live_pipe[0]);
1939
1940                         if (is_top_script(argv[0])) {
1941                                 system_wide = true;
1942                         } else if (!system_wide) {
1943                                 if (have_cmd(argc - rep_args, &argv[rep_args]) != 0) {
1944                                         err = -1;
1945                                         goto out;
1946                                 }
1947                         }
1948
1949                         __argv = malloc((argc + 6) * sizeof(const char *));
1950                         if (!__argv) {
1951                                 pr_err("malloc failed\n");
1952                                 err = -ENOMEM;
1953                                 goto out;
1954                         }
1955
1956                         __argv[j++] = "/bin/sh";
1957                         __argv[j++] = rec_script_path;
1958                         if (system_wide)
1959                                 __argv[j++] = "-a";
1960                         __argv[j++] = "-q";
1961                         __argv[j++] = "-o";
1962                         __argv[j++] = "-";
1963                         for (i = rep_args + 1; i < argc; i++)
1964                                 __argv[j++] = argv[i];
1965                         __argv[j++] = NULL;
1966
1967                         execvp("/bin/sh", (char **)__argv);
1968                         free(__argv);
1969                         exit(-1);
1970                 }
1971
1972                 dup2(live_pipe[0], 0);
1973                 close(live_pipe[1]);
1974
1975                 __argv = malloc((argc + 4) * sizeof(const char *));
1976                 if (!__argv) {
1977                         pr_err("malloc failed\n");
1978                         err = -ENOMEM;
1979                         goto out;
1980                 }
1981
1982                 j = 0;
1983                 __argv[j++] = "/bin/sh";
1984                 __argv[j++] = rep_script_path;
1985                 for (i = 1; i < rep_args + 1; i++)
1986                         __argv[j++] = argv[i];
1987                 __argv[j++] = "-i";
1988                 __argv[j++] = "-";
1989                 __argv[j++] = NULL;
1990
1991                 execvp("/bin/sh", (char **)__argv);
1992                 free(__argv);
1993                 exit(-1);
1994         }
1995
1996         if (rec_script_path)
1997                 script_path = rec_script_path;
1998         if (rep_script_path)
1999                 script_path = rep_script_path;
2000
2001         if (script_path) {
2002                 j = 0;
2003
2004                 if (!rec_script_path)
2005                         system_wide = false;
2006                 else if (!system_wide) {
2007                         if (have_cmd(argc - 1, &argv[1]) != 0) {
2008                                 err = -1;
2009                                 goto out;
2010                         }
2011                 }
2012
2013                 __argv = malloc((argc + 2) * sizeof(const char *));
2014                 if (!__argv) {
2015                         pr_err("malloc failed\n");
2016                         err = -ENOMEM;
2017                         goto out;
2018                 }
2019
2020                 __argv[j++] = "/bin/sh";
2021                 __argv[j++] = script_path;
2022                 if (system_wide)
2023                         __argv[j++] = "-a";
2024                 for (i = 2; i < argc; i++)
2025                         __argv[j++] = argv[i];
2026                 __argv[j++] = NULL;
2027
2028                 execvp("/bin/sh", (char **)__argv);
2029                 free(__argv);
2030                 exit(-1);
2031         }
2032
2033         if (!script_name)
2034                 setup_pager();
2035
2036         session = perf_session__new(&file, false, &script.tool);
2037         if (session == NULL)
2038                 return -1;
2039
2040         if (header || header_only) {
2041                 perf_session__fprintf_info(session, stdout, show_full_info);
2042                 if (header_only)
2043                         goto out_delete;
2044         }
2045
2046         if (symbol__init(&session->header.env) < 0)
2047                 goto out_delete;
2048
2049         script.session = session;
2050         script__setup_sample_type(&script);
2051
2052         session->itrace_synth_opts = &itrace_synth_opts;
2053
2054         if (cpu_list) {
2055                 err = perf_session__cpu_bitmap(session, cpu_list, cpu_bitmap);
2056                 if (err < 0)
2057                         goto out_delete;
2058         }
2059
2060         if (!no_callchain)
2061                 symbol_conf.use_callchain = true;
2062         else
2063                 symbol_conf.use_callchain = false;
2064
2065         if (session->tevent.pevent &&
2066             pevent_set_function_resolver(session->tevent.pevent,
2067                                          machine__resolve_kernel_addr,
2068                                          &session->machines.host) < 0) {
2069                 pr_err("%s: failed to set libtraceevent function resolver\n", __func__);
2070                 return -1;
2071         }
2072
2073         if (generate_script_lang) {
2074                 struct stat perf_stat;
2075                 int input;
2076
2077                 if (output_set_by_user()) {
2078                         fprintf(stderr,
2079                                 "custom fields not supported for generated scripts");
2080                         err = -EINVAL;
2081                         goto out_delete;
2082                 }
2083
2084                 input = open(file.path, O_RDONLY);      /* input_name */
2085                 if (input < 0) {
2086                         err = -errno;
2087                         perror("failed to open file");
2088                         goto out_delete;
2089                 }
2090
2091                 err = fstat(input, &perf_stat);
2092                 if (err < 0) {
2093                         perror("failed to stat file");
2094                         goto out_delete;
2095                 }
2096
2097                 if (!perf_stat.st_size) {
2098                         fprintf(stderr, "zero-sized file, nothing to do!\n");
2099                         goto out_delete;
2100                 }
2101
2102                 scripting_ops = script_spec__lookup(generate_script_lang);
2103                 if (!scripting_ops) {
2104                         fprintf(stderr, "invalid language specifier");
2105                         err = -ENOENT;
2106                         goto out_delete;
2107                 }
2108
2109                 err = scripting_ops->generate_script(session->tevent.pevent,
2110                                                      "perf-script");
2111                 goto out_delete;
2112         }
2113
2114         if (script_name) {
2115                 err = scripting_ops->start_script(script_name, argc, argv);
2116                 if (err)
2117                         goto out_delete;
2118                 pr_debug("perf script started with script %s\n\n", script_name);
2119                 script_started = true;
2120         }
2121
2122
2123         err = perf_session__check_output_opt(session);
2124         if (err < 0)
2125                 goto out_delete;
2126
2127         err = __cmd_script(&script);
2128
2129         flush_scripting();
2130
2131 out_delete:
2132         perf_evlist__free_stats(session->evlist);
2133         perf_session__delete(session);
2134
2135         if (script_started)
2136                 cleanup_scripting();
2137 out:
2138         return err;
2139 }