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