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