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