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