perf.c 15 KB

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