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