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