perf.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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 "perf.h"
  11. #include "util/build-id.h"
  12. #include "util/cache.h"
  13. #include "util/env.h"
  14. #include <internal/lib.h> // page_size
  15. #include <subcmd/exec-cmd.h>
  16. #include "util/config.h"
  17. #include <subcmd/run-command.h>
  18. #include "util/parse-events.h"
  19. #include <subcmd/parse-options.h>
  20. #include <subcmd/help.h>
  21. #include "util/debug.h"
  22. #include "util/event.h"
  23. #include "util/util.h" // usage()
  24. #include "ui/ui.h"
  25. #include "perf-sys.h"
  26. #include <api/fs/fs.h>
  27. #include <api/fs/tracing_path.h>
  28. #include <perf/core.h>
  29. #include <errno.h>
  30. #include <pthread.h>
  31. #include <signal.h>
  32. #include <stdlib.h>
  33. #include <time.h>
  34. #include <sys/types.h>
  35. #include <sys/stat.h>
  36. #include <unistd.h>
  37. #include <linux/kernel.h>
  38. #include <linux/string.h>
  39. #include <linux/zalloc.h>
  40. static int use_pager = -1;
  41. static FILE *debug_fp = NULL;
  42. struct cmd_struct {
  43. const char *cmd;
  44. int (*fn)(int, const char **);
  45. int option;
  46. };
  47. static struct cmd_struct commands[] = {
  48. { "archive", NULL, 0 },
  49. { "buildid-cache", cmd_buildid_cache, 0 },
  50. { "buildid-list", cmd_buildid_list, 0 },
  51. { "check", cmd_check, 0 },
  52. { "config", cmd_config, 0 },
  53. { "c2c", cmd_c2c, 0 },
  54. { "diff", cmd_diff, 0 },
  55. { "evlist", cmd_evlist, 0 },
  56. { "help", cmd_help, 0 },
  57. { "iostat", NULL, 0 },
  58. { "kallsyms", cmd_kallsyms, 0 },
  59. { "list", cmd_list, 0 },
  60. { "record", cmd_record, 0 },
  61. { "report", cmd_report, 0 },
  62. { "bench", cmd_bench, 0 },
  63. { "stat", cmd_stat, 0 },
  64. #ifdef HAVE_LIBTRACEEVENT
  65. { "timechart", cmd_timechart, 0 },
  66. #endif
  67. { "top", cmd_top, 0 },
  68. { "annotate", cmd_annotate, 0 },
  69. { "version", cmd_version, 0 },
  70. { "script", cmd_script, 0 },
  71. #ifdef HAVE_LIBTRACEEVENT
  72. { "sched", cmd_sched, 0 },
  73. #endif
  74. #ifdef HAVE_LIBELF_SUPPORT
  75. { "probe", cmd_probe, 0 },
  76. #endif
  77. #ifdef HAVE_LIBTRACEEVENT
  78. { "kmem", cmd_kmem, 0 },
  79. { "lock", cmd_lock, 0 },
  80. #endif
  81. { "kvm", cmd_kvm, 0 },
  82. { "test", cmd_test, 0 },
  83. #if defined(HAVE_LIBTRACEEVENT) && (defined(HAVE_LIBAUDIT_SUPPORT) || defined(HAVE_SYSCALL_TABLE_SUPPORT))
  84. { "trace", cmd_trace, 0 },
  85. #endif
  86. { "inject", cmd_inject, 0 },
  87. { "mem", cmd_mem, 0 },
  88. { "data", cmd_data, 0 },
  89. { "ftrace", cmd_ftrace, 0 },
  90. { "daemon", cmd_daemon, 0 },
  91. #ifdef HAVE_LIBTRACEEVENT
  92. { "kwork", cmd_kwork, 0 },
  93. #endif
  94. };
  95. struct pager_config {
  96. const char *cmd;
  97. int val;
  98. };
  99. static bool same_cmd_with_prefix(const char *var, struct pager_config *c,
  100. const char *header)
  101. {
  102. return (strstarts(var, header) && !strcmp(var + strlen(header), c->cmd));
  103. }
  104. static int pager_command_config(const char *var, const char *value, void *data)
  105. {
  106. struct pager_config *c = data;
  107. if (same_cmd_with_prefix(var, c, "pager."))
  108. c->val = perf_config_bool(var, value);
  109. return 0;
  110. }
  111. /* returns 0 for "no pager", 1 for "use pager", and -1 for "not specified" */
  112. static int check_pager_config(const char *cmd)
  113. {
  114. int err;
  115. struct pager_config c;
  116. c.cmd = cmd;
  117. c.val = -1;
  118. err = perf_config(pager_command_config, &c);
  119. return err ?: c.val;
  120. }
  121. static int browser_command_config(const char *var, const char *value, void *data)
  122. {
  123. struct pager_config *c = data;
  124. if (same_cmd_with_prefix(var, c, "tui."))
  125. c->val = perf_config_bool(var, value);
  126. if (same_cmd_with_prefix(var, c, "gtk."))
  127. c->val = perf_config_bool(var, value) ? 2 : 0;
  128. return 0;
  129. }
  130. /*
  131. * returns 0 for "no tui", 1 for "use tui", 2 for "use gtk",
  132. * and -1 for "not specified"
  133. */
  134. static int check_browser_config(const char *cmd)
  135. {
  136. int err;
  137. struct pager_config c;
  138. c.cmd = cmd;
  139. c.val = -1;
  140. err = perf_config(browser_command_config, &c);
  141. return err ?: c.val;
  142. }
  143. static void commit_pager_choice(void)
  144. {
  145. switch (use_pager) {
  146. case 0:
  147. setenv(PERF_PAGER_ENVIRONMENT, "cat", 1);
  148. break;
  149. case 1:
  150. /* setup_pager(); */
  151. break;
  152. default:
  153. break;
  154. }
  155. }
  156. static int set_debug_file(const char *path)
  157. {
  158. debug_fp = fopen(path, "w");
  159. if (!debug_fp) {
  160. fprintf(stderr, "Open debug file '%s' failed: %s\n",
  161. path, strerror(errno));
  162. return -1;
  163. }
  164. debug_set_file(debug_fp);
  165. return 0;
  166. }
  167. struct option options[] = {
  168. OPT_ARGUMENT("help", "help"),
  169. OPT_ARGUMENT("version", "version"),
  170. OPT_ARGUMENT("exec-path", "exec-path"),
  171. OPT_ARGUMENT("html-path", "html-path"),
  172. OPT_ARGUMENT("paginate", "paginate"),
  173. OPT_ARGUMENT("no-pager", "no-pager"),
  174. OPT_ARGUMENT("debugfs-dir", "debugfs-dir"),
  175. OPT_ARGUMENT("buildid-dir", "buildid-dir"),
  176. OPT_ARGUMENT("list-cmds", "list-cmds"),
  177. OPT_ARGUMENT("list-opts", "list-opts"),
  178. OPT_ARGUMENT("debug", "debug"),
  179. OPT_ARGUMENT("debug-file", "debug-file"),
  180. OPT_END()
  181. };
  182. static int handle_options(const char ***argv, int *argc, int *envchanged)
  183. {
  184. int handled = 0;
  185. while (*argc > 0) {
  186. const char *cmd = (*argv)[0];
  187. if (cmd[0] != '-')
  188. break;
  189. /*
  190. * For legacy reasons, the "version" and "help"
  191. * commands can be written with "--" prepended
  192. * to make them look like flags.
  193. */
  194. if (!strcmp(cmd, "--help") || !strcmp(cmd, "--version"))
  195. break;
  196. /*
  197. * Shortcut for '-h' and '-v' options to invoke help
  198. * and version command.
  199. */
  200. if (!strcmp(cmd, "-h")) {
  201. (*argv)[0] = "--help";
  202. break;
  203. }
  204. if (!strcmp(cmd, "-v")) {
  205. (*argv)[0] = "--version";
  206. break;
  207. }
  208. if (!strcmp(cmd, "-vv")) {
  209. (*argv)[0] = "version";
  210. verbose = 1;
  211. break;
  212. }
  213. /*
  214. * Check remaining flags.
  215. */
  216. if (strstarts(cmd, CMD_EXEC_PATH)) {
  217. cmd += strlen(CMD_EXEC_PATH);
  218. if (*cmd == '=')
  219. set_argv_exec_path(cmd + 1);
  220. else {
  221. puts(get_argv_exec_path());
  222. exit(0);
  223. }
  224. } else if (!strcmp(cmd, "--html-path")) {
  225. puts(system_path(PERF_HTML_PATH));
  226. exit(0);
  227. } else if (!strcmp(cmd, "-p") || !strcmp(cmd, "--paginate")) {
  228. use_pager = 1;
  229. } else if (!strcmp(cmd, "--no-pager")) {
  230. use_pager = 0;
  231. if (envchanged)
  232. *envchanged = 1;
  233. } else if (!strcmp(cmd, "--debugfs-dir")) {
  234. if (*argc < 2) {
  235. fprintf(stderr, "No directory given for --debugfs-dir.\n");
  236. usage(perf_usage_string);
  237. }
  238. tracing_path_set((*argv)[1]);
  239. if (envchanged)
  240. *envchanged = 1;
  241. (*argv)++;
  242. (*argc)--;
  243. } else if (!strcmp(cmd, "--buildid-dir")) {
  244. if (*argc < 2) {
  245. fprintf(stderr, "No directory given for --buildid-dir.\n");
  246. usage(perf_usage_string);
  247. }
  248. set_buildid_dir((*argv)[1]);
  249. if (envchanged)
  250. *envchanged = 1;
  251. (*argv)++;
  252. (*argc)--;
  253. } else if (strstarts(cmd, CMD_DEBUGFS_DIR)) {
  254. tracing_path_set(cmd + strlen(CMD_DEBUGFS_DIR));
  255. fprintf(stderr, "dir: %s\n", tracing_path_mount());
  256. if (envchanged)
  257. *envchanged = 1;
  258. } else if (!strcmp(cmd, "--list-cmds")) {
  259. unsigned int i;
  260. for (i = 0; i < ARRAY_SIZE(commands); i++) {
  261. struct cmd_struct *p = commands+i;
  262. printf("%s ", p->cmd);
  263. }
  264. putchar('\n');
  265. exit(0);
  266. } else if (!strcmp(cmd, "--list-opts")) {
  267. unsigned int i;
  268. for (i = 0; i < ARRAY_SIZE(options)-1; i++) {
  269. struct option *p = options+i;
  270. printf("--%s ", p->long_name);
  271. }
  272. putchar('\n');
  273. exit(0);
  274. } else if (!strcmp(cmd, "--debug")) {
  275. if (*argc < 2) {
  276. fprintf(stderr, "No variable specified for --debug.\n");
  277. usage(perf_usage_string);
  278. }
  279. if (perf_debug_option((*argv)[1]))
  280. usage(perf_usage_string);
  281. (*argv)++;
  282. (*argc)--;
  283. } else if (!strcmp(cmd, "--debug-file")) {
  284. if (*argc < 2) {
  285. fprintf(stderr, "No path given for --debug-file.\n");
  286. usage(perf_usage_string);
  287. }
  288. if (set_debug_file((*argv)[1]))
  289. usage(perf_usage_string);
  290. (*argv)++;
  291. (*argc)--;
  292. } else {
  293. fprintf(stderr, "Unknown option: %s\n", cmd);
  294. usage(perf_usage_string);
  295. }
  296. (*argv)++;
  297. (*argc)--;
  298. handled++;
  299. }
  300. return handled;
  301. }
  302. #define RUN_SETUP (1<<0)
  303. #define USE_PAGER (1<<1)
  304. static int run_builtin(struct cmd_struct *p, int argc, const char **argv)
  305. {
  306. int status;
  307. struct stat st;
  308. char sbuf[STRERR_BUFSIZE];
  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__init(&perf_env);
  317. perf_env__set_cmdline(&perf_env, argc, argv);
  318. status = p->fn(argc, argv);
  319. perf_config__exit();
  320. exit_browser(status);
  321. perf_env__exit(&perf_env);
  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. /* Turn "perf cmd --help" into "perf help cmd" */
  355. if (argc > 1 && !strcmp(argv[1], "--help")) {
  356. argv[1] = argv[0];
  357. argv[0] = cmd = "help";
  358. }
  359. for (i = 0; i < ARRAY_SIZE(commands); i++) {
  360. struct cmd_struct *p = commands+i;
  361. if (p->fn == NULL)
  362. continue;
  363. if (strcmp(p->cmd, cmd))
  364. continue;
  365. exit(run_builtin(p, argc, argv));
  366. }
  367. }
  368. static void execv_dashed_external(const char **argv)
  369. {
  370. char *cmd;
  371. const char *tmp;
  372. int status;
  373. if (asprintf(&cmd, "perf-%s", argv[0]) < 0)
  374. goto do_die;
  375. /*
  376. * argv[0] must be the perf command, but the argv array
  377. * belongs to the caller, and may be reused in
  378. * subsequent loop iterations. Save argv[0] and
  379. * restore it on error.
  380. */
  381. tmp = argv[0];
  382. argv[0] = cmd;
  383. /*
  384. * if we fail because the command is not found, it is
  385. * OK to return. Otherwise, we just pass along the status code.
  386. */
  387. status = run_command_v_opt(argv, 0);
  388. if (status != -ERR_RUN_COMMAND_EXEC) {
  389. if (IS_RUN_COMMAND_ERR(status)) {
  390. do_die:
  391. pr_err("FATAL: unable to run '%s'", argv[0]);
  392. status = -128;
  393. }
  394. exit(-status);
  395. }
  396. errno = ENOENT; /* as if we called execvp */
  397. argv[0] = tmp;
  398. zfree(&cmd);
  399. }
  400. static int run_argv(int *argcp, const char ***argv)
  401. {
  402. /* See if it's an internal command */
  403. handle_internal_command(*argcp, *argv);
  404. /* .. then try the external ones */
  405. execv_dashed_external(*argv);
  406. return 0;
  407. }
  408. static int libperf_print(enum libperf_print_level level,
  409. const char *fmt, va_list ap)
  410. {
  411. return veprintf(level, verbose, fmt, ap);
  412. }
  413. int main(int argc, const char **argv)
  414. {
  415. int err, done_help = 0;
  416. const char *cmd;
  417. char sbuf[STRERR_BUFSIZE];
  418. perf_debug_setup();
  419. /* libsubcmd init */
  420. exec_cmd_init("perf", PREFIX, PERF_EXEC_PATH, EXEC_PATH_ENVIRONMENT);
  421. pager_init(PERF_PAGER_ENVIRONMENT);
  422. libperf_init(libperf_print);
  423. cmd = extract_argv0_path(argv[0]);
  424. if (!cmd)
  425. cmd = "perf-help";
  426. srandom(time(NULL));
  427. /* Setting $PERF_CONFIG makes perf read _only_ the given config file. */
  428. config_exclusive_filename = getenv("PERF_CONFIG");
  429. err = perf_config(perf_default_config, NULL);
  430. if (err)
  431. return err;
  432. set_buildid_dir(NULL);
  433. /*
  434. * "perf-xxxx" is the same as "perf xxxx", but we obviously:
  435. *
  436. * - cannot take flags in between the "perf" and the "xxxx".
  437. * - cannot execute it externally (since it would just do
  438. * the same thing over again)
  439. *
  440. * So we just directly call the internal command handler. If that one
  441. * fails to handle this, then maybe we just run a renamed perf binary
  442. * that contains a dash in its name. To handle this scenario, we just
  443. * fall through and ignore the "xxxx" part of the command string.
  444. */
  445. if (strstarts(cmd, "perf-")) {
  446. cmd += 5;
  447. argv[0] = cmd;
  448. handle_internal_command(argc, argv);
  449. /*
  450. * If the command is handled, the above function does not
  451. * return undo changes and fall through in such a case.
  452. */
  453. cmd -= 5;
  454. argv[0] = cmd;
  455. }
  456. if (strstarts(cmd, "trace")) {
  457. #ifndef HAVE_LIBTRACEEVENT
  458. fprintf(stderr,
  459. "trace command not available: missing libtraceevent devel package at build time.\n");
  460. goto out;
  461. #elif !defined(HAVE_LIBAUDIT_SUPPORT) && !defined(HAVE_SYSCALL_TABLE_SUPPORT)
  462. fprintf(stderr,
  463. "trace command not available: missing audit-libs devel package at build time.\n");
  464. goto out;
  465. #else
  466. setup_path();
  467. argv[0] = "trace";
  468. return cmd_trace(argc, argv);
  469. #endif
  470. }
  471. /* Look for flags.. */
  472. argv++;
  473. argc--;
  474. handle_options(&argv, &argc, NULL);
  475. commit_pager_choice();
  476. if (argc > 0) {
  477. if (strstarts(argv[0], "--"))
  478. argv[0] += 2;
  479. } else {
  480. /* The user didn't specify a command; give them help */
  481. printf("\n usage: %s\n\n", perf_usage_string);
  482. list_common_cmds_help();
  483. printf("\n %s\n\n", perf_more_info_string);
  484. goto out;
  485. }
  486. cmd = argv[0];
  487. test_attr__init();
  488. /*
  489. * We use PATH to find perf commands, but we prepend some higher
  490. * precedence paths: the "--exec-path" option, the PERF_EXEC_PATH
  491. * environment, and the $(perfexecdir) from the Makefile at build
  492. * time.
  493. */
  494. setup_path();
  495. /*
  496. * Block SIGWINCH notifications so that the thread that wants it can
  497. * unblock and get syscalls like select interrupted instead of waiting
  498. * forever while the signal goes to some other non interested thread.
  499. */
  500. pthread__block_sigwinch();
  501. while (1) {
  502. run_argv(&argc, &argv);
  503. if (errno != ENOENT)
  504. break;
  505. if (!done_help) {
  506. struct cmdnames main_cmds = {};
  507. for (unsigned int i = 0; i < ARRAY_SIZE(commands); i++) {
  508. add_cmdname(&main_cmds,
  509. commands[i].cmd,
  510. strlen(commands[i].cmd));
  511. }
  512. cmd = argv[0] = help_unknown_cmd(cmd, &main_cmds);
  513. clean_cmdnames(&main_cmds);
  514. done_help = 1;
  515. if (!cmd)
  516. break;
  517. } else
  518. break;
  519. }
  520. if (cmd) {
  521. fprintf(stderr, "Failed to run command '%s': %s\n",
  522. cmd, str_error_r(errno, sbuf, sizeof(sbuf)));
  523. }
  524. out:
  525. if (debug_fp)
  526. fclose(debug_fp);
  527. return 1;
  528. }