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