xref: /linux/tools/perf/perf.c (revision 877a7a11050ee4d465364c57f8fbf78f6b1a2559)
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 #include <linux/kernel.h>
26 
27 const char perf_usage_string[] =
28 	"perf [--version] [--help] [OPTIONS] COMMAND [ARGS]";
29 
30 const char perf_more_info_string[] =
31 	"See 'perf help COMMAND' for more information on a specific command.";
32 
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 **);
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 	{ "ftrace",	cmd_ftrace,	0 },
76 };
77 
78 struct pager_config {
79 	const char *cmd;
80 	int val;
81 };
82 
83 static int pager_command_config(const char *var, const char *value, void *data)
84 {
85 	struct pager_config *c = data;
86 	if (!prefixcmp(var, "pager.") && !strcmp(var + 6, c->cmd))
87 		c->val = perf_config_bool(var, value);
88 	return 0;
89 }
90 
91 /* returns 0 for "no pager", 1 for "use pager", and -1 for "not specified" */
92 int check_pager_config(const char *cmd)
93 {
94 	int err;
95 	struct pager_config c;
96 	c.cmd = cmd;
97 	c.val = -1;
98 	err = perf_config(pager_command_config, &c);
99 	return err ?: c.val;
100 }
101 
102 static int browser_command_config(const char *var, const char *value, void *data)
103 {
104 	struct pager_config *c = data;
105 	if (!prefixcmp(var, "tui.") && !strcmp(var + 4, c->cmd))
106 		c->val = perf_config_bool(var, value);
107 	if (!prefixcmp(var, "gtk.") && !strcmp(var + 4, c->cmd))
108 		c->val = perf_config_bool(var, value) ? 2 : 0;
109 	return 0;
110 }
111 
112 /*
113  * returns 0 for "no tui", 1 for "use tui", 2 for "use gtk",
114  * and -1 for "not specified"
115  */
116 static int check_browser_config(const char *cmd)
117 {
118 	int err;
119 	struct pager_config c;
120 	c.cmd = cmd;
121 	c.val = -1;
122 	err = perf_config(browser_command_config, &c);
123 	return err ?: c.val;
124 }
125 
126 static void commit_pager_choice(void)
127 {
128 	switch (use_pager) {
129 	case 0:
130 		setenv(PERF_PAGER_ENVIRONMENT, "cat", 1);
131 		break;
132 	case 1:
133 		/* setup_pager(); */
134 		break;
135 	default:
136 		break;
137 	}
138 }
139 
140 struct option options[] = {
141 	OPT_ARGUMENT("help", "help"),
142 	OPT_ARGUMENT("version", "version"),
143 	OPT_ARGUMENT("exec-path", "exec-path"),
144 	OPT_ARGUMENT("html-path", "html-path"),
145 	OPT_ARGUMENT("paginate", "paginate"),
146 	OPT_ARGUMENT("no-pager", "no-pager"),
147 	OPT_ARGUMENT("debugfs-dir", "debugfs-dir"),
148 	OPT_ARGUMENT("buildid-dir", "buildid-dir"),
149 	OPT_ARGUMENT("list-cmds", "list-cmds"),
150 	OPT_ARGUMENT("list-opts", "list-opts"),
151 	OPT_ARGUMENT("debug", "debug"),
152 	OPT_END()
153 };
154 
155 static int handle_options(const char ***argv, int *argc, int *envchanged)
156 {
157 	int handled = 0;
158 
159 	while (*argc > 0) {
160 		const char *cmd = (*argv)[0];
161 		if (cmd[0] != '-')
162 			break;
163 
164 		/*
165 		 * For legacy reasons, the "version" and "help"
166 		 * commands can be written with "--" prepended
167 		 * to make them look like flags.
168 		 */
169 		if (!strcmp(cmd, "--help") || !strcmp(cmd, "--version"))
170 			break;
171 
172 		/*
173 		 * Shortcut for '-h' and '-v' options to invoke help
174 		 * and version command.
175 		 */
176 		if (!strcmp(cmd, "-h")) {
177 			(*argv)[0] = "--help";
178 			break;
179 		}
180 
181 		if (!strcmp(cmd, "-v")) {
182 			(*argv)[0] = "--version";
183 			break;
184 		}
185 
186 		/*
187 		 * Check remaining flags.
188 		 */
189 		if (!prefixcmp(cmd, CMD_EXEC_PATH)) {
190 			cmd += strlen(CMD_EXEC_PATH);
191 			if (*cmd == '=')
192 				set_argv_exec_path(cmd + 1);
193 			else {
194 				puts(get_argv_exec_path());
195 				exit(0);
196 			}
197 		} else if (!strcmp(cmd, "--html-path")) {
198 			puts(system_path(PERF_HTML_PATH));
199 			exit(0);
200 		} else if (!strcmp(cmd, "-p") || !strcmp(cmd, "--paginate")) {
201 			use_pager = 1;
202 		} else if (!strcmp(cmd, "--no-pager")) {
203 			use_pager = 0;
204 			if (envchanged)
205 				*envchanged = 1;
206 		} else if (!strcmp(cmd, "--debugfs-dir")) {
207 			if (*argc < 2) {
208 				fprintf(stderr, "No directory given for --debugfs-dir.\n");
209 				usage(perf_usage_string);
210 			}
211 			tracing_path_set((*argv)[1]);
212 			if (envchanged)
213 				*envchanged = 1;
214 			(*argv)++;
215 			(*argc)--;
216 		} else if (!strcmp(cmd, "--buildid-dir")) {
217 			if (*argc < 2) {
218 				fprintf(stderr, "No directory given for --buildid-dir.\n");
219 				usage(perf_usage_string);
220 			}
221 			set_buildid_dir((*argv)[1]);
222 			if (envchanged)
223 				*envchanged = 1;
224 			(*argv)++;
225 			(*argc)--;
226 		} else if (!prefixcmp(cmd, CMD_DEBUGFS_DIR)) {
227 			tracing_path_set(cmd + strlen(CMD_DEBUGFS_DIR));
228 			fprintf(stderr, "dir: %s\n", tracing_path);
229 			if (envchanged)
230 				*envchanged = 1;
231 		} else if (!strcmp(cmd, "--list-cmds")) {
232 			unsigned int i;
233 
234 			for (i = 0; i < ARRAY_SIZE(commands); i++) {
235 				struct cmd_struct *p = commands+i;
236 				printf("%s ", p->cmd);
237 			}
238 			putchar('\n');
239 			exit(0);
240 		} else if (!strcmp(cmd, "--list-opts")) {
241 			unsigned int i;
242 
243 			for (i = 0; i < ARRAY_SIZE(options)-1; i++) {
244 				struct option *p = options+i;
245 				printf("--%s ", p->long_name);
246 			}
247 			putchar('\n');
248 			exit(0);
249 		} else if (!strcmp(cmd, "--debug")) {
250 			if (*argc < 2) {
251 				fprintf(stderr, "No variable specified for --debug.\n");
252 				usage(perf_usage_string);
253 			}
254 			if (perf_debug_option((*argv)[1]))
255 				usage(perf_usage_string);
256 
257 			(*argv)++;
258 			(*argc)--;
259 		} else {
260 			fprintf(stderr, "Unknown option: %s\n", cmd);
261 			usage(perf_usage_string);
262 		}
263 
264 		(*argv)++;
265 		(*argc)--;
266 		handled++;
267 	}
268 	return handled;
269 }
270 
271 #define RUN_SETUP	(1<<0)
272 #define USE_PAGER	(1<<1)
273 
274 static int run_builtin(struct cmd_struct *p, int argc, const char **argv)
275 {
276 	int status;
277 	struct stat st;
278 	char sbuf[STRERR_BUFSIZE];
279 
280 	if (use_browser == -1)
281 		use_browser = check_browser_config(p->cmd);
282 
283 	if (use_pager == -1 && p->option & RUN_SETUP)
284 		use_pager = check_pager_config(p->cmd);
285 	if (use_pager == -1 && p->option & USE_PAGER)
286 		use_pager = 1;
287 	commit_pager_choice();
288 
289 	perf_env__set_cmdline(&perf_env, argc, argv);
290 	status = p->fn(argc, argv);
291 	perf_config__exit();
292 	exit_browser(status);
293 	perf_env__exit(&perf_env);
294 	bpf__clear();
295 
296 	if (status)
297 		return status & 0xff;
298 
299 	/* Somebody closed stdout? */
300 	if (fstat(fileno(stdout), &st))
301 		return 0;
302 	/* Ignore write errors for pipes and sockets.. */
303 	if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode))
304 		return 0;
305 
306 	status = 1;
307 	/* Check for ENOSPC and EIO errors.. */
308 	if (fflush(stdout)) {
309 		fprintf(stderr, "write failure on standard output: %s",
310 			str_error_r(errno, sbuf, sizeof(sbuf)));
311 		goto out;
312 	}
313 	if (ferror(stdout)) {
314 		fprintf(stderr, "unknown write failure on standard output");
315 		goto out;
316 	}
317 	if (fclose(stdout)) {
318 		fprintf(stderr, "close failed on standard output: %s",
319 			str_error_r(errno, sbuf, sizeof(sbuf)));
320 		goto out;
321 	}
322 	status = 0;
323 out:
324 	return status;
325 }
326 
327 static void handle_internal_command(int argc, const char **argv)
328 {
329 	const char *cmd = argv[0];
330 	unsigned int i;
331 	static const char ext[] = STRIP_EXTENSION;
332 
333 	if (sizeof(ext) > 1) {
334 		i = strlen(argv[0]) - strlen(ext);
335 		if (i > 0 && !strcmp(argv[0] + i, ext)) {
336 			char *argv0 = strdup(argv[0]);
337 			argv[0] = cmd = argv0;
338 			argv0[i] = '\0';
339 		}
340 	}
341 
342 	/* Turn "perf cmd --help" into "perf help cmd" */
343 	if (argc > 1 && !strcmp(argv[1], "--help")) {
344 		argv[1] = argv[0];
345 		argv[0] = cmd = "help";
346 	}
347 
348 	for (i = 0; i < ARRAY_SIZE(commands); i++) {
349 		struct cmd_struct *p = commands+i;
350 		if (strcmp(p->cmd, cmd))
351 			continue;
352 		exit(run_builtin(p, argc, argv));
353 	}
354 }
355 
356 static void execv_dashed_external(const char **argv)
357 {
358 	char *cmd;
359 	const char *tmp;
360 	int status;
361 
362 	if (asprintf(&cmd, "perf-%s", argv[0]) < 0)
363 		goto do_die;
364 
365 	/*
366 	 * argv[0] must be the perf command, but the argv array
367 	 * belongs to the caller, and may be reused in
368 	 * subsequent loop iterations. Save argv[0] and
369 	 * restore it on error.
370 	 */
371 	tmp = argv[0];
372 	argv[0] = cmd;
373 
374 	/*
375 	 * if we fail because the command is not found, it is
376 	 * OK to return. Otherwise, we just pass along the status code.
377 	 */
378 	status = run_command_v_opt(argv, 0);
379 	if (status != -ERR_RUN_COMMAND_EXEC) {
380 		if (IS_RUN_COMMAND_ERR(status)) {
381 do_die:
382 			pr_err("FATAL: unable to run '%s'", argv[0]);
383 			status = -128;
384 		}
385 		exit(-status);
386 	}
387 	errno = ENOENT; /* as if we called execvp */
388 
389 	argv[0] = tmp;
390 	zfree(&cmd);
391 }
392 
393 static int run_argv(int *argcp, const char ***argv)
394 {
395 	/* See if it's an internal command */
396 	handle_internal_command(*argcp, *argv);
397 
398 	/* .. then try the external ones */
399 	execv_dashed_external(*argv);
400 	return 0;
401 }
402 
403 static void pthread__block_sigwinch(void)
404 {
405 	sigset_t set;
406 
407 	sigemptyset(&set);
408 	sigaddset(&set, SIGWINCH);
409 	pthread_sigmask(SIG_BLOCK, &set, NULL);
410 }
411 
412 void pthread__unblock_sigwinch(void)
413 {
414 	sigset_t set;
415 
416 	sigemptyset(&set);
417 	sigaddset(&set, SIGWINCH);
418 	pthread_sigmask(SIG_UNBLOCK, &set, NULL);
419 }
420 
421 #ifdef _SC_LEVEL1_DCACHE_LINESIZE
422 #define cache_line_size(cacheline_sizep) *cacheline_sizep = sysconf(_SC_LEVEL1_DCACHE_LINESIZE)
423 #else
424 static void cache_line_size(int *cacheline_sizep)
425 {
426 	if (sysfs__read_int("devices/system/cpu/cpu0/cache/index0/coherency_line_size", cacheline_sizep))
427 		pr_debug("cannot determine cache line size");
428 }
429 #endif
430 
431 int main(int argc, const char **argv)
432 {
433 	int err;
434 	const char *cmd;
435 	char sbuf[STRERR_BUFSIZE];
436 	int value;
437 
438 	/* libsubcmd init */
439 	exec_cmd_init("perf", PREFIX, PERF_EXEC_PATH, EXEC_PATH_ENVIRONMENT);
440 	pager_init(PERF_PAGER_ENVIRONMENT);
441 
442 	/* The page_size is placed in util object. */
443 	page_size = sysconf(_SC_PAGE_SIZE);
444 	cache_line_size(&cacheline_size);
445 
446 	if (sysctl__read_int("kernel/perf_event_max_stack", &value) == 0)
447 		sysctl_perf_event_max_stack = value;
448 
449 	if (sysctl__read_int("kernel/perf_event_max_contexts_per_stack", &value) == 0)
450 		sysctl_perf_event_max_contexts_per_stack = value;
451 
452 	cmd = extract_argv0_path(argv[0]);
453 	if (!cmd)
454 		cmd = "perf-help";
455 
456 	srandom(time(NULL));
457 
458 	perf_config__init();
459 	err = perf_config(perf_default_config, NULL);
460 	if (err)
461 		return err;
462 	set_buildid_dir(NULL);
463 
464 	/* get debugfs/tracefs mount point from /proc/mounts */
465 	tracing_path_mount();
466 
467 	/*
468 	 * "perf-xxxx" is the same as "perf xxxx", but we obviously:
469 	 *
470 	 *  - cannot take flags in between the "perf" and the "xxxx".
471 	 *  - cannot execute it externally (since it would just do
472 	 *    the same thing over again)
473 	 *
474 	 * So we just directly call the internal command handler, and
475 	 * die if that one cannot handle it.
476 	 */
477 	if (!prefixcmp(cmd, "perf-")) {
478 		cmd += 5;
479 		argv[0] = cmd;
480 		handle_internal_command(argc, argv);
481 		fprintf(stderr, "cannot handle %s internally", cmd);
482 		goto out;
483 	}
484 	if (!prefixcmp(cmd, "trace")) {
485 #ifdef HAVE_LIBAUDIT_SUPPORT
486 		setup_path();
487 		argv[0] = "trace";
488 		return cmd_trace(argc, argv);
489 #else
490 		fprintf(stderr,
491 			"trace command not available: missing audit-libs devel package at build time.\n");
492 		goto out;
493 #endif
494 	}
495 	/* Look for flags.. */
496 	argv++;
497 	argc--;
498 	handle_options(&argv, &argc, NULL);
499 	commit_pager_choice();
500 
501 	if (argc > 0) {
502 		if (!prefixcmp(argv[0], "--"))
503 			argv[0] += 2;
504 	} else {
505 		/* The user didn't specify a command; give them help */
506 		printf("\n usage: %s\n\n", perf_usage_string);
507 		list_common_cmds_help();
508 		printf("\n %s\n\n", perf_more_info_string);
509 		goto out;
510 	}
511 	cmd = argv[0];
512 
513 	test_attr__init();
514 
515 	/*
516 	 * We use PATH to find perf commands, but we prepend some higher
517 	 * precedence paths: the "--exec-path" option, the PERF_EXEC_PATH
518 	 * environment, and the $(perfexecdir) from the Makefile at build
519 	 * time.
520 	 */
521 	setup_path();
522 	/*
523 	 * Block SIGWINCH notifications so that the thread that wants it can
524 	 * unblock and get syscalls like select interrupted instead of waiting
525 	 * forever while the signal goes to some other non interested thread.
526 	 */
527 	pthread__block_sigwinch();
528 
529 	perf_debug_setup();
530 
531 	while (1) {
532 		static int done_help;
533 
534 		run_argv(&argc, &argv);
535 
536 		if (errno != ENOENT)
537 			break;
538 
539 		if (!done_help) {
540 			cmd = argv[0] = help_unknown_cmd(cmd);
541 			done_help = 1;
542 		} else
543 			break;
544 	}
545 
546 	fprintf(stderr, "Failed to run command '%s': %s\n",
547 		cmd, str_error_r(errno, sbuf, sizeof(sbuf)));
548 out:
549 	return 1;
550 }
551