Merge commit 'v2.6.37-rc7' into perf/core
[pandora-kernel.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
16 static char const               *script_name;
17 static char const               *generate_script_lang;
18 static bool                     debug_mode;
19 static u64                      last_timestamp;
20 static u64                      nr_unordered;
21 extern const struct option      record_options[];
22
23 static int default_start_script(const char *script __unused,
24                                 int argc __unused,
25                                 const char **argv __unused)
26 {
27         return 0;
28 }
29
30 static int default_stop_script(void)
31 {
32         return 0;
33 }
34
35 static int default_generate_script(const char *outfile __unused)
36 {
37         return 0;
38 }
39
40 static struct scripting_ops default_scripting_ops = {
41         .start_script           = default_start_script,
42         .stop_script            = default_stop_script,
43         .process_event          = print_event,
44         .generate_script        = default_generate_script,
45 };
46
47 static struct scripting_ops     *scripting_ops;
48
49 static void setup_scripting(void)
50 {
51         setup_perl_scripting();
52         setup_python_scripting();
53
54         scripting_ops = &default_scripting_ops;
55 }
56
57 static int cleanup_scripting(void)
58 {
59         pr_debug("\nperf script stopped\n");
60
61         return scripting_ops->stop_script();
62 }
63
64 static char const               *input_name = "perf.data";
65
66 static int process_sample_event(event_t *event, struct sample_data *sample,
67                                 struct perf_session *session)
68 {
69         struct thread *thread = perf_session__findnew(session, event->ip.pid);
70
71         if (thread == NULL) {
72                 pr_debug("problem processing %d event, skipping it.\n",
73                          event->header.type);
74                 return -1;
75         }
76
77         if (session->sample_type & PERF_SAMPLE_RAW) {
78                 if (debug_mode) {
79                         if (sample->time < last_timestamp) {
80                                 pr_err("Samples misordered, previous: %llu "
81                                         "this: %llu\n", last_timestamp,
82                                         sample->time);
83                                 nr_unordered++;
84                         }
85                         last_timestamp = sample->time;
86                         return 0;
87                 }
88                 /*
89                  * FIXME: better resolve from pid from the struct trace_entry
90                  * field, although it should be the same than this perf
91                  * event pid
92                  */
93                 scripting_ops->process_event(sample->cpu, sample->raw_data,
94                                              sample->raw_size,
95                                              sample->time, thread->comm);
96         }
97
98         session->hists.stats.total_period += sample->period;
99         return 0;
100 }
101
102 static u64 nr_lost;
103
104 static int process_lost_event(event_t *event, struct sample_data *sample __used,
105                               struct perf_session *session __used)
106 {
107         nr_lost += event->lost.lost;
108
109         return 0;
110 }
111
112 static struct perf_event_ops event_ops = {
113         .sample = process_sample_event,
114         .comm   = event__process_comm,
115         .attr   = event__process_attr,
116         .event_type = event__process_event_type,
117         .tracing_data = event__process_tracing_data,
118         .build_id = event__process_build_id,
119         .lost = process_lost_event,
120         .ordered_samples = true,
121 };
122
123 extern volatile int session_done;
124
125 static void sig_handler(int sig __unused)
126 {
127         session_done = 1;
128 }
129
130 static int __cmd_script(struct perf_session *session)
131 {
132         int ret;
133
134         signal(SIGINT, sig_handler);
135
136         ret = perf_session__process_events(session, &event_ops);
137
138         if (debug_mode) {
139                 pr_err("Misordered timestamps: %llu\n", nr_unordered);
140                 pr_err("Lost events: %llu\n", nr_lost);
141         }
142
143         return ret;
144 }
145
146 struct script_spec {
147         struct list_head        node;
148         struct scripting_ops    *ops;
149         char                    spec[0];
150 };
151
152 LIST_HEAD(script_specs);
153
154 static struct script_spec *script_spec__new(const char *spec,
155                                             struct scripting_ops *ops)
156 {
157         struct script_spec *s = malloc(sizeof(*s) + strlen(spec) + 1);
158
159         if (s != NULL) {
160                 strcpy(s->spec, spec);
161                 s->ops = ops;
162         }
163
164         return s;
165 }
166
167 static void script_spec__delete(struct script_spec *s)
168 {
169         free(s->spec);
170         free(s);
171 }
172
173 static void script_spec__add(struct script_spec *s)
174 {
175         list_add_tail(&s->node, &script_specs);
176 }
177
178 static struct script_spec *script_spec__find(const char *spec)
179 {
180         struct script_spec *s;
181
182         list_for_each_entry(s, &script_specs, node)
183                 if (strcasecmp(s->spec, spec) == 0)
184                         return s;
185         return NULL;
186 }
187
188 static struct script_spec *script_spec__findnew(const char *spec,
189                                                 struct scripting_ops *ops)
190 {
191         struct script_spec *s = script_spec__find(spec);
192
193         if (s)
194                 return s;
195
196         s = script_spec__new(spec, ops);
197         if (!s)
198                 goto out_delete_spec;
199
200         script_spec__add(s);
201
202         return s;
203
204 out_delete_spec:
205         script_spec__delete(s);
206
207         return NULL;
208 }
209
210 int script_spec_register(const char *spec, struct scripting_ops *ops)
211 {
212         struct script_spec *s;
213
214         s = script_spec__find(spec);
215         if (s)
216                 return -1;
217
218         s = script_spec__findnew(spec, ops);
219         if (!s)
220                 return -1;
221
222         return 0;
223 }
224
225 static struct scripting_ops *script_spec__lookup(const char *spec)
226 {
227         struct script_spec *s = script_spec__find(spec);
228         if (!s)
229                 return NULL;
230
231         return s->ops;
232 }
233
234 static void list_available_languages(void)
235 {
236         struct script_spec *s;
237
238         fprintf(stderr, "\n");
239         fprintf(stderr, "Scripting language extensions (used in "
240                 "perf script -s [spec:]script.[spec]):\n\n");
241
242         list_for_each_entry(s, &script_specs, node)
243                 fprintf(stderr, "  %-42s [%s]\n", s->spec, s->ops->name);
244
245         fprintf(stderr, "\n");
246 }
247
248 static int parse_scriptname(const struct option *opt __used,
249                             const char *str, int unset __used)
250 {
251         char spec[PATH_MAX];
252         const char *script, *ext;
253         int len;
254
255         if (strcmp(str, "lang") == 0) {
256                 list_available_languages();
257                 exit(0);
258         }
259
260         script = strchr(str, ':');
261         if (script) {
262                 len = script - str;
263                 if (len >= PATH_MAX) {
264                         fprintf(stderr, "invalid language specifier");
265                         return -1;
266                 }
267                 strncpy(spec, str, len);
268                 spec[len] = '\0';
269                 scripting_ops = script_spec__lookup(spec);
270                 if (!scripting_ops) {
271                         fprintf(stderr, "invalid language specifier");
272                         return -1;
273                 }
274                 script++;
275         } else {
276                 script = str;
277                 ext = strrchr(script, '.');
278                 if (!ext) {
279                         fprintf(stderr, "invalid script extension");
280                         return -1;
281                 }
282                 scripting_ops = script_spec__lookup(++ext);
283                 if (!scripting_ops) {
284                         fprintf(stderr, "invalid script extension");
285                         return -1;
286                 }
287         }
288
289         script_name = strdup(script);
290
291         return 0;
292 }
293
294 /* Helper function for filesystems that return a dent->d_type DT_UNKNOWN */
295 static int is_directory(const char *base_path, const struct dirent *dent)
296 {
297         char path[PATH_MAX];
298         struct stat st;
299
300         sprintf(path, "%s/%s", base_path, dent->d_name);
301         if (stat(path, &st))
302                 return 0;
303
304         return S_ISDIR(st.st_mode);
305 }
306
307 #define for_each_lang(scripts_path, scripts_dir, lang_dirent, lang_next)\
308         while (!readdir_r(scripts_dir, &lang_dirent, &lang_next) &&     \
309                lang_next)                                               \
310                 if ((lang_dirent.d_type == DT_DIR ||                    \
311                      (lang_dirent.d_type == DT_UNKNOWN &&               \
312                       is_directory(scripts_path, &lang_dirent))) &&     \
313                     (strcmp(lang_dirent.d_name, ".")) &&                \
314                     (strcmp(lang_dirent.d_name, "..")))
315
316 #define for_each_script(lang_path, lang_dir, script_dirent, script_next)\
317         while (!readdir_r(lang_dir, &script_dirent, &script_next) &&    \
318                script_next)                                             \
319                 if (script_dirent.d_type != DT_DIR &&                   \
320                     (script_dirent.d_type != DT_UNKNOWN ||              \
321                      !is_directory(lang_path, &script_dirent)))
322
323
324 #define RECORD_SUFFIX                   "-record"
325 #define REPORT_SUFFIX                   "-report"
326
327 struct script_desc {
328         struct list_head        node;
329         char                    *name;
330         char                    *half_liner;
331         char                    *args;
332 };
333
334 LIST_HEAD(script_descs);
335
336 static struct script_desc *script_desc__new(const char *name)
337 {
338         struct script_desc *s = zalloc(sizeof(*s));
339
340         if (s != NULL && name)
341                 s->name = strdup(name);
342
343         return s;
344 }
345
346 static void script_desc__delete(struct script_desc *s)
347 {
348         free(s->name);
349         free(s->half_liner);
350         free(s->args);
351         free(s);
352 }
353
354 static void script_desc__add(struct script_desc *s)
355 {
356         list_add_tail(&s->node, &script_descs);
357 }
358
359 static struct script_desc *script_desc__find(const char *name)
360 {
361         struct script_desc *s;
362
363         list_for_each_entry(s, &script_descs, node)
364                 if (strcasecmp(s->name, name) == 0)
365                         return s;
366         return NULL;
367 }
368
369 static struct script_desc *script_desc__findnew(const char *name)
370 {
371         struct script_desc *s = script_desc__find(name);
372
373         if (s)
374                 return s;
375
376         s = script_desc__new(name);
377         if (!s)
378                 goto out_delete_desc;
379
380         script_desc__add(s);
381
382         return s;
383
384 out_delete_desc:
385         script_desc__delete(s);
386
387         return NULL;
388 }
389
390 static const char *ends_with(const char *str, const char *suffix)
391 {
392         size_t suffix_len = strlen(suffix);
393         const char *p = str;
394
395         if (strlen(str) > suffix_len) {
396                 p = str + strlen(str) - suffix_len;
397                 if (!strncmp(p, suffix, suffix_len))
398                         return p;
399         }
400
401         return NULL;
402 }
403
404 static char *ltrim(char *str)
405 {
406         int len = strlen(str);
407
408         while (len && isspace(*str)) {
409                 len--;
410                 str++;
411         }
412
413         return str;
414 }
415
416 static int read_script_info(struct script_desc *desc, const char *filename)
417 {
418         char line[BUFSIZ], *p;
419         FILE *fp;
420
421         fp = fopen(filename, "r");
422         if (!fp)
423                 return -1;
424
425         while (fgets(line, sizeof(line), fp)) {
426                 p = ltrim(line);
427                 if (strlen(p) == 0)
428                         continue;
429                 if (*p != '#')
430                         continue;
431                 p++;
432                 if (strlen(p) && *p == '!')
433                         continue;
434
435                 p = ltrim(p);
436                 if (strlen(p) && p[strlen(p) - 1] == '\n')
437                         p[strlen(p) - 1] = '\0';
438
439                 if (!strncmp(p, "description:", strlen("description:"))) {
440                         p += strlen("description:");
441                         desc->half_liner = strdup(ltrim(p));
442                         continue;
443                 }
444
445                 if (!strncmp(p, "args:", strlen("args:"))) {
446                         p += strlen("args:");
447                         desc->args = strdup(ltrim(p));
448                         continue;
449                 }
450         }
451
452         fclose(fp);
453
454         return 0;
455 }
456
457 static int list_available_scripts(const struct option *opt __used,
458                                   const char *s __used, int unset __used)
459 {
460         struct dirent *script_next, *lang_next, script_dirent, lang_dirent;
461         char scripts_path[MAXPATHLEN];
462         DIR *scripts_dir, *lang_dir;
463         char script_path[MAXPATHLEN];
464         char lang_path[MAXPATHLEN];
465         struct script_desc *desc;
466         char first_half[BUFSIZ];
467         char *script_root;
468         char *str;
469
470         snprintf(scripts_path, MAXPATHLEN, "%s/scripts", perf_exec_path());
471
472         scripts_dir = opendir(scripts_path);
473         if (!scripts_dir)
474                 return -1;
475
476         for_each_lang(scripts_path, scripts_dir, lang_dirent, lang_next) {
477                 snprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
478                          lang_dirent.d_name);
479                 lang_dir = opendir(lang_path);
480                 if (!lang_dir)
481                         continue;
482
483                 for_each_script(lang_path, lang_dir, script_dirent, script_next) {
484                         script_root = strdup(script_dirent.d_name);
485                         str = (char *)ends_with(script_root, REPORT_SUFFIX);
486                         if (str) {
487                                 *str = '\0';
488                                 desc = script_desc__findnew(script_root);
489                                 snprintf(script_path, MAXPATHLEN, "%s/%s",
490                                          lang_path, script_dirent.d_name);
491                                 read_script_info(desc, script_path);
492                         }
493                         free(script_root);
494                 }
495         }
496
497         fprintf(stdout, "List of available trace scripts:\n");
498         list_for_each_entry(desc, &script_descs, node) {
499                 sprintf(first_half, "%s %s", desc->name,
500                         desc->args ? desc->args : "");
501                 fprintf(stdout, "  %-36s %s\n", first_half,
502                         desc->half_liner ? desc->half_liner : "");
503         }
504
505         exit(0);
506 }
507
508 static char *get_script_path(const char *script_root, const char *suffix)
509 {
510         struct dirent *script_next, *lang_next, script_dirent, lang_dirent;
511         char scripts_path[MAXPATHLEN];
512         char script_path[MAXPATHLEN];
513         DIR *scripts_dir, *lang_dir;
514         char lang_path[MAXPATHLEN];
515         char *str, *__script_root;
516         char *path = NULL;
517
518         snprintf(scripts_path, MAXPATHLEN, "%s/scripts", perf_exec_path());
519
520         scripts_dir = opendir(scripts_path);
521         if (!scripts_dir)
522                 return NULL;
523
524         for_each_lang(scripts_path, scripts_dir, lang_dirent, lang_next) {
525                 snprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
526                          lang_dirent.d_name);
527                 lang_dir = opendir(lang_path);
528                 if (!lang_dir)
529                         continue;
530
531                 for_each_script(lang_path, lang_dir, script_dirent, script_next) {
532                         __script_root = strdup(script_dirent.d_name);
533                         str = (char *)ends_with(__script_root, suffix);
534                         if (str) {
535                                 *str = '\0';
536                                 if (strcmp(__script_root, script_root))
537                                         continue;
538                                 snprintf(script_path, MAXPATHLEN, "%s/%s",
539                                          lang_path, script_dirent.d_name);
540                                 path = strdup(script_path);
541                                 free(__script_root);
542                                 break;
543                         }
544                         free(__script_root);
545                 }
546         }
547
548         return path;
549 }
550
551 static bool is_top_script(const char *script_path)
552 {
553         return ends_with(script_path, "top") == NULL ? false : true;
554 }
555
556 static int has_required_arg(char *script_path)
557 {
558         struct script_desc *desc;
559         int n_args = 0;
560         char *p;
561
562         desc = script_desc__new(NULL);
563
564         if (read_script_info(desc, script_path))
565                 goto out;
566
567         if (!desc->args)
568                 goto out;
569
570         for (p = desc->args; *p; p++)
571                 if (*p == '<')
572                         n_args++;
573 out:
574         script_desc__delete(desc);
575
576         return n_args;
577 }
578
579 static const char * const script_usage[] = {
580         "perf script [<options>]",
581         "perf script [<options>] record <script> [<record-options>] <command>",
582         "perf script [<options>] report <script> [script-args]",
583         "perf script [<options>] <script> [<record-options>] <command>",
584         "perf script [<options>] <top-script> [script-args]",
585         NULL
586 };
587
588 static const struct option options[] = {
589         OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
590                     "dump raw trace in ASCII"),
591         OPT_INCR('v', "verbose", &verbose,
592                     "be more verbose (show symbol address, etc)"),
593         OPT_BOOLEAN('L', "Latency", &latency_format,
594                     "show latency attributes (irqs/preemption disabled, etc)"),
595         OPT_CALLBACK_NOOPT('l', "list", NULL, NULL, "list available scripts",
596                            list_available_scripts),
597         OPT_CALLBACK('s', "script", NULL, "name",
598                      "script file name (lang:script name, script name, or *)",
599                      parse_scriptname),
600         OPT_STRING('g', "gen-script", &generate_script_lang, "lang",
601                    "generate perf-script.xx script in specified language"),
602         OPT_STRING('i', "input", &input_name, "file",
603                     "input file name"),
604         OPT_BOOLEAN('d', "debug-mode", &debug_mode,
605                    "do various checks like samples ordering and lost events"),
606
607         OPT_END()
608 };
609
610 static bool have_cmd(int argc, const char **argv)
611 {
612         char **__argv = malloc(sizeof(const char *) * argc);
613
614         if (!__argv)
615                 die("malloc");
616         memcpy(__argv, argv, sizeof(const char *) * argc);
617         argc = parse_options(argc, (const char **)__argv, record_options,
618                              NULL, PARSE_OPT_STOP_AT_NON_OPTION);
619         free(__argv);
620
621         return argc != 0;
622 }
623
624 int cmd_script(int argc, const char **argv, const char *prefix __used)
625 {
626         char *rec_script_path = NULL;
627         char *rep_script_path = NULL;
628         struct perf_session *session;
629         char *script_path = NULL;
630         const char **__argv;
631         bool system_wide;
632         int i, j, err;
633
634         setup_scripting();
635
636         argc = parse_options(argc, argv, options, script_usage,
637                              PARSE_OPT_STOP_AT_NON_OPTION);
638
639         if (argc > 1 && !strncmp(argv[0], "rec", strlen("rec"))) {
640                 rec_script_path = get_script_path(argv[1], RECORD_SUFFIX);
641                 if (!rec_script_path)
642                         return cmd_record(argc, argv, NULL);
643         }
644
645         if (argc > 1 && !strncmp(argv[0], "rep", strlen("rep"))) {
646                 rep_script_path = get_script_path(argv[1], REPORT_SUFFIX);
647                 if (!rep_script_path) {
648                         fprintf(stderr,
649                                 "Please specify a valid report script"
650                                 "(see 'perf script -l' for listing)\n");
651                         return -1;
652                 }
653         }
654
655         /* make sure PERF_EXEC_PATH is set for scripts */
656         perf_set_argv_exec_path(perf_exec_path());
657
658         if (argc && !script_name && !rec_script_path && !rep_script_path) {
659                 int live_pipe[2];
660                 int rep_args;
661                 pid_t pid;
662
663                 rec_script_path = get_script_path(argv[0], RECORD_SUFFIX);
664                 rep_script_path = get_script_path(argv[0], REPORT_SUFFIX);
665
666                 if (!rec_script_path && !rep_script_path) {
667                         fprintf(stderr, " Couldn't find script %s\n\n See perf"
668                                 " script -l for available scripts.\n", argv[0]);
669                         usage_with_options(script_usage, options);
670                 }
671
672                 if (is_top_script(argv[0])) {
673                         rep_args = argc - 1;
674                 } else {
675                         int rec_args;
676
677                         rep_args = has_required_arg(rep_script_path);
678                         rec_args = (argc - 1) - rep_args;
679                         if (rec_args < 0) {
680                                 fprintf(stderr, " %s script requires options."
681                                         "\n\n See perf script -l for available "
682                                         "scripts and options.\n", argv[0]);
683                                 usage_with_options(script_usage, options);
684                         }
685                 }
686
687                 if (pipe(live_pipe) < 0) {
688                         perror("failed to create pipe");
689                         exit(-1);
690                 }
691
692                 pid = fork();
693                 if (pid < 0) {
694                         perror("failed to fork");
695                         exit(-1);
696                 }
697
698                 if (!pid) {
699                         system_wide = true;
700                         j = 0;
701
702                         dup2(live_pipe[1], 1);
703                         close(live_pipe[0]);
704
705                         if (!is_top_script(argv[0]))
706                                 system_wide = !have_cmd(argc - rep_args,
707                                                         &argv[rep_args]);
708
709                         __argv = malloc((argc + 6) * sizeof(const char *));
710                         if (!__argv)
711                                 die("malloc");
712
713                         __argv[j++] = "/bin/sh";
714                         __argv[j++] = rec_script_path;
715                         if (system_wide)
716                                 __argv[j++] = "-a";
717                         __argv[j++] = "-q";
718                         __argv[j++] = "-o";
719                         __argv[j++] = "-";
720                         for (i = rep_args + 1; i < argc; i++)
721                                 __argv[j++] = argv[i];
722                         __argv[j++] = NULL;
723
724                         execvp("/bin/sh", (char **)__argv);
725                         free(__argv);
726                         exit(-1);
727                 }
728
729                 dup2(live_pipe[0], 0);
730                 close(live_pipe[1]);
731
732                 __argv = malloc((argc + 4) * sizeof(const char *));
733                 if (!__argv)
734                         die("malloc");
735                 j = 0;
736                 __argv[j++] = "/bin/sh";
737                 __argv[j++] = rep_script_path;
738                 for (i = 1; i < rep_args + 1; i++)
739                         __argv[j++] = argv[i];
740                 __argv[j++] = "-i";
741                 __argv[j++] = "-";
742                 __argv[j++] = NULL;
743
744                 execvp("/bin/sh", (char **)__argv);
745                 free(__argv);
746                 exit(-1);
747         }
748
749         if (rec_script_path)
750                 script_path = rec_script_path;
751         if (rep_script_path)
752                 script_path = rep_script_path;
753
754         if (script_path) {
755                 system_wide = false;
756                 j = 0;
757
758                 if (rec_script_path)
759                         system_wide = !have_cmd(argc - 1, &argv[1]);
760
761                 __argv = malloc((argc + 2) * sizeof(const char *));
762                 if (!__argv)
763                         die("malloc");
764                 __argv[j++] = "/bin/sh";
765                 __argv[j++] = script_path;
766                 if (system_wide)
767                         __argv[j++] = "-a";
768                 for (i = 2; i < argc; i++)
769                         __argv[j++] = argv[i];
770                 __argv[j++] = NULL;
771
772                 execvp("/bin/sh", (char **)__argv);
773                 free(__argv);
774                 exit(-1);
775         }
776
777         if (symbol__init() < 0)
778                 return -1;
779         if (!script_name)
780                 setup_pager();
781
782         session = perf_session__new(input_name, O_RDONLY, 0, false);
783         if (session == NULL)
784                 return -ENOMEM;
785
786         if (strcmp(input_name, "-") &&
787             !perf_session__has_traces(session, "record -R"))
788                 return -EINVAL;
789
790         if (generate_script_lang) {
791                 struct stat perf_stat;
792
793                 int input = open(input_name, O_RDONLY);
794                 if (input < 0) {
795                         perror("failed to open file");
796                         exit(-1);
797                 }
798
799                 err = fstat(input, &perf_stat);
800                 if (err < 0) {
801                         perror("failed to stat file");
802                         exit(-1);
803                 }
804
805                 if (!perf_stat.st_size) {
806                         fprintf(stderr, "zero-sized file, nothing to do!\n");
807                         exit(0);
808                 }
809
810                 scripting_ops = script_spec__lookup(generate_script_lang);
811                 if (!scripting_ops) {
812                         fprintf(stderr, "invalid language specifier");
813                         return -1;
814                 }
815
816                 err = scripting_ops->generate_script("perf-script");
817                 goto out;
818         }
819
820         if (script_name) {
821                 err = scripting_ops->start_script(script_name, argc, argv);
822                 if (err)
823                         goto out;
824                 pr_debug("perf script started with script %s\n\n", script_name);
825         }
826
827         err = __cmd_script(session);
828
829         perf_session__delete(session);
830         cleanup_scripting();
831 out:
832         return err;
833 }