xref: /linux/tools/perf/builtin-help.c (revision bf4afc53b77aeaa48b5409da5c8da6bb4eff7f43)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * builtin-help.c
4  *
5  * Builtin help command
6  */
7 #include "util/cache.h"
8 #include "util/config.h"
9 #include "util/strbuf.h"
10 #include "builtin.h"
11 #include <subcmd/exec-cmd.h>
12 #include <subcmd/parse-options.h>
13 #include <subcmd/run-command.h>
14 #include <subcmd/help.h>
15 #include "util/debug.h"
16 #include "util/util.h"
17 #include <linux/kernel.h>
18 #include <linux/string.h>
19 #include <linux/zalloc.h>
20 #include <errno.h>
21 #include <limits.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <unistd.h>
28 
29 static struct man_viewer_list {
30 	struct man_viewer_list *next;
31 	char name[0];
32 } *man_viewer_list;
33 
34 static struct man_viewer_info_list {
35 	struct man_viewer_info_list *next;
36 	const char *info;
37 	char name[0];
38 } *man_viewer_info_list;
39 
40 enum help_format {
41 	HELP_FORMAT_NONE,
42 	HELP_FORMAT_MAN,
43 	HELP_FORMAT_INFO,
44 	HELP_FORMAT_WEB,
45 };
46 
47 static enum help_format parse_help_format(const char *format)
48 {
49 	if (!strcmp(format, "man"))
50 		return HELP_FORMAT_MAN;
51 	if (!strcmp(format, "info"))
52 		return HELP_FORMAT_INFO;
53 	if (!strcmp(format, "web") || !strcmp(format, "html"))
54 		return HELP_FORMAT_WEB;
55 
56 	pr_err("unrecognized help format '%s'", format);
57 	return HELP_FORMAT_NONE;
58 }
59 
60 static const char *get_man_viewer_info(const char *name)
61 {
62 	struct man_viewer_info_list *viewer;
63 
64 	for (viewer = man_viewer_info_list; viewer; viewer = viewer->next) {
65 		if (!strcasecmp(name, viewer->name))
66 			return viewer->info;
67 	}
68 	return NULL;
69 }
70 
71 static int check_emacsclient_version(void)
72 {
73 	struct strbuf buffer = STRBUF_INIT;
74 	struct child_process ec_process;
75 	const char *argv_ec[] = { "emacsclient", "--version", NULL };
76 	int version;
77 	int ret = -1;
78 
79 	/* emacsclient prints its version number on stderr */
80 	memset(&ec_process, 0, sizeof(ec_process));
81 	ec_process.argv = argv_ec;
82 	ec_process.err = -1;
83 	ec_process.stdout_to_stderr = 1;
84 	if (start_command(&ec_process)) {
85 		fprintf(stderr, "Failed to start emacsclient.\n");
86 		return -1;
87 	}
88 	if (strbuf_read(&buffer, ec_process.err, 20) < 0) {
89 		fprintf(stderr, "Failed to read emacsclient version\n");
90 		goto out;
91 	}
92 	close(ec_process.err);
93 
94 	/*
95 	 * Don't bother checking return value, because "emacsclient --version"
96 	 * seems to always exits with code 1.
97 	 */
98 	finish_command(&ec_process);
99 
100 	if (!strstarts(buffer.buf, "emacsclient")) {
101 		fprintf(stderr, "Failed to parse emacsclient version.\n");
102 		goto out;
103 	}
104 
105 	version = atoi(buffer.buf + strlen("emacsclient"));
106 
107 	if (version < 22) {
108 		fprintf(stderr,
109 			"emacsclient version '%d' too old (< 22).\n",
110 			version);
111 	} else
112 		ret = 0;
113 out:
114 	strbuf_release(&buffer);
115 	return ret;
116 }
117 
118 static void exec_failed(const char *cmd)
119 {
120 	char sbuf[STRERR_BUFSIZE];
121 	pr_warning("failed to exec '%s': %s", cmd, str_error_r(errno, sbuf, sizeof(sbuf)));
122 }
123 
124 static void exec_woman_emacs(const char *path, const char *page)
125 {
126 	if (!check_emacsclient_version()) {
127 		/* This works only with emacsclient version >= 22. */
128 		char *man_page;
129 
130 		if (!path)
131 			path = "emacsclient";
132 		if (asprintf(&man_page, "(woman \"%s\")", page) > 0) {
133 			execlp(path, "emacsclient", "-e", man_page, NULL);
134 			free(man_page);
135 		}
136 		exec_failed(path);
137 	}
138 }
139 
140 static void exec_man_konqueror(const char *path, const char *page)
141 {
142 	const char *display = getenv("DISPLAY");
143 
144 	if (display && *display) {
145 		char *man_page;
146 		const char *filename = "kfmclient";
147 
148 		/* It's simpler to launch konqueror using kfmclient. */
149 		if (path) {
150 			const char *file = strrchr(path, '/');
151 			if (file && !strcmp(file + 1, "konqueror")) {
152 				char *new = strdup(path);
153 				char *dest = strrchr(new, '/');
154 
155 				/* strlen("konqueror") == strlen("kfmclient") */
156 				strcpy(dest + 1, "kfmclient");
157 				path = new;
158 			}
159 			if (file)
160 				filename = file;
161 		} else
162 			path = "kfmclient";
163 		if (asprintf(&man_page, "man:%s(1)", page) > 0) {
164 			execlp(path, filename, "newTab", man_page, NULL);
165 			free(man_page);
166 		}
167 		exec_failed(path);
168 	}
169 }
170 
171 static void exec_man_man(const char *path, const char *page)
172 {
173 	if (!path)
174 		path = "man";
175 	execlp(path, "man", page, NULL);
176 	exec_failed(path);
177 }
178 
179 static void exec_man_cmd(const char *cmd, const char *page)
180 {
181 	char *shell_cmd;
182 
183 	if (asprintf(&shell_cmd, "%s %s", cmd, page) > 0) {
184 		execl("/bin/sh", "sh", "-c", shell_cmd, NULL);
185 		free(shell_cmd);
186 	}
187 	exec_failed(cmd);
188 }
189 
190 static void add_man_viewer(const char *name)
191 {
192 	struct man_viewer_list **p = &man_viewer_list;
193 	size_t len = strlen(name);
194 
195 	while (*p)
196 		p = &((*p)->next);
197 	*p = zalloc(sizeof(**p) + len + 1);
198 	strcpy((*p)->name, name);
199 }
200 
201 static int supported_man_viewer(const char *name, size_t len)
202 {
203 	return (!strncasecmp("man", name, len) ||
204 		!strncasecmp("woman", name, len) ||
205 		!strncasecmp("konqueror", name, len));
206 }
207 
208 static void do_add_man_viewer_info(const char *name,
209 				   size_t len,
210 				   const char *value)
211 {
212 	struct man_viewer_info_list *new = zalloc(sizeof(*new) + len + 1);
213 
214 	strncpy(new->name, name, len);
215 	new->info = strdup(value);
216 	new->next = man_viewer_info_list;
217 	man_viewer_info_list = new;
218 }
219 
220 static void unsupported_man_viewer(const char *name, const char *var)
221 {
222 	pr_warning("'%s': path for unsupported man viewer.\n"
223 		   "Please consider using 'man.<tool>.%s' instead.", name, var);
224 }
225 
226 static int add_man_viewer_path(const char *name,
227 			       size_t len,
228 			       const char *value)
229 {
230 	if (supported_man_viewer(name, len))
231 		do_add_man_viewer_info(name, len, value);
232 	else
233 		unsupported_man_viewer(name, "cmd");
234 
235 	return 0;
236 }
237 
238 static int add_man_viewer_cmd(const char *name,
239 			      size_t len,
240 			      const char *value)
241 {
242 	if (supported_man_viewer(name, len))
243 		unsupported_man_viewer(name, "path");
244 	else
245 		do_add_man_viewer_info(name, len, value);
246 
247 	return 0;
248 }
249 
250 static int add_man_viewer_info(const char *var, const char *value)
251 {
252 	const char *name = var + 4;
253 	const char *subkey = strrchr(name, '.');
254 
255 	if (!subkey) {
256 		pr_err("Config with no key for man viewer: %s", name);
257 		return -1;
258 	}
259 
260 	if (!strcmp(subkey, ".path")) {
261 		if (!value)
262 			return config_error_nonbool(var);
263 		return add_man_viewer_path(name, subkey - name, value);
264 	}
265 	if (!strcmp(subkey, ".cmd")) {
266 		if (!value)
267 			return config_error_nonbool(var);
268 		return add_man_viewer_cmd(name, subkey - name, value);
269 	}
270 
271 	pr_warning("'%s': unsupported man viewer sub key.", subkey);
272 	return 0;
273 }
274 
275 static int perf_help_config(const char *var, const char *value, void *cb)
276 {
277 	enum help_format *help_formatp = cb;
278 
279 	if (!strcmp(var, "help.format")) {
280 		if (!value)
281 			return config_error_nonbool(var);
282 		*help_formatp = parse_help_format(value);
283 		if (*help_formatp == HELP_FORMAT_NONE)
284 			return -1;
285 		return 0;
286 	}
287 	if (!strcmp(var, "man.viewer")) {
288 		if (!value)
289 			return config_error_nonbool(var);
290 		add_man_viewer(value);
291 		return 0;
292 	}
293 	if (strstarts(var, "man."))
294 		return add_man_viewer_info(var, value);
295 
296 	return 0;
297 }
298 
299 static struct cmdnames main_cmds, other_cmds;
300 
301 void list_common_cmds_help(void)
302 {
303 	const struct cmdname_help {
304 		const char *name;
305 		const char *help;
306 	} common_cmds[] = {
307 		{"annotate", "Read perf.data (created by perf record) and display annotated code"},
308 		{"archive",
309 		 "Create archive with object files with build-ids found in perf.data file"},
310 		{"bench", "General framework for benchmark suites"},
311 		{"buildid-cache", "Manage build-id cache."},
312 		{"buildid-list", "List the buildids in a perf.data file"},
313 		{"c2c", "Shared Data C2C/HITM Analyzer."},
314 		{"config", "Get and set variables in a configuration file."},
315 		{"daemon", "Run record sessions on background"},
316 		{"data", "Data file related processing"},
317 		{"diff", "Read perf.data files and display the differential profile"},
318 		{"evlist", "List the event names in a perf.data file"},
319 		{"ftrace", "simple wrapper for kernel's ftrace functionality"},
320 		{"inject", "Filter to augment the events stream with additional information"},
321 		{"iostat", "Show I/O performance metrics"},
322 		{"kallsyms", "Searches running kernel for symbols"},
323 		{"kvm", "Tool to trace/measure kvm guest os"},
324 		{"list", "List all symbolic event types"},
325 		{"mem", "Profile memory accesses"},
326 		{"record", "Run a command and record its profile into perf.data"},
327 		{"report", "Read perf.data (created by perf record) and display the profile"},
328 		{"script", "Read perf.data (created by perf record) and display trace output"},
329 		{"stat", "Run a command and gather performance counter statistics"},
330 		{"test", "Runs sanity tests."},
331 		{"top", "System profiling tool."},
332 		{"version", "display the version of perf binary"},
333 	#ifdef HAVE_LIBELF_SUPPORT
334 		{"probe", "Define new dynamic tracepoints"},
335 	#endif /* HAVE_LIBELF_SUPPORT */
336 	#ifdef HAVE_LIBTRACEEVENT
337 		{"trace", "strace inspired tool"},
338 		{"kmem", "Tool to trace/measure kernel memory properties"},
339 		{"kwork", "Tool to trace/measure kernel work properties (latencies)"},
340 		{"lock", "Analyze lock events"},
341 		{"sched", "Tool to trace/measure scheduler properties (latencies)"},
342 		{"timechart", "Tool to visualize total system behavior during a workload"},
343 	#endif /* HAVE_LIBTRACEEVENT */
344 	};
345 	size_t longest = 0;
346 
347 	for (size_t i = 0; i < ARRAY_SIZE(common_cmds); i++) {
348 		if (longest < strlen(common_cmds[i].name))
349 			longest = strlen(common_cmds[i].name);
350 	}
351 
352 	puts(" The most commonly used perf commands are:");
353 	for (size_t i = 0; i < ARRAY_SIZE(common_cmds); i++) {
354 		printf("   %-*s   ", (int)longest, common_cmds[i].name);
355 		puts(common_cmds[i].help);
356 	}
357 }
358 
359 static const char *cmd_to_page(const char *perf_cmd)
360 {
361 	char *s;
362 
363 	if (!perf_cmd)
364 		return "perf";
365 	else if (strstarts(perf_cmd, "perf"))
366 		return perf_cmd;
367 
368 	return asprintf(&s, "perf-%s", perf_cmd) < 0 ? NULL : s;
369 }
370 
371 static void setup_man_path(void)
372 {
373 	char *new_path;
374 	const char *old_path = getenv("MANPATH");
375 
376 	/* We should always put ':' after our path. If there is no
377 	 * old_path, the ':' at the end will let 'man' to try
378 	 * system-wide paths after ours to find the manual page. If
379 	 * there is old_path, we need ':' as delimiter. */
380 	if (asprintf(&new_path, "%s:%s", system_path(PERF_MAN_PATH), old_path ?: "") > 0) {
381 		setenv("MANPATH", new_path, 1);
382 		free(new_path);
383 	} else {
384 		pr_err("Unable to setup man path");
385 	}
386 }
387 
388 static void exec_viewer(const char *name, const char *page)
389 {
390 	const char *info = get_man_viewer_info(name);
391 
392 	if (!strcasecmp(name, "man"))
393 		exec_man_man(info, page);
394 	else if (!strcasecmp(name, "woman"))
395 		exec_woman_emacs(info, page);
396 	else if (!strcasecmp(name, "konqueror"))
397 		exec_man_konqueror(info, page);
398 	else if (info)
399 		exec_man_cmd(info, page);
400 	else
401 		pr_warning("'%s': unknown man viewer.", name);
402 }
403 
404 static int show_man_page(const char *perf_cmd)
405 {
406 	struct man_viewer_list *viewer;
407 	const char *page = cmd_to_page(perf_cmd);
408 	const char *fallback = getenv("PERF_MAN_VIEWER");
409 
410 	setup_man_path();
411 	for (viewer = man_viewer_list; viewer; viewer = viewer->next)
412 		exec_viewer(viewer->name, page); /* will return when unable */
413 
414 	if (fallback)
415 		exec_viewer(fallback, page);
416 	exec_viewer("man", page);
417 
418 	pr_err("no man viewer handled the request");
419 	return -1;
420 }
421 
422 static int show_info_page(const char *perf_cmd)
423 {
424 	const char *page = cmd_to_page(perf_cmd);
425 	setenv("INFOPATH", system_path(PERF_INFO_PATH), 1);
426 	execlp("info", "info", "perfman", page, NULL);
427 	return -1;
428 }
429 
430 static int get_html_page_path(char **page_path, const char *page)
431 {
432 	struct stat st;
433 	const char *html_path = system_path(PERF_HTML_PATH);
434 	char path[PATH_MAX];
435 
436 	/* Check that we have a perf documentation directory. */
437 	if (stat(mkpath(path, sizeof(path), "%s/perf.html", html_path), &st)
438 	    || !S_ISREG(st.st_mode)) {
439 		pr_err("'%s': not a documentation directory.", html_path);
440 		return -1;
441 	}
442 
443 	return asprintf(page_path, "%s/%s.html", html_path, page);
444 }
445 
446 /*
447  * If open_html is not defined in a platform-specific way (see for
448  * example compat/mingw.h), we use the script web--browse to display
449  * HTML.
450  */
451 #ifndef open_html
452 static void open_html(const char *path)
453 {
454 	execl_cmd("web--browse", "-c", "help.browser", path, NULL);
455 }
456 #endif
457 
458 static int show_html_page(const char *perf_cmd)
459 {
460 	const char *page = cmd_to_page(perf_cmd);
461 	char *page_path; /* it leaks but we exec below */
462 
463 	if (get_html_page_path(&page_path, page) < 0)
464 		return -1;
465 
466 	open_html(page_path);
467 
468 	return 0;
469 }
470 
471 int cmd_help(int argc, const char **argv)
472 {
473 	bool show_all = false;
474 	enum help_format help_format = HELP_FORMAT_MAN;
475 	struct option builtin_help_options[] = {
476 	OPT_BOOLEAN('a', "all", &show_all, "print all available commands"),
477 	OPT_SET_UINT('m', "man", &help_format, "show man page", HELP_FORMAT_MAN),
478 	OPT_SET_UINT('w', "web", &help_format, "show manual in web browser",
479 			HELP_FORMAT_WEB),
480 	OPT_SET_UINT('i', "info", &help_format, "show info page",
481 			HELP_FORMAT_INFO),
482 	OPT_END(),
483 	};
484 	const char * const builtin_help_subcommands[] = {
485 		"buildid-cache", "buildid-list", "diff", "evlist", "help", "list",
486 		"record", "report", "bench", "stat", "timechart", "top", "annotate",
487 		"script", "sched", "kallsyms", "kmem", "lock", "kvm", "test", "inject", "mem", "data",
488 #ifdef HAVE_LIBELF_SUPPORT
489 		"probe",
490 #endif
491 		"trace",
492 	NULL };
493 	const char *builtin_help_usage[] = {
494 		"perf help [--all] [--man|--web|--info] [command]",
495 		NULL
496 	};
497 	int rc;
498 
499 	load_command_list("perf-", &main_cmds, &other_cmds);
500 
501 	rc = perf_config(perf_help_config, &help_format);
502 	if (rc)
503 		return rc;
504 
505 	argc = parse_options_subcommand(argc, argv, builtin_help_options,
506 			builtin_help_subcommands, builtin_help_usage, 0);
507 
508 	if (show_all) {
509 		printf("\n Usage: %s\n\n", perf_usage_string);
510 		list_commands("perf commands", &main_cmds, &other_cmds);
511 		printf(" %s\n\n", perf_more_info_string);
512 		return 0;
513 	}
514 
515 	if (!argv[0]) {
516 		printf("\n usage: %s\n\n", perf_usage_string);
517 		list_common_cmds_help();
518 		printf("\n %s\n\n", perf_more_info_string);
519 		return 0;
520 	}
521 
522 	switch (help_format) {
523 	case HELP_FORMAT_MAN:
524 		rc = show_man_page(argv[0]);
525 		break;
526 	case HELP_FORMAT_INFO:
527 		rc = show_info_page(argv[0]);
528 		break;
529 	case HELP_FORMAT_WEB:
530 		rc = show_html_page(argv[0]);
531 		break;
532 	case HELP_FORMAT_NONE:
533 		/* fall-through */
534 	default:
535 		rc = -1;
536 		break;
537 	}
538 
539 	return rc;
540 }
541