4 #include "util/cache.h"
5 #include "util/debug.h"
6 #include "util/exec_cmd.h"
7 #include "util/header.h"
8 #include "util/parse-options.h"
9 #include "util/session.h"
10 #include "util/symbol.h"
11 #include "util/thread.h"
12 #include "util/trace-event.h"
13 #include "util/parse-options.h"
14 #include "util/util.h"
15 #include "util/evlist.h"
16 #include "util/evsel.h"
18 static char const *script_name;
19 static char const *generate_script_lang;
20 static bool debug_mode;
21 static u64 last_timestamp;
22 static u64 nr_unordered;
23 extern const struct option record_options[];
24 static bool no_callchain;
26 enum perf_output_field {
27 PERF_OUTPUT_COMM = 1U << 0,
28 PERF_OUTPUT_TID = 1U << 1,
29 PERF_OUTPUT_PID = 1U << 2,
30 PERF_OUTPUT_TIME = 1U << 3,
31 PERF_OUTPUT_CPU = 1U << 4,
32 PERF_OUTPUT_EVNAME = 1U << 5,
33 PERF_OUTPUT_TRACE = 1U << 6,
34 PERF_OUTPUT_SYM = 1U << 7,
37 struct output_option {
39 enum perf_output_field field;
40 } all_output_options[] = {
41 {.str = "comm", .field = PERF_OUTPUT_COMM},
42 {.str = "tid", .field = PERF_OUTPUT_TID},
43 {.str = "pid", .field = PERF_OUTPUT_PID},
44 {.str = "time", .field = PERF_OUTPUT_TIME},
45 {.str = "cpu", .field = PERF_OUTPUT_CPU},
46 {.str = "event", .field = PERF_OUTPUT_EVNAME},
47 {.str = "trace", .field = PERF_OUTPUT_TRACE},
48 {.str = "sym", .field = PERF_OUTPUT_SYM},
51 /* default set to maintain compatibility with current format */
52 static u64 output_fields[PERF_TYPE_MAX] = {
53 [PERF_TYPE_HARDWARE] = PERF_OUTPUT_COMM | PERF_OUTPUT_TID | \
54 PERF_OUTPUT_CPU | PERF_OUTPUT_TIME | \
55 PERF_OUTPUT_EVNAME | PERF_OUTPUT_SYM,
57 [PERF_TYPE_SOFTWARE] = PERF_OUTPUT_COMM | PERF_OUTPUT_TID | \
58 PERF_OUTPUT_CPU | PERF_OUTPUT_TIME | \
59 PERF_OUTPUT_EVNAME | PERF_OUTPUT_SYM,
61 [PERF_TYPE_TRACEPOINT] = PERF_OUTPUT_COMM | PERF_OUTPUT_TID | \
62 PERF_OUTPUT_CPU | PERF_OUTPUT_TIME | \
63 PERF_OUTPUT_EVNAME | PERF_OUTPUT_TRACE,
66 static bool output_set_by_user;
68 #define PRINT_FIELD(x) (output_fields[attr->type] & PERF_OUTPUT_##x)
70 static int perf_session__check_attr(struct perf_session *session,
71 struct perf_event_attr *attr)
73 if (PRINT_FIELD(TRACE) &&
74 !perf_session__has_traces(session, "record -R"))
77 if (PRINT_FIELD(SYM)) {
78 if (!(session->sample_type & PERF_SAMPLE_IP)) {
79 pr_err("Samples do not contain IP data.\n");
83 !(session->sample_type & PERF_SAMPLE_CALLCHAIN))
84 symbol_conf.use_callchain = false;
87 if ((PRINT_FIELD(PID) || PRINT_FIELD(TID)) &&
88 !(session->sample_type & PERF_SAMPLE_TID)) {
89 pr_err("Samples do not contain TID/PID data.\n");
93 if (PRINT_FIELD(TIME) &&
94 !(session->sample_type & PERF_SAMPLE_TIME)) {
95 pr_err("Samples do not contain timestamps.\n");
99 if (PRINT_FIELD(CPU) &&
100 !(session->sample_type & PERF_SAMPLE_CPU)) {
101 pr_err("Samples do not contain cpu.\n");
108 static void print_sample_start(struct perf_sample *sample,
109 struct thread *thread,
110 struct perf_event_attr *attr)
114 const char *evname = NULL;
117 unsigned long long nsecs;
119 if (PRINT_FIELD(COMM)) {
121 printf("%8.8s ", thread->comm);
122 else if (PRINT_FIELD(SYM) && symbol_conf.use_callchain)
123 printf("%s ", thread->comm);
125 printf("%16s ", thread->comm);
128 if (PRINT_FIELD(PID) && PRINT_FIELD(TID))
129 printf("%5d/%-5d ", sample->pid, sample->tid);
130 else if (PRINT_FIELD(PID))
131 printf("%5d ", sample->pid);
132 else if (PRINT_FIELD(TID))
133 printf("%5d ", sample->tid);
135 if (PRINT_FIELD(CPU)) {
137 printf("%3d ", sample->cpu);
139 printf("[%03d] ", sample->cpu);
142 if (PRINT_FIELD(TIME)) {
143 nsecs = sample->time;
144 secs = nsecs / NSECS_PER_SEC;
145 nsecs -= secs * NSECS_PER_SEC;
146 usecs = nsecs / NSECS_PER_USEC;
147 printf("%5lu.%06lu: ", secs, usecs);
150 if (PRINT_FIELD(EVNAME)) {
151 if (attr->type == PERF_TYPE_TRACEPOINT) {
152 type = trace_parse_common_type(sample->raw_data);
153 event = trace_find_event(type);
155 evname = event->name;
157 evname = __event_name(attr->type, attr->config);
159 printf("%s: ", evname ? evname : "(unknown)");
163 static void process_event(union perf_event *event __unused,
164 struct perf_sample *sample,
165 struct perf_session *session,
166 struct thread *thread)
168 struct perf_event_attr *attr;
169 struct perf_evsel *evsel;
171 evsel = perf_evlist__id2evsel(session->evlist, sample->id);
173 pr_err("Invalid data. Contains samples with id not in "
179 if (output_fields[attr->type] == 0)
182 if (perf_session__check_attr(session, attr) < 0)
185 print_sample_start(sample, thread, attr);
187 if (PRINT_FIELD(TRACE))
188 print_trace_event(sample->cpu, sample->raw_data,
191 if (PRINT_FIELD(SYM)) {
192 if (!symbol_conf.use_callchain)
196 perf_session__print_symbols(event, sample, session);
202 static int default_start_script(const char *script __unused,
204 const char **argv __unused)
209 static int default_stop_script(void)
214 static int default_generate_script(const char *outfile __unused)
219 static struct scripting_ops default_scripting_ops = {
220 .start_script = default_start_script,
221 .stop_script = default_stop_script,
222 .process_event = process_event,
223 .generate_script = default_generate_script,
226 static struct scripting_ops *scripting_ops;
228 static void setup_scripting(void)
230 setup_perl_scripting();
231 setup_python_scripting();
233 scripting_ops = &default_scripting_ops;
236 static int cleanup_scripting(void)
238 pr_debug("\nperf script stopped\n");
240 return scripting_ops->stop_script();
243 static char const *input_name = "perf.data";
245 static int process_sample_event(union perf_event *event,
246 struct perf_sample *sample,
247 struct perf_session *session)
249 struct thread *thread = perf_session__findnew(session, event->ip.pid);
251 if (thread == NULL) {
252 pr_debug("problem processing %d event, skipping it.\n",
258 if (sample->time < last_timestamp) {
259 pr_err("Samples misordered, previous: %" PRIu64
260 " this: %" PRIu64 "\n", last_timestamp,
264 last_timestamp = sample->time;
267 scripting_ops->process_event(event, sample, session, thread);
269 session->hists.stats.total_period += sample->period;
273 static struct perf_event_ops event_ops = {
274 .sample = process_sample_event,
275 .mmap = perf_event__process_mmap,
276 .comm = perf_event__process_comm,
277 .exit = perf_event__process_task,
278 .fork = perf_event__process_task,
279 .attr = perf_event__process_attr,
280 .event_type = perf_event__process_event_type,
281 .tracing_data = perf_event__process_tracing_data,
282 .build_id = perf_event__process_build_id,
283 .ordered_samples = true,
284 .ordering_requires_timestamps = true,
287 extern volatile int session_done;
289 static void sig_handler(int sig __unused)
294 static int __cmd_script(struct perf_session *session)
298 signal(SIGINT, sig_handler);
300 ret = perf_session__process_events(session, &event_ops);
303 pr_err("Misordered timestamps: %" PRIu64 "\n", nr_unordered);
309 struct list_head node;
310 struct scripting_ops *ops;
314 static LIST_HEAD(script_specs);
316 static struct script_spec *script_spec__new(const char *spec,
317 struct scripting_ops *ops)
319 struct script_spec *s = malloc(sizeof(*s) + strlen(spec) + 1);
322 strcpy(s->spec, spec);
329 static void script_spec__delete(struct script_spec *s)
335 static void script_spec__add(struct script_spec *s)
337 list_add_tail(&s->node, &script_specs);
340 static struct script_spec *script_spec__find(const char *spec)
342 struct script_spec *s;
344 list_for_each_entry(s, &script_specs, node)
345 if (strcasecmp(s->spec, spec) == 0)
350 static struct script_spec *script_spec__findnew(const char *spec,
351 struct scripting_ops *ops)
353 struct script_spec *s = script_spec__find(spec);
358 s = script_spec__new(spec, ops);
360 goto out_delete_spec;
367 script_spec__delete(s);
372 int script_spec_register(const char *spec, struct scripting_ops *ops)
374 struct script_spec *s;
376 s = script_spec__find(spec);
380 s = script_spec__findnew(spec, ops);
387 static struct scripting_ops *script_spec__lookup(const char *spec)
389 struct script_spec *s = script_spec__find(spec);
396 static void list_available_languages(void)
398 struct script_spec *s;
400 fprintf(stderr, "\n");
401 fprintf(stderr, "Scripting language extensions (used in "
402 "perf script -s [spec:]script.[spec]):\n\n");
404 list_for_each_entry(s, &script_specs, node)
405 fprintf(stderr, " %-42s [%s]\n", s->spec, s->ops->name);
407 fprintf(stderr, "\n");
410 static int parse_scriptname(const struct option *opt __used,
411 const char *str, int unset __used)
414 const char *script, *ext;
417 if (strcmp(str, "lang") == 0) {
418 list_available_languages();
422 script = strchr(str, ':');
425 if (len >= PATH_MAX) {
426 fprintf(stderr, "invalid language specifier");
429 strncpy(spec, str, len);
431 scripting_ops = script_spec__lookup(spec);
432 if (!scripting_ops) {
433 fprintf(stderr, "invalid language specifier");
439 ext = strrchr(script, '.');
441 fprintf(stderr, "invalid script extension");
444 scripting_ops = script_spec__lookup(++ext);
445 if (!scripting_ops) {
446 fprintf(stderr, "invalid script extension");
451 script_name = strdup(script);
456 static int parse_output_fields(const struct option *opt __used,
457 const char *arg, int unset __used)
460 int i, imax = sizeof(all_output_options) / sizeof(struct output_option);
462 char *str = strdup(arg);
468 tok = strtok(str, ":");
471 "Invalid field string - not prepended with type.");
475 /* first word should state which event type user
476 * is specifying the fields
478 if (!strcmp(tok, "hw"))
479 type = PERF_TYPE_HARDWARE;
480 else if (!strcmp(tok, "sw"))
481 type = PERF_TYPE_SOFTWARE;
482 else if (!strcmp(tok, "trace"))
483 type = PERF_TYPE_TRACEPOINT;
485 fprintf(stderr, "Invalid event type in field string.");
489 output_fields[type] = 0;
491 tok = strtok(NULL, ",");
494 for (i = 0; i < imax; ++i) {
495 if (strcmp(tok, all_output_options[i].str) == 0) {
496 output_fields[type] |= all_output_options[i].field;
501 fprintf(stderr, "Invalid field requested.");
507 if (output_fields[type] == 0) {
508 pr_debug("No fields requested for %s type. "
509 "Events will not be displayed\n", event_type(type));
512 output_set_by_user = true;
518 /* Helper function for filesystems that return a dent->d_type DT_UNKNOWN */
519 static int is_directory(const char *base_path, const struct dirent *dent)
524 sprintf(path, "%s/%s", base_path, dent->d_name);
528 return S_ISDIR(st.st_mode);
531 #define for_each_lang(scripts_path, scripts_dir, lang_dirent, lang_next)\
532 while (!readdir_r(scripts_dir, &lang_dirent, &lang_next) && \
534 if ((lang_dirent.d_type == DT_DIR || \
535 (lang_dirent.d_type == DT_UNKNOWN && \
536 is_directory(scripts_path, &lang_dirent))) && \
537 (strcmp(lang_dirent.d_name, ".")) && \
538 (strcmp(lang_dirent.d_name, "..")))
540 #define for_each_script(lang_path, lang_dir, script_dirent, script_next)\
541 while (!readdir_r(lang_dir, &script_dirent, &script_next) && \
543 if (script_dirent.d_type != DT_DIR && \
544 (script_dirent.d_type != DT_UNKNOWN || \
545 !is_directory(lang_path, &script_dirent)))
548 #define RECORD_SUFFIX "-record"
549 #define REPORT_SUFFIX "-report"
552 struct list_head node;
558 static LIST_HEAD(script_descs);
560 static struct script_desc *script_desc__new(const char *name)
562 struct script_desc *s = zalloc(sizeof(*s));
564 if (s != NULL && name)
565 s->name = strdup(name);
570 static void script_desc__delete(struct script_desc *s)
578 static void script_desc__add(struct script_desc *s)
580 list_add_tail(&s->node, &script_descs);
583 static struct script_desc *script_desc__find(const char *name)
585 struct script_desc *s;
587 list_for_each_entry(s, &script_descs, node)
588 if (strcasecmp(s->name, name) == 0)
593 static struct script_desc *script_desc__findnew(const char *name)
595 struct script_desc *s = script_desc__find(name);
600 s = script_desc__new(name);
602 goto out_delete_desc;
609 script_desc__delete(s);
614 static const char *ends_with(const char *str, const char *suffix)
616 size_t suffix_len = strlen(suffix);
619 if (strlen(str) > suffix_len) {
620 p = str + strlen(str) - suffix_len;
621 if (!strncmp(p, suffix, suffix_len))
628 static char *ltrim(char *str)
630 int len = strlen(str);
632 while (len && isspace(*str)) {
640 static int read_script_info(struct script_desc *desc, const char *filename)
642 char line[BUFSIZ], *p;
645 fp = fopen(filename, "r");
649 while (fgets(line, sizeof(line), fp)) {
656 if (strlen(p) && *p == '!')
660 if (strlen(p) && p[strlen(p) - 1] == '\n')
661 p[strlen(p) - 1] = '\0';
663 if (!strncmp(p, "description:", strlen("description:"))) {
664 p += strlen("description:");
665 desc->half_liner = strdup(ltrim(p));
669 if (!strncmp(p, "args:", strlen("args:"))) {
670 p += strlen("args:");
671 desc->args = strdup(ltrim(p));
681 static int list_available_scripts(const struct option *opt __used,
682 const char *s __used, int unset __used)
684 struct dirent *script_next, *lang_next, script_dirent, lang_dirent;
685 char scripts_path[MAXPATHLEN];
686 DIR *scripts_dir, *lang_dir;
687 char script_path[MAXPATHLEN];
688 char lang_path[MAXPATHLEN];
689 struct script_desc *desc;
690 char first_half[BUFSIZ];
694 snprintf(scripts_path, MAXPATHLEN, "%s/scripts", perf_exec_path());
696 scripts_dir = opendir(scripts_path);
700 for_each_lang(scripts_path, scripts_dir, lang_dirent, lang_next) {
701 snprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
703 lang_dir = opendir(lang_path);
707 for_each_script(lang_path, lang_dir, script_dirent, script_next) {
708 script_root = strdup(script_dirent.d_name);
709 str = (char *)ends_with(script_root, REPORT_SUFFIX);
712 desc = script_desc__findnew(script_root);
713 snprintf(script_path, MAXPATHLEN, "%s/%s",
714 lang_path, script_dirent.d_name);
715 read_script_info(desc, script_path);
721 fprintf(stdout, "List of available trace scripts:\n");
722 list_for_each_entry(desc, &script_descs, node) {
723 sprintf(first_half, "%s %s", desc->name,
724 desc->args ? desc->args : "");
725 fprintf(stdout, " %-36s %s\n", first_half,
726 desc->half_liner ? desc->half_liner : "");
732 static char *get_script_path(const char *script_root, const char *suffix)
734 struct dirent *script_next, *lang_next, script_dirent, lang_dirent;
735 char scripts_path[MAXPATHLEN];
736 char script_path[MAXPATHLEN];
737 DIR *scripts_dir, *lang_dir;
738 char lang_path[MAXPATHLEN];
739 char *str, *__script_root;
742 snprintf(scripts_path, MAXPATHLEN, "%s/scripts", perf_exec_path());
744 scripts_dir = opendir(scripts_path);
748 for_each_lang(scripts_path, scripts_dir, lang_dirent, lang_next) {
749 snprintf(lang_path, MAXPATHLEN, "%s/%s/bin", scripts_path,
751 lang_dir = opendir(lang_path);
755 for_each_script(lang_path, lang_dir, script_dirent, script_next) {
756 __script_root = strdup(script_dirent.d_name);
757 str = (char *)ends_with(__script_root, suffix);
760 if (strcmp(__script_root, script_root))
762 snprintf(script_path, MAXPATHLEN, "%s/%s",
763 lang_path, script_dirent.d_name);
764 path = strdup(script_path);
775 static bool is_top_script(const char *script_path)
777 return ends_with(script_path, "top") == NULL ? false : true;
780 static int has_required_arg(char *script_path)
782 struct script_desc *desc;
786 desc = script_desc__new(NULL);
788 if (read_script_info(desc, script_path))
794 for (p = desc->args; *p; p++)
798 script_desc__delete(desc);
803 static const char * const script_usage[] = {
804 "perf script [<options>]",
805 "perf script [<options>] record <script> [<record-options>] <command>",
806 "perf script [<options>] report <script> [script-args]",
807 "perf script [<options>] <script> [<record-options>] <command>",
808 "perf script [<options>] <top-script> [script-args]",
812 static const struct option options[] = {
813 OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
814 "dump raw trace in ASCII"),
815 OPT_INCR('v', "verbose", &verbose,
816 "be more verbose (show symbol address, etc)"),
817 OPT_BOOLEAN('L', "Latency", &latency_format,
818 "show latency attributes (irqs/preemption disabled, etc)"),
819 OPT_CALLBACK_NOOPT('l', "list", NULL, NULL, "list available scripts",
820 list_available_scripts),
821 OPT_CALLBACK('s', "script", NULL, "name",
822 "script file name (lang:script name, script name, or *)",
824 OPT_STRING('g', "gen-script", &generate_script_lang, "lang",
825 "generate perf-script.xx script in specified language"),
826 OPT_STRING('i', "input", &input_name, "file",
828 OPT_BOOLEAN('d', "debug-mode", &debug_mode,
829 "do various checks like samples ordering and lost events"),
830 OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
831 "file", "vmlinux pathname"),
832 OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
833 "file", "kallsyms pathname"),
834 OPT_BOOLEAN('G', "hide-call-graph", &no_callchain,
835 "When printing symbols do not display call chain"),
836 OPT_STRING(0, "symfs", &symbol_conf.symfs, "directory",
837 "Look for files with symbols relative to this directory"),
838 OPT_CALLBACK('f', "fields", NULL, "str",
839 "comma separated output fields prepend with 'type:'. Valid types: hw,sw,trace. Fields: comm,tid,pid,time,cpu,event,trace,sym",
840 parse_output_fields),
845 static bool have_cmd(int argc, const char **argv)
847 char **__argv = malloc(sizeof(const char *) * argc);
851 memcpy(__argv, argv, sizeof(const char *) * argc);
852 argc = parse_options(argc, (const char **)__argv, record_options,
853 NULL, PARSE_OPT_STOP_AT_NON_OPTION);
859 int cmd_script(int argc, const char **argv, const char *prefix __used)
861 char *rec_script_path = NULL;
862 char *rep_script_path = NULL;
863 struct perf_session *session;
864 char *script_path = NULL;
871 argc = parse_options(argc, argv, options, script_usage,
872 PARSE_OPT_STOP_AT_NON_OPTION);
874 if (argc > 1 && !strncmp(argv[0], "rec", strlen("rec"))) {
875 rec_script_path = get_script_path(argv[1], RECORD_SUFFIX);
876 if (!rec_script_path)
877 return cmd_record(argc, argv, NULL);
880 if (argc > 1 && !strncmp(argv[0], "rep", strlen("rep"))) {
881 rep_script_path = get_script_path(argv[1], REPORT_SUFFIX);
882 if (!rep_script_path) {
884 "Please specify a valid report script"
885 "(see 'perf script -l' for listing)\n");
890 /* make sure PERF_EXEC_PATH is set for scripts */
891 perf_set_argv_exec_path(perf_exec_path());
893 if (argc && !script_name && !rec_script_path && !rep_script_path) {
898 rec_script_path = get_script_path(argv[0], RECORD_SUFFIX);
899 rep_script_path = get_script_path(argv[0], REPORT_SUFFIX);
901 if (!rec_script_path && !rep_script_path) {
902 fprintf(stderr, " Couldn't find script %s\n\n See perf"
903 " script -l for available scripts.\n", argv[0]);
904 usage_with_options(script_usage, options);
907 if (is_top_script(argv[0])) {
912 rep_args = has_required_arg(rep_script_path);
913 rec_args = (argc - 1) - rep_args;
915 fprintf(stderr, " %s script requires options."
916 "\n\n See perf script -l for available "
917 "scripts and options.\n", argv[0]);
918 usage_with_options(script_usage, options);
922 if (pipe(live_pipe) < 0) {
923 perror("failed to create pipe");
929 perror("failed to fork");
937 dup2(live_pipe[1], 1);
940 if (!is_top_script(argv[0]))
941 system_wide = !have_cmd(argc - rep_args,
944 __argv = malloc((argc + 6) * sizeof(const char *));
948 __argv[j++] = "/bin/sh";
949 __argv[j++] = rec_script_path;
955 for (i = rep_args + 1; i < argc; i++)
956 __argv[j++] = argv[i];
959 execvp("/bin/sh", (char **)__argv);
964 dup2(live_pipe[0], 0);
967 __argv = malloc((argc + 4) * sizeof(const char *));
971 __argv[j++] = "/bin/sh";
972 __argv[j++] = rep_script_path;
973 for (i = 1; i < rep_args + 1; i++)
974 __argv[j++] = argv[i];
979 execvp("/bin/sh", (char **)__argv);
985 script_path = rec_script_path;
987 script_path = rep_script_path;
994 system_wide = !have_cmd(argc - 1, &argv[1]);
996 __argv = malloc((argc + 2) * sizeof(const char *));
999 __argv[j++] = "/bin/sh";
1000 __argv[j++] = script_path;
1003 for (i = 2; i < argc; i++)
1004 __argv[j++] = argv[i];
1007 execvp("/bin/sh", (char **)__argv);
1012 if (symbol__init() < 0)
1017 session = perf_session__new(input_name, O_RDONLY, 0, false, &event_ops);
1018 if (session == NULL)
1022 symbol_conf.use_callchain = true;
1024 symbol_conf.use_callchain = false;
1026 if (generate_script_lang) {
1027 struct stat perf_stat;
1030 if (output_set_by_user) {
1032 "custom fields not supported for generated scripts");
1036 input = open(input_name, O_RDONLY);
1038 perror("failed to open file");
1042 err = fstat(input, &perf_stat);
1044 perror("failed to stat file");
1048 if (!perf_stat.st_size) {
1049 fprintf(stderr, "zero-sized file, nothing to do!\n");
1053 scripting_ops = script_spec__lookup(generate_script_lang);
1054 if (!scripting_ops) {
1055 fprintf(stderr, "invalid language specifier");
1059 err = scripting_ops->generate_script("perf-script");
1064 err = scripting_ops->start_script(script_name, argc, argv);
1067 pr_debug("perf script started with script %s\n\n", script_name);
1070 err = __cmd_script(session);
1072 perf_session__delete(session);
1073 cleanup_scripting();