perf tools: make -C consistent across commands (for cpu list arg)
[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/session.h"
10 #include "util/tool.h"
11 #include "util/symbol.h"
12 #include "util/thread.h"
13 #include "util/trace-event.h"
14 #include "util/util.h"
15 #include "util/evlist.h"
16 #include "util/evsel.h"
17 #include <linux/bitmap.h>
18
19 static char const               *script_name;
20 static char const               *generate_script_lang;
21 static bool                     debug_mode;
22 static u64                      last_timestamp;
23 static u64                      nr_unordered;
24 extern const struct option      record_options[];
25 static bool                     no_callchain;
26 static bool                     show_full_info;
27 static const char               *cpu_list;
28 static DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
29
30 enum perf_output_field {
31         PERF_OUTPUT_COMM            = 1U << 0,
32         PERF_OUTPUT_TID             = 1U << 1,
33         PERF_OUTPUT_PID             = 1U << 2,
34         PERF_OUTPUT_TIME            = 1U << 3,
35         PERF_OUTPUT_CPU             = 1U << 4,
36         PERF_OUTPUT_EVNAME          = 1U << 5,
37         PERF_OUTPUT_TRACE           = 1U << 6,
38         PERF_OUTPUT_IP              = 1U << 7,
39         PERF_OUTPUT_SYM             = 1U << 8,
40         PERF_OUTPUT_DSO             = 1U << 9,
41         PERF_OUTPUT_ADDR            = 1U << 10,
42 };
43
44 struct output_option {
45         const char *str;
46         enum perf_output_field field;
47 } all_output_options[] = {
48         {.str = "comm",  .field = PERF_OUTPUT_COMM},
49         {.str = "tid",   .field = PERF_OUTPUT_TID},
50         {.str = "pid",   .field = PERF_OUTPUT_PID},
51         {.str = "time",  .field = PERF_OUTPUT_TIME},
52         {.str = "cpu",   .field = PERF_OUTPUT_CPU},
53         {.str = "event", .field = PERF_OUTPUT_EVNAME},
54         {.str = "trace", .field = PERF_OUTPUT_TRACE},
55         {.str = "ip",    .field = PERF_OUTPUT_IP},
56         {.str = "sym",   .field = PERF_OUTPUT_SYM},
57         {.str = "dso",   .field = PERF_OUTPUT_DSO},
58         {.str = "addr",  .field = PERF_OUTPUT_ADDR},
59 };
60
61 /* default set to maintain compatibility with current format */
62 static struct {
63         bool user_set;
64         bool wildcard_set;
65         u64 fields;
66         u64 invalid_fields;
67 } output[PERF_TYPE_MAX] = {
68
69         [PERF_TYPE_HARDWARE] = {
70                 .user_set = false,
71
72                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
73                               PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
74                               PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
75                                   PERF_OUTPUT_SYM | PERF_OUTPUT_DSO,
76
77                 .invalid_fields = PERF_OUTPUT_TRACE,
78         },
79
80         [PERF_TYPE_SOFTWARE] = {
81                 .user_set = false,
82
83                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
84                               PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
85                               PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
86                                   PERF_OUTPUT_SYM | PERF_OUTPUT_DSO,
87
88                 .invalid_fields = PERF_OUTPUT_TRACE,
89         },
90
91         [PERF_TYPE_TRACEPOINT] = {
92                 .user_set = false,
93
94                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
95                                   PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
96                                   PERF_OUTPUT_EVNAME | PERF_OUTPUT_TRACE,
97         },
98
99         [PERF_TYPE_RAW] = {
100                 .user_set = false,
101
102                 .fields = PERF_OUTPUT_COMM | PERF_OUTPUT_TID |
103                               PERF_OUTPUT_CPU | PERF_OUTPUT_TIME |
104                               PERF_OUTPUT_EVNAME | PERF_OUTPUT_IP |
105                                   PERF_OUTPUT_SYM | PERF_OUTPUT_DSO,
106
107                 .invalid_fields = PERF_OUTPUT_TRACE,
108         },
109 };
110
111 static bool output_set_by_user(void)
112 {
113         int j;
114         for (j = 0; j < PERF_TYPE_MAX; ++j) {
115                 if (output[j].user_set)
116                         return true;
117         }
118         return false;
119 }
120
121 static const char *output_field2str(enum perf_output_field field)
122 {
123         int i, imax = ARRAY_SIZE(all_output_options);
124         const char *str = "";
125
126         for (i = 0; i < imax; ++i) {
127                 if (all_output_options[i].field == field) {
128                         str = all_output_options[i].str;
129                         break;
130                 }
131         }
132         return str;
133 }
134
135 #define PRINT_FIELD(x)  (output[attr->type].fields & PERF_OUTPUT_##x)
136
137 static int perf_event_attr__check_stype(struct perf_event_attr *attr,
138                                   u64 sample_type, const char *sample_msg,
139                                   enum perf_output_field field)
140 {
141         int type = attr->type;
142         const char *evname;
143
144         if (attr->sample_type & sample_type)
145                 return 0;
146
147         if (output[type].user_set) {
148                 evname = __event_name(attr->type, attr->config);
149                 pr_err("Samples for '%s' event do not have %s attribute set. "
150                        "Cannot print '%s' field.\n",
151                        evname, sample_msg, output_field2str(field));
152                 return -1;
153         }
154
155         /* user did not ask for it explicitly so remove from the default list */
156         output[type].fields &= ~field;
157         evname = __event_name(attr->type, attr->config);
158         pr_debug("Samples for '%s' event do not have %s attribute set. "
159                  "Skipping '%s' field.\n",
160                  evname, sample_msg, output_field2str(field));
161
162         return 0;
163 }
164
165 static int perf_evsel__check_attr(struct perf_evsel *evsel,
166                                   struct perf_session *session)
167 {
168         struct perf_event_attr *attr = &evsel->attr;
169
170         if (PRINT_FIELD(TRACE) &&
171                 !perf_session__has_traces(session, "record -R"))
172                 return -EINVAL;
173
174         if (PRINT_FIELD(IP)) {
175                 if (perf_event_attr__check_stype(attr, PERF_SAMPLE_IP, "IP",
176                                            PERF_OUTPUT_IP))
177                         return -EINVAL;
178
179                 if (!no_callchain &&
180                     !(attr->sample_type & PERF_SAMPLE_CALLCHAIN))
181                         symbol_conf.use_callchain = false;
182         }
183
184         if (PRINT_FIELD(ADDR) &&
185                 perf_event_attr__check_stype(attr, PERF_SAMPLE_ADDR, "ADDR",
186                                        PERF_OUTPUT_ADDR))
187                 return -EINVAL;
188
189         if (PRINT_FIELD(SYM) && !PRINT_FIELD(IP) && !PRINT_FIELD(ADDR)) {
190                 pr_err("Display of symbols requested but neither sample IP nor "
191                            "sample address\nis selected. Hence, no addresses to convert "
192                        "to symbols.\n");
193                 return -EINVAL;
194         }
195         if (PRINT_FIELD(DSO) && !PRINT_FIELD(IP) && !PRINT_FIELD(ADDR)) {
196                 pr_err("Display of DSO requested but neither sample IP nor "
197                            "sample address\nis selected. Hence, no addresses to convert "
198                        "to DSO.\n");
199                 return -EINVAL;
200         }
201
202         if ((PRINT_FIELD(PID) || PRINT_FIELD(TID)) &&
203                 perf_event_attr__check_stype(attr, PERF_SAMPLE_TID, "TID",
204                                        PERF_OUTPUT_TID|PERF_OUTPUT_PID))
205                 return -EINVAL;
206
207         if (PRINT_FIELD(TIME) &&
208                 perf_event_attr__check_stype(attr, PERF_SAMPLE_TIME, "TIME",
209                                        PERF_OUTPUT_TIME))
210                 return -EINVAL;
211
212         if (PRINT_FIELD(CPU) &&
213                 perf_event_attr__check_stype(attr, PERF_SAMPLE_CPU, "CPU",
214                                        PERF_OUTPUT_CPU))
215                 return -EINVAL;
216
217         return 0;
218 }
219
220 /*
221  * verify all user requested events exist and the samples
222  * have the expected data
223  */
224 static int perf_session__check_output_opt(struct perf_session *session)
225 {
226         int j;
227         struct perf_evsel *evsel;
228
229         for (j = 0; j < PERF_TYPE_MAX; ++j) {
230                 evsel = perf_session__find_first_evtype(session, j);
231
232                 /*
233                  * even if fields is set to 0 (ie., show nothing) event must
234                  * exist if user explicitly includes it on the command line
235                  */
236                 if (!evsel && output[j].user_set && !output[j].wildcard_set) {
237                         pr_err("%s events do not exist. "
238                                "Remove corresponding -f option to proceed.\n",
239                                event_type(j));
240                         return -1;
241                 }
242
243                 if (evsel && output[j].fields &&
244                         perf_evsel__check_attr(evsel, session))
245                         return -1;
246         }
247
248         return 0;
249 }
250
251 static void print_sample_start(struct perf_sample *sample,
252                                struct thread *thread,
253                                struct perf_event_attr *attr)
254 {
255         int type;
256         struct event *event;
257         const char *evname = NULL;
258         unsigned long secs;
259         unsigned long usecs;
260         unsigned long long nsecs;
261
262         if (PRINT_FIELD(COMM)) {
263                 if (latency_format)
264                         printf("%8.8s ", thread->comm);
265                 else if (PRINT_FIELD(IP) && symbol_conf.use_callchain)
266                         printf("%s ", thread->comm);
267                 else
268                         printf("%16s ", thread->comm);
269         }
270
271         if (PRINT_FIELD(PID) && PRINT_FIELD(TID))
272                 printf("%5d/%-5d ", sample->pid, sample->tid);
273         else if (PRINT_FIELD(PID))
274                 printf("%5d ", sample->pid);
275         else if (PRINT_FIELD(TID))
276                 printf("%5d ", sample->tid);
277
278         if (PRINT_FIELD(CPU)) {
279                 if (latency_format)
280                         printf("%3d ", sample->cpu);
281                 else
282                         printf("[%03d] ", sample->cpu);
283         }
284
285         if (PRINT_FIELD(TIME)) {
286                 nsecs = sample->time;
287                 secs = nsecs / NSECS_PER_SEC;
288                 nsecs -= secs * NSECS_PER_SEC;
289                 usecs = nsecs / NSECS_PER_USEC;
290                 printf("%5lu.%06lu: ", secs, usecs);
291         }
292
293         if (PRINT_FIELD(EVNAME)) {
294                 if (attr->type == PERF_TYPE_TRACEPOINT) {
295                         type = trace_parse_common_type(sample->raw_data);
296                         event = trace_find_event(type);
297                         if (event)
298                                 evname = event->name;
299                 } else
300                         evname = __event_name(attr->type, attr->config);
301
302                 printf("%s: ", evname ? evname : "(unknown)");
303         }
304 }
305
306 static bool sample_addr_correlates_sym(struct perf_event_attr *attr)
307 {
308         if ((attr->type == PERF_TYPE_SOFTWARE) &&
309             ((attr->config == PERF_COUNT_SW_PAGE_FAULTS) ||
310              (attr->config == PERF_COUNT_SW_PAGE_FAULTS_MIN) ||
311              (attr->config == PERF_COUNT_SW_PAGE_FAULTS_MAJ)))
312                 return true;
313
314         return false;
315 }
316
317 static void print_sample_addr(union perf_event *event,
318                           struct perf_sample *sample,
319                           struct machine *machine,
320                           struct thread *thread,
321                           struct perf_event_attr *attr)
322 {
323         struct addr_location al;
324         u8 cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
325         const char *symname, *dsoname;
326
327         printf("%16" PRIx64, sample->addr);
328
329         if (!sample_addr_correlates_sym(attr))
330                 return;
331
332         thread__find_addr_map(thread, machine, cpumode, MAP__FUNCTION,
333                               sample->addr, &al);
334         if (!al.map)
335                 thread__find_addr_map(thread, machine, cpumode, MAP__VARIABLE,
336                                       sample->addr, &al);
337
338         al.cpu = sample->cpu;
339         al.sym = NULL;
340
341         if (al.map)
342                 al.sym = map__find_symbol(al.map, al.addr, NULL);
343
344         if (PRINT_FIELD(SYM)) {
345                 if (al.sym && al.sym->name)
346                         symname = al.sym->name;
347                 else
348                         symname = "";
349
350                 printf(" %16s", symname);
351         }
352
353         if (PRINT_FIELD(DSO)) {
354                 if (al.map && al.map->dso && al.map->dso->name)
355                         dsoname = al.map->dso->name;
356                 else
357                         dsoname = "";
358
359                 printf(" (%s)", dsoname);
360         }
361 }
362
363 static void process_event(union perf_event *event __unused,
364                           struct perf_sample *sample,
365                           struct perf_evsel *evsel,
366                           struct machine *machine,
367                           struct thread *thread)
368 {
369         struct perf_event_attr *attr = &evsel->attr;
370
371         if (output[attr->type].fields == 0)
372                 return;
373
374         print_sample_start(sample, thread, attr);
375
376         if (PRINT_FIELD(TRACE))
377                 print_trace_event(sample->cpu, sample->raw_data,
378                                   sample->raw_size);
379
380         if (PRINT_FIELD(ADDR))
381                 print_sample_addr(event, sample, machine, thread, attr);
382
383         if (PRINT_FIELD(IP)) {
384                 if (!symbol_conf.use_callchain)
385                         printf(" ");
386                 else
387                         printf("\n");
388                 perf_event__print_ip(event, sample, machine, evsel,
389                                      PRINT_FIELD(SYM), PRINT_FIELD(DSO));
390         }
391
392         printf("\n");
393 }
394
395 static int default_start_script(const char *script __unused,
396                                 int argc __unused,
397                                 const char **argv __unused)
398 {
399         return 0;
400 }
401
402 static int default_stop_script(void)
403 {
404         return 0;
405 }
406
407 static int default_generate_script(const char *outfile __unused)
408 {
409         return 0;
410 }
411
412 static struct scripting_ops default_scripting_ops = {
413         .start_script           = default_start_script,
414         .stop_script            = default_stop_script,
415         .process_event          = process_event,
416         .generate_script        = default_generate_script,
417 };
418
419 static struct scripting_ops     *scripting_ops;
420
421 static void setup_scripting(void)
422 {
423         setup_perl_scripting();
424         setup_python_scripting();
425
426         scripting_ops = &default_scripting_ops;
427 }
428
429 static int cleanup_scripting(void)
430 {
431         pr_debug("\nperf script stopped\n");
432
433         return scripting_ops->stop_script();
434 }
435
436 static char const               *input_name = "perf.data";
437
438 static int process_sample_event(struct perf_tool *tool __used,
439                                 union perf_event *event,
440                                 struct perf_sample *sample,
441                                 struct perf_evsel *evsel,
442                                 struct machine *machine)
443 {
444         struct thread *thread = machine__findnew_thread(machine, event->ip.pid);
445
446         if (thread == NULL) {
447                 pr_debug("problem processing %d event, skipping it.\n",
448                          event->header.type);
449                 return -1;
450         }
451
452         if (debug_mode) {
453                 if (sample->time < last_timestamp) {
454                         pr_err("Samples misordered, previous: %" PRIu64
455                                 " this: %" PRIu64 "\n", last_timestamp,
456                                 sample->time);
457                         nr_unordered++;
458                 }
459                 last_timestamp = sample->time;
460                 return 0;
461         }
462
463         if (cpu_list && !test_bit(sample->cpu, cpu_bitmap))
464                 return 0;
465
466         scripting_ops->process_event(event, sample, evsel, machine, thread);
467
468         evsel->hists.stats.total_period += sample->period;
469         return 0;
470 }
471
472 static struct perf_tool perf_script = {
473         .sample          = process_sample_event,
474         .mmap            = perf_event__process_mmap,
475         .comm            = perf_event__process_comm,
476         .exit            = perf_event__process_task,
477         .fork            = perf_event__process_task,
478         .attr            = perf_event__process_attr,
479         .event_type      = perf_event__process_event_type,
480         .tracing_data    = perf_event__process_tracing_data,
481         .build_id        = perf_event__process_build_id,
482         .ordered_samples = true,
483         .ordering_requires_timestamps = true,
484 };
485
486 extern volatile int session_done;
487
488 static void sig_handler(int sig __unused)
489 {
490         session_done = 1;
491 }
492
493 static int __cmd_script(struct perf_session *session)
494 {
495         int ret;
496
497         signal(SIGINT, sig_handler);
498
499         ret = perf_session__process_events(session, &perf_script);
500
501         if (debug_mode)
502                 pr_err("Misordered timestamps: %" PRIu64 "\n", nr_unordered);
503
504         return ret;
505 }
506
507 struct script_spec {
508         struct list_head        node;
509         struct scripting_ops    *ops;
510         char                    spec[0];
511 };
512
513 static LIST_HEAD(script_specs);
514
515 static struct script_spec *script_spec__new(const char *spec,
516                                             struct scripting_ops *ops)
517 {
518         struct script_spec *s = malloc(sizeof(*s) + strlen(spec) + 1);
519
520         if (s != NULL) {
521                 strcpy(s->spec, spec);
522                 s->ops = ops;
523         }
524
525         return s;
526 }
527
528 static void script_spec__delete(struct script_spec *s)
529 {
530         free(s->spec);
531         free(s);
532 }
533
534 static void script_spec__add(struct script_spec *s)
535 {
536         list_add_tail(&s->node, &script_specs);
537 }
538
539 static struct script_spec *script_spec__find(const char *spec)
540 {
541         struct script_spec *s;
542
543         list_for_each_entry(s, &script_specs, node)
544                 if (strcasecmp(s->spec, spec) == 0)
545                         return s;
546         return NULL;
547 }
548
549 static struct script_spec *script_spec__findnew(const char *spec,
550                                                 struct scripting_ops *ops)
551 {
552         struct script_spec *s = script_spec__find(spec);
553
554         if (s)
555                 return s;
556
557         s = script_spec__new(spec, ops);
558         if (!s)
559                 goto out_delete_spec;
560
561         script_spec__add(s);
562
563         return s;
564
565 out_delete_spec:
566         script_spec__delete(s);
567
568         return NULL;
569 }
570
571 int script_spec_register(const char *spec, struct scripting_ops *ops)
572 {
573         struct script_spec *s;
574
575         s = script_spec__find(spec);
576         if (s)
577                 return -1;
578
579         s = script_spec__findnew(spec, ops);
580         if (!s)
581                 return -1;
582
583         return 0;
584 }
585
586 static struct scripting_ops *script_spec__lookup(const char *spec)
587 {
588         struct script_spec *s = script_spec__find(spec);
589         if (!s)
590                 return NULL;
591
592         return s->ops;
593 }
594
595 static void list_available_languages(void)
596 {
597         struct script_spec *s;
598
599         fprintf(stderr, "\n");
600         fprintf(stderr, "Scripting language extensions (used in "
601                 "perf script -s [spec:]script.[spec]):\n\n");
602
603         list_for_each_entry(s, &script_specs, node)
604                 fprintf(stderr, "  %-42s [%s]\n", s->spec, s->ops->name);
605
606         fprintf(stderr, "\n");
607 }
608
609 static int parse_scriptname(const struct option *opt __used,
610                             const char *str, int unset __used)
611 {
612         char spec[PATH_MAX];
613         const char *script, *ext;
614         int len;
615
616         if (strcmp(str, "lang") == 0) {
617                 list_available_languages();
618                 exit(0);
619         }
620
621         script = strchr(str, ':');
622         if (script) {
623                 len = script - str;
624                 if (len >= PATH_MAX) {
625                         fprintf(stderr, "invalid language specifier");
626                         return -1;
627                 }
628                 strncpy(spec, str, len);
629                 spec[len] = '\0';
630                 scripting_ops = script_spec__lookup(spec);
631                 if (!scripting_ops) {
632                         fprintf(stderr, "invalid language specifier");
633                         return -1;
634                 }
635                 script++;
636         } else {
637                 script = str;
638                 ext = strrchr(script, '.');
639                 if (!ext) {
640                         fprintf(stderr, "invalid script extension");
641                         return -1;
642                 }
643                 scripting_ops = script_spec__lookup(++ext);
644                 if (!scripting_ops) {
645                         fprintf(stderr, "invalid script extension");
646                         return -1;
647                 }
648         }
649
650         script_name = strdup(script);
651
652         return 0;
653 }
654
655 static int parse_output_fields(const struct option *opt __used,
656                             const char *arg, int unset __used)
657 {
658         char *tok;
659         int i, imax = sizeof(all_output_options) / sizeof(struct output_option);
660         int j;
661         int rc = 0;
662         char *str = strdup(arg);
663         int type = -1;
664
665         if (!str)
666                 return -ENOMEM;
667
668         /* first word can state for which event type the user is specifying
669          * the fields. If no type exists, the specified fields apply to all
670          * event types found in the file minus the invalid fields for a type.
671          */
672         tok = strchr(str, ':');
673         if (tok) {
674                 *tok = '\0';
675                 tok++;
676                 if (!strcmp(str, "hw"))
677                         type = PERF_TYPE_HARDWARE;
678                 else if (!strcmp(str, "sw"))
679                         type = PERF_TYPE_SOFTWARE;
680                 else if (!strcmp(str, "trace"))
681                         type = PERF_TYPE_TRACEPOINT;
682                 else if (!strcmp(str, "raw"))
683                         type = PERF_TYPE_RAW;
684                 else {
685                         fprintf(stderr, "Invalid event type in field string.\n");
686                         return -EINVAL;
687                 }
688
689                 if (output[type].user_set)
690                         pr_warning("Overriding previous field request for %s events.\n",
691                                    event_type(type));
692
693                 output[type].fields = 0;
694                 output[type].user_set = true;
695                 output[type].wildcard_set = false;
696
697         } else {
698                 tok = str;
699                 if (strlen(str) == 0) {
700                         fprintf(stderr,
701                                 "Cannot set fields to 'none' for all event types.\n");
702                         rc = -EINVAL;
703                         goto out;
704                 }
705
706                 if (output_set_by_user())
707                         pr_warning("Overriding previous field request for all events.\n");
708
709                 for (j = 0; j < PERF_TYPE_MAX; ++j) {
710                         output[j].fields = 0;
711                         output[j].user_set = true;
712                         output[j].wildcard_set = true;
713                 }
714         }
715
716         tok = strtok(tok, ",");
717         while (tok) {
718                 for (i = 0; i < imax; ++i) {
719                         if (strcmp(tok, all_output_options[i].str) == 0)
720                                 break;
721                 }
722                 if (i == imax) {
723                         fprintf(stderr, "Invalid field requested.\n");
724                         rc = -EINVAL;
725                         goto out;
726                 }
727
728                 if (type == -1) {
729                         /* add user option to all events types for
730                          * which it is valid
731                          */
732                         for (j = 0; j < PERF_TYPE_MAX; ++j) {
733                                 if (output[j].invalid_fields & all_output_options[i].field) {
734                                         pr_warning("\'%s\' not valid for %s events. Ignoring.\n",
735                                                    all_output_options[i].str, event_type(j));
736                                 } else
737                                         output[j].fields |= all_output_options[i].field;
738                         }
739                 } else {
740                         if (output[type].invalid_fields & all_output_options[i].field) {
741                                 fprintf(stderr, "\'%s\' not valid for %s events.\n",
742                                          all_output_options[i].str, event_type(type));
743
744                                 rc = -EINVAL;
745                                 goto out;
746                         }
747                         output[type].fields |= all_output_options[i].field;
748                 }
749
750                 tok = strtok(NULL, ",");
751         }
752
753         if (type >= 0) {
754                 if (output[type].fields == 0) {
755                         pr_debug("No fields requested for %s type. "
756                                  "Events will not be displayed.\n", event_type(type));
757                 }
758         }
759
760 out:
761         free(str);
762         return rc;
763 }
764
765 /* Helper function for filesystems that return a dent->d_type DT_UNKNOWN */
766 static int is_directory(const char *base_path, const struct dirent *dent)
767 {
768         char path[PATH_MAX];
769         struct stat st;
770
771         sprintf(path, "%s/%s", base_path, dent->d_name);
772         if (stat(path, &st))
773                 return 0;
774
775         return S_ISDIR(st.st_mode);
776 }
777
778 #define for_each_lang(scripts_path, scripts_dir, lang_dirent, lang_next)\
779         while (!readdir_r(scripts_dir, &lang_dirent, &lang_next) &&     \
780                lang_next)                                               \
781                 if ((lang_dirent.d_type == DT_DIR ||                    \
782                      (lang_dirent.d_type == DT_UNKNOWN &&               \
783                       is_directory(scripts_path, &lang_dirent))) &&     \
784                     (strcmp(lang_dirent.d_name, ".")) &&                \
785                     (strcmp(lang_dirent.d_name, "..")))
786
787 #define for_each_script(lang_path, lang_dir, script_dirent, script_next)\
788         while (!readdir_r(lang_dir, &script_dirent, &script_next) &&    \
789                script_next)                                             \
790                 if (script_dirent.d_type != DT_DIR &&                   \
791                     (script_dirent.d_type != DT_UNKNOWN ||              \
792                      !is_directory(lang_path, &script_dirent)))
793
794
795 #define RECORD_SUFFIX                   "-record"
796 #define REPORT_SUFFIX                   "-report"
797
798 struct script_desc {
799         struct list_head        node;
800         char                    *name;
801         char                    *half_liner;
802         char                    *args;
803 };
804
805 static LIST_HEAD(script_descs);
806
807 static struct script_desc *script_desc__new(const char *name)
808 {
809         struct script_desc *s = zalloc(sizeof(*s));
810
811         if (s != NULL && name)
812                 s->name = strdup(name);
813
814         return s;
815 }
816
817 static void script_desc__delete(struct script_desc *s)
818 {
819         free(s->name);
820         free(s->half_liner);
821         free(s->args);
822         free(s);
823 }
824
825 static void script_desc__add(struct script_desc *s)
826 {
827         list_add_tail(&s->node, &script_descs);
828 }
829
830 static struct script_desc *script_desc__find(const char *name)
831 {
832         struct script_desc *s;
833
834         list_for_each_entry(s, &script_descs, node)
835                 if (strcasecmp(s->name, name) == 0)
836                         return s;
837         return NULL;
838 }
839
840 static struct script_desc *script_desc__findnew(const char *name)
841 {
842         struct script_desc *s = script_desc__find(name);
843
844         if (s)
845                 return s;
846
847         s = script_desc__new(name);
848         if (!s)
849                 goto out_delete_desc;
850
851         script_desc__add(s);
852
853         return s;
854
855 out_delete_desc:
856         script_desc__delete(s);
857
858         return NULL;
859 }
860
861 static const char *ends_with(const char *str, const char *suffix)
862 {
863         size_t suffix_len = strlen(suffix);
864         const char *p = str;
865
866         if (strlen(str) > suffix_len) {
867                 p = str + strlen(str) - suffix_len;
868                 if (!strncmp(p, suffix, suffix_len))
869                         return p;
870         }
871
872         return NULL;
873 }
874
875 static char *ltrim(char *str)
876 {
877         int len = strlen(str);
878
879         while (len && isspace(*str)) {
880                 len--;
881                 str++;
882         }
883
884         return str;
885 }
886
887 static int read_script_info(struct script_desc *desc, const char *filename)
888 {
889         char line[BUFSIZ], *p;
890         FILE *fp;
891
892         fp = fopen(filename, "r");
893         if (!fp)
894                 return -1;
895
896         while (fgets(line, sizeof(line), fp)) {
897                 p = ltrim(line);
898                 if (strlen(p) == 0)
899                         continue;
900                 if (*p != '#')
901                         continue;
902                 p++;
903                 if (strlen(p) && *p == '!')
904                         continue;
905
906                 p = ltrim(p);
907                 if (strlen(p) && p[strlen(p) - 1] == '\n')
908                         p[strlen(p) - 1] = '\0';
909
910                 if (!strncmp(p, "description:", strlen("description:"))) {
911                         p += strlen("description:");
912                         desc->half_liner = strdup(ltrim(p));
913                         continue;
914                 }
915
916                 if (!strncmp(p, "args:", strlen("args:"))) {
917                         p += strlen("args:");
918                         desc->args = strdup(ltrim(p));
919                         continue;
920                 }
921         }
922
923         fclose(fp);
924
925         return 0;
926 }
927
928 static int list_available_scripts(const struct option *opt __used,
929                                   const char *s __used, int unset __used)
930 {
931         struct dirent *script_next, *lang_next, script_dirent, lang_dirent;
932         char scripts_path[MAXPATHLEN];
933         DIR *scripts_dir, *lang_dir;
934         char script_path[MAXPATHLEN];
935         char lang_path[MAXPATHLEN];
936         struct script_desc *desc;
937         char first_half[BUFSIZ];
938         char *script_root;
939         char *str;
940
941         snprintf(scripts_path, MAXPATHLEN, "%s/scripts", perf_exec_path());
942
943         scripts_dir = opendir(scripts_path);
944         if (!scripts_dir)
945                 return -1;
946
947         for_each_lang(scripts_path, scripts_dir, lang_dirent, lang_next) {
948                 snprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
949                          lang_dirent.d_name);
950                 lang_dir = opendir(lang_path);
951                 if (!lang_dir)
952                         continue;
953
954                 for_each_script(lang_path, lang_dir, script_dirent, script_next) {
955                         script_root = strdup(script_dirent.d_name);
956                         str = (char *)ends_with(script_root, REPORT_SUFFIX);
957                         if (str) {
958                                 *str = '\0';
959                                 desc = script_desc__findnew(script_root);
960                                 snprintf(script_path, MAXPATHLEN, "%s/%s",
961                                          lang_path, script_dirent.d_name);
962                                 read_script_info(desc, script_path);
963                         }
964                         free(script_root);
965                 }
966         }
967
968         fprintf(stdout, "List of available trace scripts:\n");
969         list_for_each_entry(desc, &script_descs, node) {
970                 sprintf(first_half, "%s %s", desc->name,
971                         desc->args ? desc->args : "");
972                 fprintf(stdout, "  %-36s %s\n", first_half,
973                         desc->half_liner ? desc->half_liner : "");
974         }
975
976         exit(0);
977 }
978
979 static char *get_script_path(const char *script_root, const char *suffix)
980 {
981         struct dirent *script_next, *lang_next, script_dirent, lang_dirent;
982         char scripts_path[MAXPATHLEN];
983         char script_path[MAXPATHLEN];
984         DIR *scripts_dir, *lang_dir;
985         char lang_path[MAXPATHLEN];
986         char *str, *__script_root;
987         char *path = NULL;
988
989         snprintf(scripts_path, MAXPATHLEN, "%s/scripts", perf_exec_path());
990
991         scripts_dir = opendir(scripts_path);
992         if (!scripts_dir)
993                 return NULL;
994
995         for_each_lang(scripts_path, scripts_dir, lang_dirent, lang_next) {
996                 snprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
997                          lang_dirent.d_name);
998                 lang_dir = opendir(lang_path);
999                 if (!lang_dir)
1000                         continue;
1001
1002                 for_each_script(lang_path, lang_dir, script_dirent, script_next) {
1003                         __script_root = strdup(script_dirent.d_name);
1004                         str = (char *)ends_with(__script_root, suffix);
1005                         if (str) {
1006                                 *str = '\0';
1007                                 if (strcmp(__script_root, script_root))
1008                                         continue;
1009                                 snprintf(script_path, MAXPATHLEN, "%s/%s",
1010                                          lang_path, script_dirent.d_name);
1011                                 path = strdup(script_path);
1012                                 free(__script_root);
1013                                 break;
1014                         }
1015                         free(__script_root);
1016                 }
1017         }
1018
1019         return path;
1020 }
1021
1022 static bool is_top_script(const char *script_path)
1023 {
1024         return ends_with(script_path, "top") == NULL ? false : true;
1025 }
1026
1027 static int has_required_arg(char *script_path)
1028 {
1029         struct script_desc *desc;
1030         int n_args = 0;
1031         char *p;
1032
1033         desc = script_desc__new(NULL);
1034
1035         if (read_script_info(desc, script_path))
1036                 goto out;
1037
1038         if (!desc->args)
1039                 goto out;
1040
1041         for (p = desc->args; *p; p++)
1042                 if (*p == '<')
1043                         n_args++;
1044 out:
1045         script_desc__delete(desc);
1046
1047         return n_args;
1048 }
1049
1050 static const char * const script_usage[] = {
1051         "perf script [<options>]",
1052         "perf script [<options>] record <script> [<record-options>] <command>",
1053         "perf script [<options>] report <script> [script-args]",
1054         "perf script [<options>] <script> [<record-options>] <command>",
1055         "perf script [<options>] <top-script> [script-args]",
1056         NULL
1057 };
1058
1059 static const struct option options[] = {
1060         OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
1061                     "dump raw trace in ASCII"),
1062         OPT_INCR('v', "verbose", &verbose,
1063                     "be more verbose (show symbol address, etc)"),
1064         OPT_BOOLEAN('L', "Latency", &latency_format,
1065                     "show latency attributes (irqs/preemption disabled, etc)"),
1066         OPT_CALLBACK_NOOPT('l', "list", NULL, NULL, "list available scripts",
1067                            list_available_scripts),
1068         OPT_CALLBACK('s', "script", NULL, "name",
1069                      "script file name (lang:script name, script name, or *)",
1070                      parse_scriptname),
1071         OPT_STRING('g', "gen-script", &generate_script_lang, "lang",
1072                    "generate perf-script.xx script in specified language"),
1073         OPT_STRING('i', "input", &input_name, "file",
1074                     "input file name"),
1075         OPT_BOOLEAN('d', "debug-mode", &debug_mode,
1076                    "do various checks like samples ordering and lost events"),
1077         OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
1078                    "file", "vmlinux pathname"),
1079         OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
1080                    "file", "kallsyms pathname"),
1081         OPT_BOOLEAN('G', "hide-call-graph", &no_callchain,
1082                     "When printing symbols do not display call chain"),
1083         OPT_STRING(0, "symfs", &symbol_conf.symfs, "directory",
1084                     "Look for files with symbols relative to this directory"),
1085         OPT_CALLBACK('f', "fields", NULL, "str",
1086                      "comma separated output fields prepend with 'type:'. Valid types: hw,sw,trace,raw. Fields: comm,tid,pid,time,cpu,event,trace,ip,sym,dso,addr",
1087                      parse_output_fields),
1088         OPT_STRING('C', "cpu", &cpu_list, "cpu", "list of cpus to profile"),
1089         OPT_BOOLEAN('I', "show-info", &show_full_info,
1090                     "display extended information from perf.data file"),
1091         OPT_END()
1092 };
1093
1094 static bool have_cmd(int argc, const char **argv)
1095 {
1096         char **__argv = malloc(sizeof(const char *) * argc);
1097
1098         if (!__argv)
1099                 die("malloc");
1100         memcpy(__argv, argv, sizeof(const char *) * argc);
1101         argc = parse_options(argc, (const char **)__argv, record_options,
1102                              NULL, PARSE_OPT_STOP_AT_NON_OPTION);
1103         free(__argv);
1104
1105         return argc != 0;
1106 }
1107
1108 int cmd_script(int argc, const char **argv, const char *prefix __used)
1109 {
1110         char *rec_script_path = NULL;
1111         char *rep_script_path = NULL;
1112         struct perf_session *session;
1113         char *script_path = NULL;
1114         const char **__argv;
1115         bool system_wide;
1116         int i, j, err;
1117
1118         setup_scripting();
1119
1120         argc = parse_options(argc, argv, options, script_usage,
1121                              PARSE_OPT_STOP_AT_NON_OPTION);
1122
1123         if (argc > 1 && !strncmp(argv[0], "rec", strlen("rec"))) {
1124                 rec_script_path = get_script_path(argv[1], RECORD_SUFFIX);
1125                 if (!rec_script_path)
1126                         return cmd_record(argc, argv, NULL);
1127         }
1128
1129         if (argc > 1 && !strncmp(argv[0], "rep", strlen("rep"))) {
1130                 rep_script_path = get_script_path(argv[1], REPORT_SUFFIX);
1131                 if (!rep_script_path) {
1132                         fprintf(stderr,
1133                                 "Please specify a valid report script"
1134                                 "(see 'perf script -l' for listing)\n");
1135                         return -1;
1136                 }
1137         }
1138
1139         /* make sure PERF_EXEC_PATH is set for scripts */
1140         perf_set_argv_exec_path(perf_exec_path());
1141
1142         if (argc && !script_name && !rec_script_path && !rep_script_path) {
1143                 int live_pipe[2];
1144                 int rep_args;
1145                 pid_t pid;
1146
1147                 rec_script_path = get_script_path(argv[0], RECORD_SUFFIX);
1148                 rep_script_path = get_script_path(argv[0], REPORT_SUFFIX);
1149
1150                 if (!rec_script_path && !rep_script_path) {
1151                         fprintf(stderr, " Couldn't find script %s\n\n See perf"
1152                                 " script -l for available scripts.\n", argv[0]);
1153                         usage_with_options(script_usage, options);
1154                 }
1155
1156                 if (is_top_script(argv[0])) {
1157                         rep_args = argc - 1;
1158                 } else {
1159                         int rec_args;
1160
1161                         rep_args = has_required_arg(rep_script_path);
1162                         rec_args = (argc - 1) - rep_args;
1163                         if (rec_args < 0) {
1164                                 fprintf(stderr, " %s script requires options."
1165                                         "\n\n See perf script -l for available "
1166                                         "scripts and options.\n", argv[0]);
1167                                 usage_with_options(script_usage, options);
1168                         }
1169                 }
1170
1171                 if (pipe(live_pipe) < 0) {
1172                         perror("failed to create pipe");
1173                         exit(-1);
1174                 }
1175
1176                 pid = fork();
1177                 if (pid < 0) {
1178                         perror("failed to fork");
1179                         exit(-1);
1180                 }
1181
1182                 if (!pid) {
1183                         system_wide = true;
1184                         j = 0;
1185
1186                         dup2(live_pipe[1], 1);
1187                         close(live_pipe[0]);
1188
1189                         if (!is_top_script(argv[0]))
1190                                 system_wide = !have_cmd(argc - rep_args,
1191                                                         &argv[rep_args]);
1192
1193                         __argv = malloc((argc + 6) * sizeof(const char *));
1194                         if (!__argv)
1195                                 die("malloc");
1196
1197                         __argv[j++] = "/bin/sh";
1198                         __argv[j++] = rec_script_path;
1199                         if (system_wide)
1200                                 __argv[j++] = "-a";
1201                         __argv[j++] = "-q";
1202                         __argv[j++] = "-o";
1203                         __argv[j++] = "-";
1204                         for (i = rep_args + 1; i < argc; i++)
1205                                 __argv[j++] = argv[i];
1206                         __argv[j++] = NULL;
1207
1208                         execvp("/bin/sh", (char **)__argv);
1209                         free(__argv);
1210                         exit(-1);
1211                 }
1212
1213                 dup2(live_pipe[0], 0);
1214                 close(live_pipe[1]);
1215
1216                 __argv = malloc((argc + 4) * sizeof(const char *));
1217                 if (!__argv)
1218                         die("malloc");
1219                 j = 0;
1220                 __argv[j++] = "/bin/sh";
1221                 __argv[j++] = rep_script_path;
1222                 for (i = 1; i < rep_args + 1; i++)
1223                         __argv[j++] = argv[i];
1224                 __argv[j++] = "-i";
1225                 __argv[j++] = "-";
1226                 __argv[j++] = NULL;
1227
1228                 execvp("/bin/sh", (char **)__argv);
1229                 free(__argv);
1230                 exit(-1);
1231         }
1232
1233         if (rec_script_path)
1234                 script_path = rec_script_path;
1235         if (rep_script_path)
1236                 script_path = rep_script_path;
1237
1238         if (script_path) {
1239                 system_wide = false;
1240                 j = 0;
1241
1242                 if (rec_script_path)
1243                         system_wide = !have_cmd(argc - 1, &argv[1]);
1244
1245                 __argv = malloc((argc + 2) * sizeof(const char *));
1246                 if (!__argv)
1247                         die("malloc");
1248                 __argv[j++] = "/bin/sh";
1249                 __argv[j++] = script_path;
1250                 if (system_wide)
1251                         __argv[j++] = "-a";
1252                 for (i = 2; i < argc; i++)
1253                         __argv[j++] = argv[i];
1254                 __argv[j++] = NULL;
1255
1256                 execvp("/bin/sh", (char **)__argv);
1257                 free(__argv);
1258                 exit(-1);
1259         }
1260
1261         if (symbol__init() < 0)
1262                 return -1;
1263         if (!script_name)
1264                 setup_pager();
1265
1266         session = perf_session__new(input_name, O_RDONLY, 0, false, &perf_script);
1267         if (session == NULL)
1268                 return -ENOMEM;
1269
1270         if (cpu_list) {
1271                 if (perf_session__cpu_bitmap(session, cpu_list, cpu_bitmap))
1272                         return -1;
1273         }
1274
1275         perf_session__fprintf_info(session, stdout, show_full_info);
1276
1277         if (!no_callchain)
1278                 symbol_conf.use_callchain = true;
1279         else
1280                 symbol_conf.use_callchain = false;
1281
1282         if (generate_script_lang) {
1283                 struct stat perf_stat;
1284                 int input;
1285
1286                 if (output_set_by_user()) {
1287                         fprintf(stderr,
1288                                 "custom fields not supported for generated scripts");
1289                         return -1;
1290                 }
1291
1292                 input = open(input_name, O_RDONLY);
1293                 if (input < 0) {
1294                         perror("failed to open file");
1295                         exit(-1);
1296                 }
1297
1298                 err = fstat(input, &perf_stat);
1299                 if (err < 0) {
1300                         perror("failed to stat file");
1301                         exit(-1);
1302                 }
1303
1304                 if (!perf_stat.st_size) {
1305                         fprintf(stderr, "zero-sized file, nothing to do!\n");
1306                         exit(0);
1307                 }
1308
1309                 scripting_ops = script_spec__lookup(generate_script_lang);
1310                 if (!scripting_ops) {
1311                         fprintf(stderr, "invalid language specifier");
1312                         return -1;
1313                 }
1314
1315                 err = scripting_ops->generate_script("perf-script");
1316                 goto out;
1317         }
1318
1319         if (script_name) {
1320                 err = scripting_ops->start_script(script_name, argc, argv);
1321                 if (err)
1322                         goto out;
1323                 pr_debug("perf script started with script %s\n\n", script_name);
1324         }
1325
1326
1327         err = perf_session__check_output_opt(session);
1328         if (err < 0)
1329                 goto out;
1330
1331         err = __cmd_script(session);
1332
1333         perf_session__delete(session);
1334         cleanup_scripting();
1335 out:
1336         return err;
1337 }