builtin-annotate.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. /*
  2. * builtin-annotate.c
  3. *
  4. * Builtin annotate command: Analyze the perf.data input file,
  5. * look up and read DSOs and symbol information and display
  6. * a histogram of results, along various sorting keys.
  7. */
  8. #include "builtin.h"
  9. #include "util/util.h"
  10. #include "util/color.h"
  11. #include <linux/list.h>
  12. #include "util/cache.h"
  13. #include <linux/rbtree.h>
  14. #include "util/symbol.h"
  15. #include "util/string.h"
  16. #include "perf.h"
  17. #include "util/debug.h"
  18. #include "util/event.h"
  19. #include "util/parse-options.h"
  20. #include "util/parse-events.h"
  21. #include "util/thread.h"
  22. #include "util/sort.h"
  23. #include "util/hist.h"
  24. static char const *input_name = "perf.data";
  25. static int force;
  26. static int input;
  27. static int full_paths;
  28. static int print_line;
  29. static unsigned long page_size;
  30. static unsigned long mmap_window = 32;
  31. struct sym_hist {
  32. u64 sum;
  33. u64 ip[0];
  34. };
  35. struct sym_ext {
  36. struct rb_node node;
  37. double percent;
  38. char *path;
  39. };
  40. struct sym_priv {
  41. struct sym_hist *hist;
  42. struct sym_ext *ext;
  43. };
  44. static struct symbol_conf symbol_conf = {
  45. .priv_size = sizeof(struct sym_priv),
  46. .try_vmlinux_path = true,
  47. };
  48. static const char *sym_hist_filter;
  49. static int symbol_filter(struct map *map __used, struct symbol *sym)
  50. {
  51. if (sym_hist_filter == NULL ||
  52. strcmp(sym->name, sym_hist_filter) == 0) {
  53. struct sym_priv *priv = symbol__priv(sym);
  54. const int size = (sizeof(*priv->hist) +
  55. (sym->end - sym->start) * sizeof(u64));
  56. priv->hist = malloc(size);
  57. if (priv->hist)
  58. memset(priv->hist, 0, size);
  59. return 0;
  60. }
  61. /*
  62. * FIXME: We should really filter it out, as we don't want to go thru symbols
  63. * we're not interested, and if a DSO ends up with no symbols, delete it too,
  64. * but right now the kernel loading routines in symbol.c bail out if no symbols
  65. * are found, fix it later.
  66. */
  67. return 0;
  68. }
  69. /*
  70. * collect histogram counts
  71. */
  72. static void hist_hit(struct hist_entry *he, u64 ip)
  73. {
  74. unsigned int sym_size, offset;
  75. struct symbol *sym = he->sym;
  76. struct sym_priv *priv;
  77. struct sym_hist *h;
  78. he->count++;
  79. if (!sym || !he->map)
  80. return;
  81. priv = symbol__priv(sym);
  82. if (!priv->hist)
  83. return;
  84. sym_size = sym->end - sym->start;
  85. offset = ip - sym->start;
  86. if (verbose)
  87. fprintf(stderr, "%s: ip=%Lx\n", __func__,
  88. he->map->unmap_ip(he->map, ip));
  89. if (offset >= sym_size)
  90. return;
  91. h = priv->hist;
  92. h->sum++;
  93. h->ip[offset]++;
  94. if (verbose >= 3)
  95. printf("%p %s: count++ [ip: %p, %08Lx] => %Ld\n",
  96. (void *)(unsigned long)he->sym->start,
  97. he->sym->name,
  98. (void *)(unsigned long)ip, ip - he->sym->start,
  99. h->ip[offset]);
  100. }
  101. static int hist_entry__add(struct thread *thread, struct map *map,
  102. struct symbol *sym, u64 ip, u64 count, char level)
  103. {
  104. bool hit;
  105. struct hist_entry *he = __hist_entry__add(thread, map, sym, NULL, ip,
  106. count, level, &hit);
  107. if (he == NULL)
  108. return -ENOMEM;
  109. hist_hit(he, ip);
  110. return 0;
  111. }
  112. static int process_sample_event(event_t *event)
  113. {
  114. char level;
  115. u64 ip = event->ip.ip;
  116. struct map *map = NULL;
  117. struct symbol *sym = NULL;
  118. struct thread *thread = threads__findnew(event->ip.pid);
  119. dump_printf("(IP, %d): %d: %p\n", event->header.misc,
  120. event->ip.pid, (void *)(long)ip);
  121. if (thread == NULL) {
  122. fprintf(stderr, "problem processing %d event, skipping it.\n",
  123. event->header.type);
  124. return -1;
  125. }
  126. dump_printf(" ... thread: %s:%d\n", thread->comm, thread->pid);
  127. if (event->header.misc & PERF_RECORD_MISC_KERNEL) {
  128. level = 'k';
  129. sym = kernel_maps__find_function(ip, &map, symbol_filter);
  130. dump_printf(" ...... dso: %s\n",
  131. map ? map->dso->long_name : "<not found>");
  132. } else if (event->header.misc & PERF_RECORD_MISC_USER) {
  133. level = '.';
  134. map = thread__find_map(thread, MAP__FUNCTION, ip);
  135. if (map != NULL) {
  136. ip = map->map_ip(map, ip);
  137. sym = map__find_symbol(map, ip, symbol_filter);
  138. } else {
  139. /*
  140. * If this is outside of all known maps,
  141. * and is a negative address, try to look it
  142. * up in the kernel dso, as it might be a
  143. * vsyscall or vdso (which executes in user-mode).
  144. *
  145. * XXX This is nasty, we should have a symbol list in
  146. * the "[vdso]" dso, but for now lets use the old
  147. * trick of looking in the whole kernel symbol list.
  148. */
  149. if ((long long)ip < 0)
  150. sym = kernel_maps__find_function(ip, &map,
  151. symbol_filter);
  152. }
  153. dump_printf(" ...... dso: %s\n",
  154. map ? map->dso->long_name : "<not found>");
  155. } else {
  156. level = 'H';
  157. dump_printf(" ...... dso: [hypervisor]\n");
  158. }
  159. if (hist_entry__add(thread, map, sym, ip, 1, level)) {
  160. fprintf(stderr, "problem incrementing symbol count, "
  161. "skipping event\n");
  162. return -1;
  163. }
  164. return 0;
  165. }
  166. static int event__process(event_t *self)
  167. {
  168. switch (self->header.type) {
  169. case PERF_RECORD_SAMPLE:
  170. return process_sample_event(self);
  171. case PERF_RECORD_MMAP:
  172. return event__process_mmap(self);
  173. case PERF_RECORD_COMM:
  174. return event__process_comm(self);
  175. case PERF_RECORD_FORK:
  176. return event__process_task(self);
  177. /*
  178. * We dont process them right now but they are fine:
  179. */
  180. case PERF_RECORD_THROTTLE:
  181. case PERF_RECORD_UNTHROTTLE:
  182. return 0;
  183. default:
  184. return -1;
  185. }
  186. return 0;
  187. }
  188. static int parse_line(FILE *file, struct hist_entry *he, u64 len)
  189. {
  190. struct symbol *sym = he->sym;
  191. char *line = NULL, *tmp, *tmp2;
  192. static const char *prev_line;
  193. static const char *prev_color;
  194. unsigned int offset;
  195. size_t line_len;
  196. u64 start;
  197. s64 line_ip;
  198. int ret;
  199. char *c;
  200. if (getline(&line, &line_len, file) < 0)
  201. return -1;
  202. if (!line)
  203. return -1;
  204. c = strchr(line, '\n');
  205. if (c)
  206. *c = 0;
  207. line_ip = -1;
  208. offset = 0;
  209. ret = -2;
  210. /*
  211. * Strip leading spaces:
  212. */
  213. tmp = line;
  214. while (*tmp) {
  215. if (*tmp != ' ')
  216. break;
  217. tmp++;
  218. }
  219. if (*tmp) {
  220. /*
  221. * Parse hexa addresses followed by ':'
  222. */
  223. line_ip = strtoull(tmp, &tmp2, 16);
  224. if (*tmp2 != ':')
  225. line_ip = -1;
  226. }
  227. start = he->map->unmap_ip(he->map, sym->start);
  228. if (line_ip != -1) {
  229. const char *path = NULL;
  230. unsigned int hits = 0;
  231. double percent = 0.0;
  232. const char *color;
  233. struct sym_priv *priv = symbol__priv(sym);
  234. struct sym_ext *sym_ext = priv->ext;
  235. struct sym_hist *h = priv->hist;
  236. offset = line_ip - start;
  237. if (offset < len)
  238. hits = h->ip[offset];
  239. if (offset < len && sym_ext) {
  240. path = sym_ext[offset].path;
  241. percent = sym_ext[offset].percent;
  242. } else if (h->sum)
  243. percent = 100.0 * hits / h->sum;
  244. color = get_percent_color(percent);
  245. /*
  246. * Also color the filename and line if needed, with
  247. * the same color than the percentage. Don't print it
  248. * twice for close colored ip with the same filename:line
  249. */
  250. if (path) {
  251. if (!prev_line || strcmp(prev_line, path)
  252. || color != prev_color) {
  253. color_fprintf(stdout, color, " %s", path);
  254. prev_line = path;
  255. prev_color = color;
  256. }
  257. }
  258. color_fprintf(stdout, color, " %7.2f", percent);
  259. printf(" : ");
  260. color_fprintf(stdout, PERF_COLOR_BLUE, "%s\n", line);
  261. } else {
  262. if (!*line)
  263. printf(" :\n");
  264. else
  265. printf(" : %s\n", line);
  266. }
  267. return 0;
  268. }
  269. static struct rb_root root_sym_ext;
  270. static void insert_source_line(struct sym_ext *sym_ext)
  271. {
  272. struct sym_ext *iter;
  273. struct rb_node **p = &root_sym_ext.rb_node;
  274. struct rb_node *parent = NULL;
  275. while (*p != NULL) {
  276. parent = *p;
  277. iter = rb_entry(parent, struct sym_ext, node);
  278. if (sym_ext->percent > iter->percent)
  279. p = &(*p)->rb_left;
  280. else
  281. p = &(*p)->rb_right;
  282. }
  283. rb_link_node(&sym_ext->node, parent, p);
  284. rb_insert_color(&sym_ext->node, &root_sym_ext);
  285. }
  286. static void free_source_line(struct hist_entry *he, int len)
  287. {
  288. struct sym_priv *priv = symbol__priv(he->sym);
  289. struct sym_ext *sym_ext = priv->ext;
  290. int i;
  291. if (!sym_ext)
  292. return;
  293. for (i = 0; i < len; i++)
  294. free(sym_ext[i].path);
  295. free(sym_ext);
  296. priv->ext = NULL;
  297. root_sym_ext = RB_ROOT;
  298. }
  299. /* Get the filename:line for the colored entries */
  300. static void
  301. get_source_line(struct hist_entry *he, int len, const char *filename)
  302. {
  303. struct symbol *sym = he->sym;
  304. u64 start;
  305. int i;
  306. char cmd[PATH_MAX * 2];
  307. struct sym_ext *sym_ext;
  308. struct sym_priv *priv = symbol__priv(sym);
  309. struct sym_hist *h = priv->hist;
  310. if (!h->sum)
  311. return;
  312. sym_ext = priv->ext = calloc(len, sizeof(struct sym_ext));
  313. if (!priv->ext)
  314. return;
  315. start = he->map->unmap_ip(he->map, sym->start);
  316. for (i = 0; i < len; i++) {
  317. char *path = NULL;
  318. size_t line_len;
  319. u64 offset;
  320. FILE *fp;
  321. sym_ext[i].percent = 100.0 * h->ip[i] / h->sum;
  322. if (sym_ext[i].percent <= 0.5)
  323. continue;
  324. offset = start + i;
  325. sprintf(cmd, "addr2line -e %s %016llx", filename, offset);
  326. fp = popen(cmd, "r");
  327. if (!fp)
  328. continue;
  329. if (getline(&path, &line_len, fp) < 0 || !line_len)
  330. goto next;
  331. sym_ext[i].path = malloc(sizeof(char) * line_len + 1);
  332. if (!sym_ext[i].path)
  333. goto next;
  334. strcpy(sym_ext[i].path, path);
  335. insert_source_line(&sym_ext[i]);
  336. next:
  337. pclose(fp);
  338. }
  339. }
  340. static void print_summary(const char *filename)
  341. {
  342. struct sym_ext *sym_ext;
  343. struct rb_node *node;
  344. printf("\nSorted summary for file %s\n", filename);
  345. printf("----------------------------------------------\n\n");
  346. if (RB_EMPTY_ROOT(&root_sym_ext)) {
  347. printf(" Nothing higher than %1.1f%%\n", MIN_GREEN);
  348. return;
  349. }
  350. node = rb_first(&root_sym_ext);
  351. while (node) {
  352. double percent;
  353. const char *color;
  354. char *path;
  355. sym_ext = rb_entry(node, struct sym_ext, node);
  356. percent = sym_ext->percent;
  357. color = get_percent_color(percent);
  358. path = sym_ext->path;
  359. color_fprintf(stdout, color, " %7.2f %s", percent, path);
  360. node = rb_next(node);
  361. }
  362. }
  363. static void annotate_sym(struct hist_entry *he)
  364. {
  365. struct map *map = he->map;
  366. struct dso *dso = map->dso;
  367. struct symbol *sym = he->sym;
  368. const char *filename = dso->long_name, *d_filename;
  369. u64 len;
  370. char command[PATH_MAX*2];
  371. FILE *file;
  372. if (!filename)
  373. return;
  374. if (verbose)
  375. fprintf(stderr, "%s: filename=%s, sym=%s, start=%Lx, end=%Lx\n",
  376. __func__, filename, sym->name,
  377. map->unmap_ip(map, sym->start),
  378. map->unmap_ip(map, sym->end));
  379. if (full_paths)
  380. d_filename = filename;
  381. else
  382. d_filename = basename(filename);
  383. len = sym->end - sym->start;
  384. if (print_line) {
  385. get_source_line(he, len, filename);
  386. print_summary(filename);
  387. }
  388. printf("\n\n------------------------------------------------\n");
  389. printf(" Percent | Source code & Disassembly of %s\n", d_filename);
  390. printf("------------------------------------------------\n");
  391. if (verbose >= 2)
  392. printf("annotating [%p] %30s : [%p] %30s\n",
  393. dso, dso->long_name, sym, sym->name);
  394. sprintf(command, "objdump --start-address=0x%016Lx --stop-address=0x%016Lx -dS %s|grep -v %s",
  395. map->unmap_ip(map, sym->start), map->unmap_ip(map, sym->end),
  396. filename, filename);
  397. if (verbose >= 3)
  398. printf("doing: %s\n", command);
  399. file = popen(command, "r");
  400. if (!file)
  401. return;
  402. while (!feof(file)) {
  403. if (parse_line(file, he, len) < 0)
  404. break;
  405. }
  406. pclose(file);
  407. if (print_line)
  408. free_source_line(he, len);
  409. }
  410. static void find_annotations(void)
  411. {
  412. struct rb_node *nd;
  413. for (nd = rb_first(&output_hists); nd; nd = rb_next(nd)) {
  414. struct hist_entry *he = rb_entry(nd, struct hist_entry, rb_node);
  415. struct sym_priv *priv;
  416. if (he->sym == NULL)
  417. continue;
  418. priv = symbol__priv(he->sym);
  419. if (priv->hist == NULL)
  420. continue;
  421. annotate_sym(he);
  422. /*
  423. * Since we have a hist_entry per IP for the same symbol, free
  424. * he->sym->hist to signal we already processed this symbol.
  425. */
  426. free(priv->hist);
  427. priv->hist = NULL;
  428. }
  429. }
  430. static int __cmd_annotate(void)
  431. {
  432. int ret, rc = EXIT_FAILURE;
  433. unsigned long offset = 0;
  434. unsigned long head = 0;
  435. struct stat input_stat;
  436. event_t *event;
  437. uint32_t size;
  438. char *buf;
  439. register_idle_thread();
  440. input = open(input_name, O_RDONLY);
  441. if (input < 0) {
  442. perror("failed to open file");
  443. exit(-1);
  444. }
  445. ret = fstat(input, &input_stat);
  446. if (ret < 0) {
  447. perror("failed to stat file");
  448. exit(-1);
  449. }
  450. if (!force && input_stat.st_uid && (input_stat.st_uid != geteuid())) {
  451. fprintf(stderr, "file: %s not owned by current user or root\n", input_name);
  452. exit(-1);
  453. }
  454. if (!input_stat.st_size) {
  455. fprintf(stderr, "zero-sized file, nothing to do!\n");
  456. exit(0);
  457. }
  458. remap:
  459. buf = (char *)mmap(NULL, page_size * mmap_window, PROT_READ,
  460. MAP_SHARED, input, offset);
  461. if (buf == MAP_FAILED) {
  462. perror("failed to mmap file");
  463. exit(-1);
  464. }
  465. more:
  466. event = (event_t *)(buf + head);
  467. size = event->header.size;
  468. if (!size)
  469. size = 8;
  470. if (head + event->header.size >= page_size * mmap_window) {
  471. unsigned long shift = page_size * (head / page_size);
  472. int munmap_ret;
  473. munmap_ret = munmap(buf, page_size * mmap_window);
  474. assert(munmap_ret == 0);
  475. offset += shift;
  476. head -= shift;
  477. goto remap;
  478. }
  479. size = event->header.size;
  480. dump_printf("%p [%p]: event: %d\n",
  481. (void *)(offset + head),
  482. (void *)(long)event->header.size,
  483. event->header.type);
  484. if (!size || event__process(event) < 0) {
  485. dump_printf("%p [%p]: skipping unknown header type: %d\n",
  486. (void *)(offset + head),
  487. (void *)(long)(event->header.size),
  488. event->header.type);
  489. /*
  490. * assume we lost track of the stream, check alignment, and
  491. * increment a single u64 in the hope to catch on again 'soon'.
  492. */
  493. if (unlikely(head & 7))
  494. head &= ~7ULL;
  495. size = 8;
  496. }
  497. head += size;
  498. if (offset + head < (unsigned long)input_stat.st_size)
  499. goto more;
  500. rc = EXIT_SUCCESS;
  501. close(input);
  502. if (dump_trace) {
  503. event__print_totals();
  504. return 0;
  505. }
  506. if (verbose > 3)
  507. threads__fprintf(stdout);
  508. if (verbose > 2)
  509. dsos__fprintf(stdout);
  510. collapse__resort();
  511. output__resort(event__total[0]);
  512. find_annotations();
  513. return rc;
  514. }
  515. static const char * const annotate_usage[] = {
  516. "perf annotate [<options>] <command>",
  517. NULL
  518. };
  519. static const struct option options[] = {
  520. OPT_STRING('i', "input", &input_name, "file",
  521. "input file name"),
  522. OPT_STRING('s', "symbol", &sym_hist_filter, "symbol",
  523. "symbol to annotate"),
  524. OPT_BOOLEAN('f', "force", &force, "don't complain, do it"),
  525. OPT_BOOLEAN('v', "verbose", &verbose,
  526. "be more verbose (show symbol address, etc)"),
  527. OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
  528. "dump raw trace in ASCII"),
  529. OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
  530. "file", "vmlinux pathname"),
  531. OPT_BOOLEAN('m', "modules", &symbol_conf.use_modules,
  532. "load module symbols - WARNING: use only with -k and LIVE kernel"),
  533. OPT_BOOLEAN('l', "print-line", &print_line,
  534. "print matching source lines (may be slow)"),
  535. OPT_BOOLEAN('P', "full-paths", &full_paths,
  536. "Don't shorten the displayed pathnames"),
  537. OPT_END()
  538. };
  539. static void setup_sorting(void)
  540. {
  541. char *tmp, *tok, *str = strdup(sort_order);
  542. for (tok = strtok_r(str, ", ", &tmp);
  543. tok; tok = strtok_r(NULL, ", ", &tmp)) {
  544. if (sort_dimension__add(tok) < 0) {
  545. error("Unknown --sort key: `%s'", tok);
  546. usage_with_options(annotate_usage, options);
  547. }
  548. }
  549. free(str);
  550. }
  551. int cmd_annotate(int argc, const char **argv, const char *prefix __used)
  552. {
  553. if (symbol__init(&symbol_conf) < 0)
  554. return -1;
  555. page_size = getpagesize();
  556. argc = parse_options(argc, argv, options, annotate_usage, 0);
  557. setup_sorting();
  558. if (argc) {
  559. /*
  560. * Special case: if there's an argument left then assume tha
  561. * it's a symbol filter:
  562. */
  563. if (argc > 1)
  564. usage_with_options(annotate_usage, options);
  565. sym_hist_filter = argv[0];
  566. }
  567. setup_pager();
  568. if (field_sep && *field_sep == '.') {
  569. fputs("'.' is the only non valid --field-separator argument\n",
  570. stderr);
  571. exit(129);
  572. }
  573. return __cmd_annotate();
  574. }