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