]> asedeno.scripts.mit.edu Git - linux.git/blob - tools/perf/perf.c
perf kallsyms: Introduce tool to look for extended symbol information on the running...
[linux.git] / tools / perf / perf.c
1 /*
2  * perf.c
3  *
4  * Performance analysis utility.
5  *
6  * This is the main hub from which the sub-commands (perf stat,
7  * perf top, perf record, perf report, etc.) are started.
8  */
9 #include "builtin.h"
10
11 #include "util/env.h"
12 #include <subcmd/exec-cmd.h>
13 #include "util/config.h"
14 #include "util/quote.h"
15 #include <subcmd/run-command.h>
16 #include "util/parse-events.h"
17 #include <subcmd/parse-options.h>
18 #include "util/bpf-loader.h"
19 #include "util/debug.h"
20 #include <api/fs/fs.h>
21 #include <api/fs/tracing_path.h>
22 #include <pthread.h>
23 #include <stdlib.h>
24 #include <time.h>
25
26 const char perf_usage_string[] =
27         "perf [--version] [--help] [OPTIONS] COMMAND [ARGS]";
28
29 const char perf_more_info_string[] =
30         "See 'perf help COMMAND' for more information on a specific command.";
31
32 int use_browser = -1;
33 static int use_pager = -1;
34 const char *input_name;
35
36 struct cmd_struct {
37         const char *cmd;
38         int (*fn)(int, const char **, const char *);
39         int option;
40 };
41
42 static struct cmd_struct commands[] = {
43         { "buildid-cache", cmd_buildid_cache, 0 },
44         { "buildid-list", cmd_buildid_list, 0 },
45         { "config",     cmd_config,     0 },
46         { "c2c",        cmd_c2c,        0 },
47         { "diff",       cmd_diff,       0 },
48         { "evlist",     cmd_evlist,     0 },
49         { "help",       cmd_help,       0 },
50         { "kallsyms",   cmd_kallsyms,   0 },
51         { "list",       cmd_list,       0 },
52         { "record",     cmd_record,     0 },
53         { "report",     cmd_report,     0 },
54         { "bench",      cmd_bench,      0 },
55         { "stat",       cmd_stat,       0 },
56         { "timechart",  cmd_timechart,  0 },
57         { "top",        cmd_top,        0 },
58         { "annotate",   cmd_annotate,   0 },
59         { "version",    cmd_version,    0 },
60         { "script",     cmd_script,     0 },
61         { "sched",      cmd_sched,      0 },
62 #ifdef HAVE_LIBELF_SUPPORT
63         { "probe",      cmd_probe,      0 },
64 #endif
65         { "kmem",       cmd_kmem,       0 },
66         { "lock",       cmd_lock,       0 },
67         { "kvm",        cmd_kvm,        0 },
68         { "test",       cmd_test,       0 },
69 #ifdef HAVE_LIBAUDIT_SUPPORT
70         { "trace",      cmd_trace,      0 },
71 #endif
72         { "inject",     cmd_inject,     0 },
73         { "mem",        cmd_mem,        0 },
74         { "data",       cmd_data,       0 },
75 };
76
77 struct pager_config {
78         const char *cmd;
79         int val;
80 };
81
82 static int pager_command_config(const char *var, const char *value, void *data)
83 {
84         struct pager_config *c = data;
85         if (!prefixcmp(var, "pager.") && !strcmp(var + 6, c->cmd))
86                 c->val = perf_config_bool(var, value);
87         return 0;
88 }
89
90 /* returns 0 for "no pager", 1 for "use pager", and -1 for "not specified" */
91 int check_pager_config(const char *cmd)
92 {
93         struct pager_config c;
94         c.cmd = cmd;
95         c.val = -1;
96         perf_config(pager_command_config, &c);
97         return c.val;
98 }
99
100 static int browser_command_config(const char *var, const char *value, void *data)
101 {
102         struct pager_config *c = data;
103         if (!prefixcmp(var, "tui.") && !strcmp(var + 4, c->cmd))
104                 c->val = perf_config_bool(var, value);
105         if (!prefixcmp(var, "gtk.") && !strcmp(var + 4, c->cmd))
106                 c->val = perf_config_bool(var, value) ? 2 : 0;
107         return 0;
108 }
109
110 /*
111  * returns 0 for "no tui", 1 for "use tui", 2 for "use gtk",
112  * and -1 for "not specified"
113  */
114 static int check_browser_config(const char *cmd)
115 {
116         struct pager_config c;
117         c.cmd = cmd;
118         c.val = -1;
119         perf_config(browser_command_config, &c);
120         return c.val;
121 }
122
123 static void commit_pager_choice(void)
124 {
125         switch (use_pager) {
126         case 0:
127                 setenv(PERF_PAGER_ENVIRONMENT, "cat", 1);
128                 break;
129         case 1:
130                 /* setup_pager(); */
131                 break;
132         default:
133                 break;
134         }
135 }
136
137 struct option options[] = {
138         OPT_ARGUMENT("help", "help"),
139         OPT_ARGUMENT("version", "version"),
140         OPT_ARGUMENT("exec-path", "exec-path"),
141         OPT_ARGUMENT("html-path", "html-path"),
142         OPT_ARGUMENT("paginate", "paginate"),
143         OPT_ARGUMENT("no-pager", "no-pager"),
144         OPT_ARGUMENT("debugfs-dir", "debugfs-dir"),
145         OPT_ARGUMENT("buildid-dir", "buildid-dir"),
146         OPT_ARGUMENT("list-cmds", "list-cmds"),
147         OPT_ARGUMENT("list-opts", "list-opts"),
148         OPT_ARGUMENT("debug", "debug"),
149         OPT_END()
150 };
151
152 static int handle_options(const char ***argv, int *argc, int *envchanged)
153 {
154         int handled = 0;
155
156         while (*argc > 0) {
157                 const char *cmd = (*argv)[0];
158                 if (cmd[0] != '-')
159                         break;
160
161                 /*
162                  * For legacy reasons, the "version" and "help"
163                  * commands can be written with "--" prepended
164                  * to make them look like flags.
165                  */
166                 if (!strcmp(cmd, "--help") || !strcmp(cmd, "--version"))
167                         break;
168
169                 /*
170                  * Shortcut for '-h' and '-v' options to invoke help
171                  * and version command.
172                  */
173                 if (!strcmp(cmd, "-h")) {
174                         (*argv)[0] = "--help";
175                         break;
176                 }
177
178                 if (!strcmp(cmd, "-v")) {
179                         (*argv)[0] = "--version";
180                         break;
181                 }
182
183                 /*
184                  * Check remaining flags.
185                  */
186                 if (!prefixcmp(cmd, CMD_EXEC_PATH)) {
187                         cmd += strlen(CMD_EXEC_PATH);
188                         if (*cmd == '=')
189                                 set_argv_exec_path(cmd + 1);
190                         else {
191                                 puts(get_argv_exec_path());
192                                 exit(0);
193                         }
194                 } else if (!strcmp(cmd, "--html-path")) {
195                         puts(system_path(PERF_HTML_PATH));
196                         exit(0);
197                 } else if (!strcmp(cmd, "-p") || !strcmp(cmd, "--paginate")) {
198                         use_pager = 1;
199                 } else if (!strcmp(cmd, "--no-pager")) {
200                         use_pager = 0;
201                         if (envchanged)
202                                 *envchanged = 1;
203                 } else if (!strcmp(cmd, "--debugfs-dir")) {
204                         if (*argc < 2) {
205                                 fprintf(stderr, "No directory given for --debugfs-dir.\n");
206                                 usage(perf_usage_string);
207                         }
208                         tracing_path_set((*argv)[1]);
209                         if (envchanged)
210                                 *envchanged = 1;
211                         (*argv)++;
212                         (*argc)--;
213                 } else if (!strcmp(cmd, "--buildid-dir")) {
214                         if (*argc < 2) {
215                                 fprintf(stderr, "No directory given for --buildid-dir.\n");
216                                 usage(perf_usage_string);
217                         }
218                         set_buildid_dir((*argv)[1]);
219                         if (envchanged)
220                                 *envchanged = 1;
221                         (*argv)++;
222                         (*argc)--;
223                 } else if (!prefixcmp(cmd, CMD_DEBUGFS_DIR)) {
224                         tracing_path_set(cmd + strlen(CMD_DEBUGFS_DIR));
225                         fprintf(stderr, "dir: %s\n", tracing_path);
226                         if (envchanged)
227                                 *envchanged = 1;
228                 } else if (!strcmp(cmd, "--list-cmds")) {
229                         unsigned int i;
230
231                         for (i = 0; i < ARRAY_SIZE(commands); i++) {
232                                 struct cmd_struct *p = commands+i;
233                                 printf("%s ", p->cmd);
234                         }
235                         putchar('\n');
236                         exit(0);
237                 } else if (!strcmp(cmd, "--list-opts")) {
238                         unsigned int i;
239
240                         for (i = 0; i < ARRAY_SIZE(options)-1; i++) {
241                                 struct option *p = options+i;
242                                 printf("--%s ", p->long_name);
243                         }
244                         putchar('\n');
245                         exit(0);
246                 } else if (!strcmp(cmd, "--debug")) {
247                         if (*argc < 2) {
248                                 fprintf(stderr, "No variable specified for --debug.\n");
249                                 usage(perf_usage_string);
250                         }
251                         if (perf_debug_option((*argv)[1]))
252                                 usage(perf_usage_string);
253
254                         (*argv)++;
255                         (*argc)--;
256                 } else {
257                         fprintf(stderr, "Unknown option: %s\n", cmd);
258                         usage(perf_usage_string);
259                 }
260
261                 (*argv)++;
262                 (*argc)--;
263                 handled++;
264         }
265         return handled;
266 }
267
268 static int handle_alias(int *argcp, const char ***argv)
269 {
270         int envchanged = 0, ret = 0, saved_errno = errno;
271         int count, option_count;
272         const char **new_argv;
273         const char *alias_command;
274         char *alias_string;
275
276         alias_command = (*argv)[0];
277         alias_string = alias_lookup(alias_command);
278         if (alias_string) {
279                 if (alias_string[0] == '!') {
280                         if (*argcp > 1) {
281                                 struct strbuf buf;
282
283                                 if (strbuf_init(&buf, PATH_MAX) < 0 ||
284                                     strbuf_addstr(&buf, alias_string) < 0 ||
285                                     sq_quote_argv(&buf, (*argv) + 1,
286                                                   PATH_MAX) < 0)
287                                         die("Failed to allocate memory.");
288                                 free(alias_string);
289                                 alias_string = buf.buf;
290                         }
291                         ret = system(alias_string + 1);
292                         if (ret >= 0 && WIFEXITED(ret) &&
293                             WEXITSTATUS(ret) != 127)
294                                 exit(WEXITSTATUS(ret));
295                         die("Failed to run '%s' when expanding alias '%s'",
296                             alias_string + 1, alias_command);
297                 }
298                 count = split_cmdline(alias_string, &new_argv);
299                 if (count < 0)
300                         die("Bad alias.%s string", alias_command);
301                 option_count = handle_options(&new_argv, &count, &envchanged);
302                 if (envchanged)
303                         die("alias '%s' changes environment variables\n"
304                                  "You can use '!perf' in the alias to do this.",
305                                  alias_command);
306                 memmove(new_argv - option_count, new_argv,
307                                 count * sizeof(char *));
308                 new_argv -= option_count;
309
310                 if (count < 1)
311                         die("empty alias for %s", alias_command);
312
313                 if (!strcmp(alias_command, new_argv[0]))
314                         die("recursive alias: %s", alias_command);
315
316                 new_argv = realloc(new_argv, sizeof(char *) *
317                                     (count + *argcp + 1));
318                 /* insert after command name */
319                 memcpy(new_argv + count, *argv + 1, sizeof(char *) * *argcp);
320                 new_argv[count + *argcp] = NULL;
321
322                 *argv = new_argv;
323                 *argcp += count - 1;
324
325                 ret = 1;
326         }
327
328         errno = saved_errno;
329
330         return ret;
331 }
332
333 const char perf_version_string[] = PERF_VERSION;
334
335 #define RUN_SETUP       (1<<0)
336 #define USE_PAGER       (1<<1)
337
338 static int run_builtin(struct cmd_struct *p, int argc, const char **argv)
339 {
340         int status;
341         struct stat st;
342         const char *prefix;
343         char sbuf[STRERR_BUFSIZE];
344
345         prefix = NULL;
346         if (p->option & RUN_SETUP)
347                 prefix = NULL; /* setup_perf_directory(); */
348
349         if (use_browser == -1)
350                 use_browser = check_browser_config(p->cmd);
351
352         if (use_pager == -1 && p->option & RUN_SETUP)
353                 use_pager = check_pager_config(p->cmd);
354         if (use_pager == -1 && p->option & USE_PAGER)
355                 use_pager = 1;
356         commit_pager_choice();
357
358         perf_env__set_cmdline(&perf_env, argc, argv);
359         status = p->fn(argc, argv, prefix);
360         perf_config__exit();
361         exit_browser(status);
362         perf_env__exit(&perf_env);
363         bpf__clear();
364
365         if (status)
366                 return status & 0xff;
367
368         /* Somebody closed stdout? */
369         if (fstat(fileno(stdout), &st))
370                 return 0;
371         /* Ignore write errors for pipes and sockets.. */
372         if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode))
373                 return 0;
374
375         status = 1;
376         /* Check for ENOSPC and EIO errors.. */
377         if (fflush(stdout)) {
378                 fprintf(stderr, "write failure on standard output: %s",
379                         str_error_r(errno, sbuf, sizeof(sbuf)));
380                 goto out;
381         }
382         if (ferror(stdout)) {
383                 fprintf(stderr, "unknown write failure on standard output");
384                 goto out;
385         }
386         if (fclose(stdout)) {
387                 fprintf(stderr, "close failed on standard output: %s",
388                         str_error_r(errno, sbuf, sizeof(sbuf)));
389                 goto out;
390         }
391         status = 0;
392 out:
393         return status;
394 }
395
396 static void handle_internal_command(int argc, const char **argv)
397 {
398         const char *cmd = argv[0];
399         unsigned int i;
400         static const char ext[] = STRIP_EXTENSION;
401
402         if (sizeof(ext) > 1) {
403                 i = strlen(argv[0]) - strlen(ext);
404                 if (i > 0 && !strcmp(argv[0] + i, ext)) {
405                         char *argv0 = strdup(argv[0]);
406                         argv[0] = cmd = argv0;
407                         argv0[i] = '\0';
408                 }
409         }
410
411         /* Turn "perf cmd --help" into "perf help cmd" */
412         if (argc > 1 && !strcmp(argv[1], "--help")) {
413                 argv[1] = argv[0];
414                 argv[0] = cmd = "help";
415         }
416
417         for (i = 0; i < ARRAY_SIZE(commands); i++) {
418                 struct cmd_struct *p = commands+i;
419                 if (strcmp(p->cmd, cmd))
420                         continue;
421                 exit(run_builtin(p, argc, argv));
422         }
423 }
424
425 static void execv_dashed_external(const char **argv)
426 {
427         char *cmd;
428         const char *tmp;
429         int status;
430
431         if (asprintf(&cmd, "perf-%s", argv[0]) < 0)
432                 goto do_die;
433
434         /*
435          * argv[0] must be the perf command, but the argv array
436          * belongs to the caller, and may be reused in
437          * subsequent loop iterations. Save argv[0] and
438          * restore it on error.
439          */
440         tmp = argv[0];
441         argv[0] = cmd;
442
443         /*
444          * if we fail because the command is not found, it is
445          * OK to return. Otherwise, we just pass along the status code.
446          */
447         status = run_command_v_opt(argv, 0);
448         if (status != -ERR_RUN_COMMAND_EXEC) {
449                 if (IS_RUN_COMMAND_ERR(status)) {
450 do_die:
451                         die("unable to run '%s'", argv[0]);
452                 }
453                 exit(-status);
454         }
455         errno = ENOENT; /* as if we called execvp */
456
457         argv[0] = tmp;
458         zfree(&cmd);
459 }
460
461 static int run_argv(int *argcp, const char ***argv)
462 {
463         int done_alias = 0;
464
465         while (1) {
466                 /* See if it's an internal command */
467                 handle_internal_command(*argcp, *argv);
468
469                 /* .. then try the external ones */
470                 execv_dashed_external(*argv);
471
472                 /* It could be an alias -- this works around the insanity
473                  * of overriding "perf log" with "perf show" by having
474                  * alias.log = show
475                  */
476                 if (done_alias || !handle_alias(argcp, argv))
477                         break;
478                 done_alias = 1;
479         }
480
481         return done_alias;
482 }
483
484 static void pthread__block_sigwinch(void)
485 {
486         sigset_t set;
487
488         sigemptyset(&set);
489         sigaddset(&set, SIGWINCH);
490         pthread_sigmask(SIG_BLOCK, &set, NULL);
491 }
492
493 void pthread__unblock_sigwinch(void)
494 {
495         sigset_t set;
496
497         sigemptyset(&set);
498         sigaddset(&set, SIGWINCH);
499         pthread_sigmask(SIG_UNBLOCK, &set, NULL);
500 }
501
502 #ifdef _SC_LEVEL1_DCACHE_LINESIZE
503 #define cache_line_size(cacheline_sizep) *cacheline_sizep = sysconf(_SC_LEVEL1_DCACHE_LINESIZE)
504 #else
505 static void cache_line_size(int *cacheline_sizep)
506 {
507         if (sysfs__read_int("devices/system/cpu/cpu0/cache/index0/coherency_line_size", cacheline_sizep))
508                 pr_debug("cannot determine cache line size");
509 }
510 #endif
511
512 int main(int argc, const char **argv)
513 {
514         const char *cmd;
515         char sbuf[STRERR_BUFSIZE];
516         int value;
517
518         /* libsubcmd init */
519         exec_cmd_init("perf", PREFIX, PERF_EXEC_PATH, EXEC_PATH_ENVIRONMENT);
520         pager_init(PERF_PAGER_ENVIRONMENT);
521
522         /* The page_size is placed in util object. */
523         page_size = sysconf(_SC_PAGE_SIZE);
524         cache_line_size(&cacheline_size);
525
526         if (sysctl__read_int("kernel/perf_event_max_stack", &value) == 0)
527                 sysctl_perf_event_max_stack = value;
528
529         if (sysctl__read_int("kernel/perf_event_max_contexts_per_stack", &value) == 0)
530                 sysctl_perf_event_max_contexts_per_stack = value;
531
532         cmd = extract_argv0_path(argv[0]);
533         if (!cmd)
534                 cmd = "perf-help";
535
536         srandom(time(NULL));
537
538         perf_config__init();
539         perf_config(perf_default_config, NULL);
540         set_buildid_dir(NULL);
541
542         /* get debugfs/tracefs mount point from /proc/mounts */
543         tracing_path_mount();
544
545         /*
546          * "perf-xxxx" is the same as "perf xxxx", but we obviously:
547          *
548          *  - cannot take flags in between the "perf" and the "xxxx".
549          *  - cannot execute it externally (since it would just do
550          *    the same thing over again)
551          *
552          * So we just directly call the internal command handler, and
553          * die if that one cannot handle it.
554          */
555         if (!prefixcmp(cmd, "perf-")) {
556                 cmd += 5;
557                 argv[0] = cmd;
558                 handle_internal_command(argc, argv);
559                 fprintf(stderr, "cannot handle %s internally", cmd);
560                 goto out;
561         }
562         if (!prefixcmp(cmd, "trace")) {
563 #ifdef HAVE_LIBAUDIT_SUPPORT
564                 setup_path();
565                 argv[0] = "trace";
566                 return cmd_trace(argc, argv, NULL);
567 #else
568                 fprintf(stderr,
569                         "trace command not available: missing audit-libs devel package at build time.\n");
570                 goto out;
571 #endif
572         }
573         /* Look for flags.. */
574         argv++;
575         argc--;
576         handle_options(&argv, &argc, NULL);
577         commit_pager_choice();
578
579         if (argc > 0) {
580                 if (!prefixcmp(argv[0], "--"))
581                         argv[0] += 2;
582         } else {
583                 /* The user didn't specify a command; give them help */
584                 printf("\n usage: %s\n\n", perf_usage_string);
585                 list_common_cmds_help();
586                 printf("\n %s\n\n", perf_more_info_string);
587                 goto out;
588         }
589         cmd = argv[0];
590
591         test_attr__init();
592
593         /*
594          * We use PATH to find perf commands, but we prepend some higher
595          * precedence paths: the "--exec-path" option, the PERF_EXEC_PATH
596          * environment, and the $(perfexecdir) from the Makefile at build
597          * time.
598          */
599         setup_path();
600         /*
601          * Block SIGWINCH notifications so that the thread that wants it can
602          * unblock and get syscalls like select interrupted instead of waiting
603          * forever while the signal goes to some other non interested thread.
604          */
605         pthread__block_sigwinch();
606
607         perf_debug_setup();
608
609         while (1) {
610                 static int done_help;
611                 int was_alias = run_argv(&argc, &argv);
612
613                 if (errno != ENOENT)
614                         break;
615
616                 if (was_alias) {
617                         fprintf(stderr, "Expansion of alias '%s' failed; "
618                                 "'%s' is not a perf-command\n",
619                                 cmd, argv[0]);
620                         goto out;
621                 }
622                 if (!done_help) {
623                         cmd = argv[0] = help_unknown_cmd(cmd);
624                         done_help = 1;
625                 } else
626                         break;
627         }
628
629         fprintf(stderr, "Failed to run command '%s': %s\n",
630                 cmd, str_error_r(errno, sbuf, sizeof(sbuf)));
631 out:
632         return 1;
633 }