perf.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * perf.c
  4. *
  5. * Performance analysis utility.
  6. *
  7. * This is the main hub from which the sub-commands (perf stat,
  8. * perf top, perf record, perf report, etc.) are started.
  9. */
  10. #include "builtin.h"
  11. #include "util/env.h"
  12. #include <subcmd/exec-cmd.h>
  13. #include "util/config.h"
  14. #include <subcmd/run-command.h>
  15. #include "util/parse-events.h"
  16. #include <subcmd/parse-options.h>
  17. #include "util/bpf-loader.h"
  18. #include "util/debug.h"
  19. #include "util/event.h"
  20. #include <api/fs/fs.h>
  21. #include <api/fs/tracing_path.h>
  22. #include <errno.h>
  23. #include <pthread.h>
  24. #include <signal.h>
  25. #include <stdlib.h>
  26. #include <time.h>
  27. #include <sys/types.h>
  28. #include <sys/stat.h>
  29. #include <unistd.h>
  30. #include <linux/kernel.h>
  31. const char perf_usage_string[] =
  32. "perf [--version] [--help] [OPTIONS] COMMAND [ARGS]";
  33. const char perf_more_info_string[] =
  34. "See 'perf help COMMAND' for more information on a specific command.";
  35. static int use_pager = -1;
  36. const char *input_name;
  37. struct cmd_struct {
  38. const char *cmd;
  39. int (*fn)(int, const char **);
  40. int option;
  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. #if defined(HAVE_LIBAUDIT_SUPPORT) || defined(HAVE_SYSCALL_TABLE_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. struct pager_config {
  78. const char *cmd;
  79. int val;
  80. };
  81. static int pager_command_config(const char *var, const char *value, void *data)
  82. {
  83. struct pager_config *c = data;
  84. if (strstarts(var, "pager.") && !strcmp(var + 6, c->cmd))
  85. c->val = perf_config_bool(var, value);
  86. return 0;
  87. }
  88. /* returns 0 for "no pager", 1 for "use pager", and -1 for "not specified" */
  89. static int check_pager_config(const char *cmd)
  90. {
  91. int err;
  92. struct pager_config c;
  93. c.cmd = cmd;
  94. c.val = -1;
  95. err = perf_config(pager_command_config, &c);
  96. return err ?: c.val;
  97. }
  98. static int browser_command_config(const char *var, const char *value, void *data)
  99. {
  100. struct pager_config *c = data;
  101. if (strstarts(var, "tui.") && !strcmp(var + 4, c->cmd))
  102. c->val = perf_config_bool(var, value);
  103. if (strstarts(var, "gtk.") && !strcmp(var + 4, c->cmd))
  104. c->val = perf_config_bool(var, value) ? 2 : 0;
  105. return 0;
  106. }
  107. /*
  108. * returns 0 for "no tui", 1 for "use tui", 2 for "use gtk",
  109. * and -1 for "not specified"
  110. */
  111. static int check_browser_config(const char *cmd)
  112. {
  113. int err;
  114. struct pager_config c;
  115. c.cmd = cmd;
  116. c.val = -1;
  117. err = perf_config(browser_command_config, &c);
  118. return err ?: c.val;
  119. }
  120. static void commit_pager_choice(void)
  121. {
  122. switch (use_pager) {
  123. case 0:
  124. setenv(PERF_PAGER_ENVIRONMENT, "cat", 1);
  125. break;
  126. case 1:
  127. /* setup_pager(); */
  128. break;
  129. default:
  130. break;
  131. }
  132. }
  133. struct option options[] = {
  134. OPT_ARGUMENT("help", "help"),
  135. OPT_ARGUMENT("version", "version"),
  136. OPT_ARGUMENT("exec-path", "exec-path"),
  137. OPT_ARGUMENT("html-path", "html-path"),
  138. OPT_ARGUMENT("paginate", "paginate"),
  139. OPT_ARGUMENT("no-pager", "no-pager"),
  140. OPT_ARGUMENT("debugfs-dir", "debugfs-dir"),
  141. OPT_ARGUMENT("buildid-dir", "buildid-dir"),
  142. OPT_ARGUMENT("list-cmds", "list-cmds"),
  143. OPT_ARGUMENT("list-opts", "list-opts"),
  144. OPT_ARGUMENT("debug", "debug"),
  145. OPT_END()
  146. };
  147. static int handle_options(const char ***argv, int *argc, int *envchanged)
  148. {
  149. int handled = 0;
  150. while (*argc > 0) {
  151. const char *cmd = (*argv)[0];
  152. if (cmd[0] != '-')
  153. break;
  154. /*
  155. * For legacy reasons, the "version" and "help"
  156. * commands can be written with "--" prepended
  157. * to make them look like flags.
  158. */
  159. if (!strcmp(cmd, "--help") || !strcmp(cmd, "--version"))
  160. break;
  161. /*
  162. * Shortcut for '-h' and '-v' options to invoke help
  163. * and version command.
  164. */
  165. if (!strcmp(cmd, "-h")) {
  166. (*argv)[0] = "--help";
  167. break;
  168. }
  169. if (!strcmp(cmd, "-v")) {
  170. (*argv)[0] = "--version";
  171. break;
  172. }
  173. if (!strcmp(cmd, "-vv")) {
  174. (*argv)[0] = "version";
  175. version_verbose = 1;
  176. break;
  177. }
  178. /*
  179. * Check remaining flags.
  180. */
  181. if (strstarts(cmd, CMD_EXEC_PATH)) {
  182. cmd += strlen(CMD_EXEC_PATH);
  183. if (*cmd == '=')
  184. set_argv_exec_path(cmd + 1);
  185. else {
  186. puts(get_argv_exec_path());
  187. exit(0);
  188. }
  189. } else if (!strcmp(cmd, "--html-path")) {
  190. puts(system_path(PERF_HTML_PATH));
  191. exit(0);
  192. } else if (!strcmp(cmd, "-p") || !strcmp(cmd, "--paginate")) {
  193. use_pager = 1;
  194. } else if (!strcmp(cmd, "--no-pager")) {
  195. use_pager = 0;
  196. if (envchanged)
  197. *envchanged = 1;
  198. } else if (!strcmp(cmd, "--debugfs-dir")) {
  199. if (*argc < 2) {
  200. fprintf(stderr, "No directory given for --debugfs-dir.\n");
  201. usage(perf_usage_string);
  202. }
  203. tracing_path_set((*argv)[1]);
  204. if (envchanged)
  205. *envchanged = 1;
  206. (*argv)++;
  207. (*argc)--;
  208. } else if (!strcmp(cmd, "--buildid-dir")) {
  209. if (*argc < 2) {
  210. fprintf(stderr, "No directory given for --buildid-dir.\n");
  211. usage(perf_usage_string);
  212. }
  213. set_buildid_dir((*argv)[1]);
  214. if (envchanged)
  215. *envchanged = 1;
  216. (*argv)++;
  217. (*argc)--;
  218. } else if (strstarts(cmd, CMD_DEBUGFS_DIR)) {
  219. tracing_path_set(cmd + strlen(CMD_DEBUGFS_DIR));
  220. fprintf(stderr, "dir: %s\n", tracing_path_mount());
  221. if (envchanged)
  222. *envchanged = 1;
  223. } else if (!strcmp(cmd, "--list-cmds")) {
  224. unsigned int i;
  225. for (i = 0; i < ARRAY_SIZE(commands); i++) {
  226. struct cmd_struct *p = commands+i;
  227. printf("%s ", p->cmd);
  228. }
  229. putchar('\n');
  230. exit(0);
  231. } else if (!strcmp(cmd, "--list-opts")) {
  232. unsigned int i;
  233. for (i = 0; i < ARRAY_SIZE(options)-1; i++) {
  234. struct option *p = options+i;
  235. printf("--%s ", p->long_name);
  236. }
  237. putchar('\n');
  238. exit(0);
  239. } else if (!strcmp(cmd, "--debug")) {
  240. if (*argc < 2) {
  241. fprintf(stderr, "No variable specified for --debug.\n");
  242. usage(perf_usage_string);
  243. }
  244. if (perf_debug_option((*argv)[1]))
  245. usage(perf_usage_string);
  246. (*argv)++;
  247. (*argc)--;
  248. } else {
  249. fprintf(stderr, "Unknown option: %s\n", cmd);
  250. usage(perf_usage_string);
  251. }
  252. (*argv)++;
  253. (*argc)--;
  254. handled++;
  255. }
  256. return handled;
  257. }
  258. #define RUN_SETUP (1<<0)
  259. #define USE_PAGER (1<<1)
  260. static int run_builtin(struct cmd_struct *p, int argc, const char **argv)
  261. {
  262. int status;
  263. struct stat st;
  264. char sbuf[STRERR_BUFSIZE];
  265. if (use_browser == -1)
  266. use_browser = check_browser_config(p->cmd);
  267. if (use_pager == -1 && p->option & RUN_SETUP)
  268. use_pager = check_pager_config(p->cmd);
  269. if (use_pager == -1 && p->option & USE_PAGER)
  270. use_pager = 1;
  271. commit_pager_choice();
  272. perf_env__set_cmdline(&perf_env, argc, argv);
  273. status = p->fn(argc, argv);
  274. perf_config__exit();
  275. exit_browser(status);
  276. perf_env__exit(&perf_env);
  277. bpf__clear();
  278. if (status)
  279. return status & 0xff;
  280. /* Somebody closed stdout? */
  281. if (fstat(fileno(stdout), &st))
  282. return 0;
  283. /* Ignore write errors for pipes and sockets.. */
  284. if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode))
  285. return 0;
  286. status = 1;
  287. /* Check for ENOSPC and EIO errors.. */
  288. if (fflush(stdout)) {
  289. fprintf(stderr, "write failure on standard output: %s",
  290. str_error_r(errno, sbuf, sizeof(sbuf)));
  291. goto out;
  292. }
  293. if (ferror(stdout)) {
  294. fprintf(stderr, "unknown write failure on standard output");
  295. goto out;
  296. }
  297. if (fclose(stdout)) {
  298. fprintf(stderr, "close failed on standard output: %s",
  299. str_error_r(errno, sbuf, sizeof(sbuf)));
  300. goto out;
  301. }
  302. status = 0;
  303. out:
  304. return status;
  305. }
  306. static void handle_internal_command(int argc, const char **argv)
  307. {
  308. const char *cmd = argv[0];
  309. unsigned int i;
  310. /* Turn "perf cmd --help" into "perf help cmd" */
  311. if (argc > 1 && !strcmp(argv[1], "--help")) {
  312. argv[1] = argv[0];
  313. argv[0] = cmd = "help";
  314. }
  315. for (i = 0; i < ARRAY_SIZE(commands); i++) {
  316. struct cmd_struct *p = commands+i;
  317. if (strcmp(p->cmd, cmd))
  318. continue;
  319. exit(run_builtin(p, argc, argv));
  320. }
  321. }
  322. static void execv_dashed_external(const char **argv)
  323. {
  324. char *cmd;
  325. const char *tmp;
  326. int status;
  327. if (asprintf(&cmd, "perf-%s", argv[0]) < 0)
  328. goto do_die;
  329. /*
  330. * argv[0] must be the perf command, but the argv array
  331. * belongs to the caller, and may be reused in
  332. * subsequent loop iterations. Save argv[0] and
  333. * restore it on error.
  334. */
  335. tmp = argv[0];
  336. argv[0] = cmd;
  337. /*
  338. * if we fail because the command is not found, it is
  339. * OK to return. Otherwise, we just pass along the status code.
  340. */
  341. status = run_command_v_opt(argv, 0);
  342. if (status != -ERR_RUN_COMMAND_EXEC) {
  343. if (IS_RUN_COMMAND_ERR(status)) {
  344. do_die:
  345. pr_err("FATAL: unable to run '%s'", argv[0]);
  346. status = -128;
  347. }
  348. exit(-status);
  349. }
  350. errno = ENOENT; /* as if we called execvp */
  351. argv[0] = tmp;
  352. zfree(&cmd);
  353. }
  354. static int run_argv(int *argcp, const char ***argv)
  355. {
  356. /* See if it's an internal command */
  357. handle_internal_command(*argcp, *argv);
  358. /* .. then try the external ones */
  359. execv_dashed_external(*argv);
  360. return 0;
  361. }
  362. static void pthread__block_sigwinch(void)
  363. {
  364. sigset_t set;
  365. sigemptyset(&set);
  366. sigaddset(&set, SIGWINCH);
  367. pthread_sigmask(SIG_BLOCK, &set, NULL);
  368. }
  369. void pthread__unblock_sigwinch(void)
  370. {
  371. sigset_t set;
  372. sigemptyset(&set);
  373. sigaddset(&set, SIGWINCH);
  374. pthread_sigmask(SIG_UNBLOCK, &set, NULL);
  375. }
  376. int main(int argc, const char **argv)
  377. {
  378. int err;
  379. const char *cmd;
  380. char sbuf[STRERR_BUFSIZE];
  381. /* libsubcmd init */
  382. exec_cmd_init("perf", PREFIX, PERF_EXEC_PATH, EXEC_PATH_ENVIRONMENT);
  383. pager_init(PERF_PAGER_ENVIRONMENT);
  384. /* The page_size is placed in util object. */
  385. page_size = sysconf(_SC_PAGE_SIZE);
  386. cmd = extract_argv0_path(argv[0]);
  387. if (!cmd)
  388. cmd = "perf-help";
  389. srandom(time(NULL));
  390. /* Setting $PERF_CONFIG makes perf read _only_ the given config file. */
  391. config_exclusive_filename = getenv("PERF_CONFIG");
  392. err = perf_config(perf_default_config, NULL);
  393. if (err)
  394. return err;
  395. set_buildid_dir(NULL);
  396. /*
  397. * "perf-xxxx" is the same as "perf xxxx", but we obviously:
  398. *
  399. * - cannot take flags in between the "perf" and the "xxxx".
  400. * - cannot execute it externally (since it would just do
  401. * the same thing over again)
  402. *
  403. * So we just directly call the internal command handler. If that one
  404. * fails to handle this, then maybe we just run a renamed perf binary
  405. * that contains a dash in its name. To handle this scenario, we just
  406. * fall through and ignore the "xxxx" part of the command string.
  407. */
  408. if (strstarts(cmd, "perf-")) {
  409. cmd += 5;
  410. argv[0] = cmd;
  411. handle_internal_command(argc, argv);
  412. /*
  413. * If the command is handled, the above function does not
  414. * return undo changes and fall through in such a case.
  415. */
  416. cmd -= 5;
  417. argv[0] = cmd;
  418. }
  419. if (strstarts(cmd, "trace")) {
  420. #if defined(HAVE_LIBAUDIT_SUPPORT) || defined(HAVE_SYSCALL_TABLE_SUPPORT)
  421. setup_path();
  422. argv[0] = "trace";
  423. return cmd_trace(argc, argv);
  424. #else
  425. fprintf(stderr,
  426. "trace command not available: missing audit-libs devel package at build time.\n");
  427. goto out;
  428. #endif
  429. }
  430. /* Look for flags.. */
  431. argv++;
  432. argc--;
  433. handle_options(&argv, &argc, NULL);
  434. commit_pager_choice();
  435. if (argc > 0) {
  436. if (strstarts(argv[0], "--"))
  437. argv[0] += 2;
  438. } else {
  439. /* The user didn't specify a command; give them help */
  440. printf("\n usage: %s\n\n", perf_usage_string);
  441. list_common_cmds_help();
  442. printf("\n %s\n\n", perf_more_info_string);
  443. goto out;
  444. }
  445. cmd = argv[0];
  446. test_attr__init();
  447. /*
  448. * We use PATH to find perf commands, but we prepend some higher
  449. * precedence paths: the "--exec-path" option, the PERF_EXEC_PATH
  450. * environment, and the $(perfexecdir) from the Makefile at build
  451. * time.
  452. */
  453. setup_path();
  454. /*
  455. * Block SIGWINCH notifications so that the thread that wants it can
  456. * unblock and get syscalls like select interrupted instead of waiting
  457. * forever while the signal goes to some other non interested thread.
  458. */
  459. pthread__block_sigwinch();
  460. perf_debug_setup();
  461. while (1) {
  462. static int done_help;
  463. run_argv(&argc, &argv);
  464. if (errno != ENOENT)
  465. break;
  466. if (!done_help) {
  467. cmd = argv[0] = help_unknown_cmd(cmd);
  468. done_help = 1;
  469. } else
  470. break;
  471. }
  472. fprintf(stderr, "Failed to run command '%s': %s\n",
  473. cmd, str_error_r(errno, sbuf, sizeof(sbuf)));
  474. out:
  475. return 1;
  476. }