2 * Copyright (c) 2009 Kai Wang
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 #include <sys/param.h>
30 #include <capsicum_helpers.h>
46 ELFTC_VCSID("$Id: addr2line.c 3499 2016-11-25 16:06:29Z emaste $");
52 Dwarf_Unsigned call_file;
53 Dwarf_Unsigned call_line;
55 Dwarf_Signed ranges_cnt;
56 struct Func *inlined_caller;
57 STAILQ_ENTRY(Func) next;
66 Dwarf_Signed nsrcfiles;
67 STAILQ_HEAD(, Func) funclist;
72 static struct option longopts[] = {
73 {"addresses", no_argument, NULL, 'a'},
74 {"target" , required_argument, NULL, 'b'},
75 {"demangle", no_argument, NULL, 'C'},
76 {"exe", required_argument, NULL, 'e'},
77 {"functions", no_argument, NULL, 'f'},
78 {"inlines", no_argument, NULL, 'i'},
79 {"section", required_argument, NULL, 'j'},
80 {"pretty-print", no_argument, NULL, 'p'},
81 {"basename", no_argument, NULL, 's'},
82 {"help", no_argument, NULL, 'H'},
83 {"version", no_argument, NULL, 'V'},
87 static int demangle, func, base, inlines, print_addr, pretty_print;
88 static char unknown[] = { '?', '?', '\0' };
89 static Dwarf_Addr section_base;
90 /* Need a new curlopc that stores last lopc value. */
91 static Dwarf_Unsigned curlopc = ~0ULL;
92 static RB_HEAD(cutree, CU) cuhead = RB_INITIALIZER(&cuhead);
95 lopccmp(struct CU *e1, struct CU *e2)
97 return (e1->lopc < e2->lopc ? -1 : e1->lopc > e2->lopc);
100 RB_PROTOTYPE(cutree, CU, entry, lopccmp);
101 RB_GENERATE(cutree, CU, entry, lopccmp)
103 #define USAGE_MESSAGE "\
104 Usage: %s [options] hexaddress...\n\
105 Map program addresses to source file names and line numbers.\n\n\
107 -a | --addresses Display address prior to line number info.\n\
108 -b TGT | --target=TGT (Accepted but ignored).\n\
109 -e EXE | --exe=EXE Use program \"EXE\" to translate addresses.\n\
110 -f | --functions Display function names.\n\
111 -i | --inlines Display caller info for inlined functions.\n\
112 -j NAME | --section=NAME Values are offsets into section \"NAME\".\n\
113 -p | --pretty-print Display line number info and function name\n\
114 in human readable manner.\n\
115 -s | --basename Only show the base name for each file name.\n\
116 -C | --demangle Demangle C++ names.\n\
117 -H | --help Print a help message.\n\
118 -V | --version Print a version identifier and exit.\n"
123 (void) fprintf(stderr, USAGE_MESSAGE, ELFTC_GETPROGNAME());
131 fprintf(stderr, "%s (%s)\n", ELFTC_GETPROGNAME(), elftc_version());
136 * Handle DWARF 4 'offset from' DW_AT_high_pc. Although we don't
137 * fully support DWARF 4, some compilers (like FreeBSD Clang 3.5.1)
138 * generate DW_AT_high_pc as an offset from DW_AT_low_pc.
140 * "If the value of the DW_AT_high_pc is of class address, it is the
141 * relocated address of the first location past the last instruction
142 * associated with the entity; if it is of class constant, the value
143 * is an unsigned integer offset which when added to the low PC gives
144 * the address of the first location past the last instruction
145 * associated with the entity."
147 * DWARF4 spec, section 2.17.2.
150 handle_high_pc(Dwarf_Die die, Dwarf_Unsigned lopc, Dwarf_Unsigned *hipc)
157 ret = dwarf_attr(die, DW_AT_high_pc, &at, &de);
158 if (ret == DW_DLV_ERROR) {
159 warnx("dwarf_attr failed: %s", dwarf_errmsg(de));
162 ret = dwarf_whatform(at, &form, &de);
163 if (ret == DW_DLV_ERROR) {
164 warnx("dwarf_whatform failed: %s", dwarf_errmsg(de));
167 if (dwarf_get_form_class(2, 0, 0, form) == DW_FORM_CLASS_CONSTANT)
174 search_func(struct CU *cu, Dwarf_Unsigned addr)
177 Dwarf_Unsigned lopc, hipc, addr_base;
182 STAILQ_FOREACH(f, &cu->funclist, next) {
183 if (f->ranges != NULL) {
185 for (i = 0; i < f->ranges_cnt; i++) {
186 if (f->ranges[i].dwr_type == DW_RANGES_END)
188 if (f->ranges[i].dwr_type ==
189 DW_RANGES_ADDRESS_SELECTION) {
190 addr_base = f->ranges[i].dwr_addr2;
194 /* DW_RANGES_ENTRY */
195 lopc = f->ranges[i].dwr_addr1 + addr_base;
196 hipc = f->ranges[i].dwr_addr2 + addr_base;
197 if (addr >= lopc && addr < hipc) {
208 } else if (addr >= f->lopc && addr < f->hipc) {
210 (f->lopc >= f0->lopc && f->hipc <= f0->hipc))
219 collect_func(Dwarf_Debug dbg, Dwarf_Die die, struct Func *parent, struct CU *cu)
221 Dwarf_Die ret_die, abst_die, spec_die;
224 Dwarf_Unsigned lopc, hipc, ranges_off;
225 Dwarf_Signed ranges_cnt;
227 Dwarf_Attribute abst_at, spec_at;
228 Dwarf_Ranges *ranges;
229 const char *funcname;
231 int found_ranges, ret;
234 abst_die = spec_die = NULL;
236 if (dwarf_tag(die, &tag, &de)) {
237 warnx("dwarf_tag: %s", dwarf_errmsg(de));
240 if (tag == DW_TAG_subprogram || tag == DW_TAG_entry_point ||
241 tag == DW_TAG_inlined_subroutine) {
243 * Function address range can be specified by either
244 * a DW_AT_ranges attribute which points to a range list or
245 * by a pair of DW_AT_low_pc and DW_AT_high_pc attributes.
250 if (dwarf_attrval_unsigned(die, DW_AT_ranges, &ranges_off,
252 dwarf_get_ranges(dbg, (Dwarf_Off) ranges_off, &ranges,
253 &ranges_cnt, NULL, &de) == DW_DLV_OK) {
254 if (ranges != NULL && ranges_cnt > 0) {
261 * Search for DW_AT_low_pc/DW_AT_high_pc if ranges pointer
264 if (dwarf_attrval_unsigned(die, DW_AT_low_pc, &lopc, &de) ||
265 dwarf_attrval_unsigned(die, DW_AT_high_pc, &hipc, &de))
267 if (handle_high_pc(die, lopc, &hipc) != DW_DLV_OK)
272 * Most common case the function name is stored in DW_AT_name
275 if (dwarf_attrval_string(die, DW_AT_name, &funcname, &de) ==
280 * For inlined function, the actual name is probably in the DIE
281 * referenced by DW_AT_abstract_origin. (if present)
283 if (dwarf_attr(die, DW_AT_abstract_origin, &abst_at, &de) ==
285 dwarf_global_formref(abst_at, &ref, &de) == DW_DLV_OK &&
286 dwarf_offdie(dbg, ref, &abst_die, &de) == DW_DLV_OK &&
287 dwarf_attrval_string(abst_die, DW_AT_name, &funcname,
292 * If DW_AT_name is not present, but DW_AT_specification is
293 * present, then probably the actual name is in the DIE
294 * referenced by DW_AT_specification.
296 if (dwarf_attr(die, DW_AT_specification, &spec_at, &de) ==
298 dwarf_global_formref(spec_at, &ref, &de) == DW_DLV_OK &&
299 dwarf_offdie(dbg, ref, &spec_die, &de) == DW_DLV_OK &&
300 dwarf_attrval_string(spec_die, DW_AT_name, &funcname,
304 /* Skip if no name associated with this DIE. */
308 if ((f = calloc(1, sizeof(*f))) == NULL)
309 err(EXIT_FAILURE, "calloc");
310 if ((f->name = strdup(funcname)) == NULL)
311 err(EXIT_FAILURE, "strdup");
314 f->ranges_cnt = ranges_cnt;
319 if (tag == DW_TAG_inlined_subroutine) {
320 f->inlined_caller = parent;
321 dwarf_attrval_unsigned(die, DW_AT_call_file,
323 dwarf_attrval_unsigned(die, DW_AT_call_line,
326 STAILQ_INSERT_TAIL(&cu->funclist, f, next);
331 /* Search children. */
332 ret = dwarf_child(die, &ret_die, &de);
333 if (ret == DW_DLV_ERROR)
334 warnx("dwarf_child: %s", dwarf_errmsg(de));
335 else if (ret == DW_DLV_OK) {
337 collect_func(dbg, ret_die, f, cu);
339 collect_func(dbg, ret_die, parent, cu);
342 /* Search sibling. */
343 ret = dwarf_siblingof(dbg, die, &ret_die, &de);
344 if (ret == DW_DLV_ERROR)
345 warnx("dwarf_siblingof: %s", dwarf_errmsg(de));
346 else if (ret == DW_DLV_OK)
347 collect_func(dbg, ret_die, parent, cu);
351 dwarf_dealloc(dbg, die, DW_DLA_DIE);
353 if (abst_die != NULL)
354 dwarf_dealloc(dbg, abst_die, DW_DLA_DIE);
356 if (spec_die != NULL)
357 dwarf_dealloc(dbg, spec_die, DW_DLA_DIE);
361 print_inlines(struct CU *cu, struct Func *f, Dwarf_Unsigned call_file,
362 Dwarf_Unsigned call_line)
364 char demangled[1024];
367 if (call_file > 0 && (Dwarf_Signed) call_file <= cu->nsrcfiles)
368 file = cu->srcfiles[call_file - 1];
373 printf(" (inlined by) ");
376 if (demangle && !elftc_demangle(f->name, demangled,
377 sizeof(demangled), 0)) {
379 printf("%s at ", demangled);
381 printf("%s\n", demangled);
384 printf("%s at ", f->name);
386 printf("%s\n", f->name);
389 (void) printf("%s:%ju\n", base ? basename(file) : file,
390 (uintmax_t) call_line);
392 if (f->inlined_caller != NULL)
393 print_inlines(cu, f->inlined_caller, f->call_file,
398 culookup(Dwarf_Unsigned addr)
400 struct CU find, *res;
403 res = RB_NFIND(cutree, &cuhead, &find);
405 if (res->lopc != addr)
406 res = RB_PREV(cutree, &cuhead, res);
407 if (res != NULL && addr >= res->lopc && addr < res->hipc)
410 res = RB_MAX(cutree, &cuhead);
411 if (res != NULL && addr >= res->lopc && addr < res->hipc)
418 * Check whether addr falls into range(s) of current CU, and save current CU
419 * to lookup tree if so.
422 check_range(Dwarf_Debug dbg, Dwarf_Die die, Dwarf_Unsigned addr,
426 Dwarf_Unsigned addr_base, lopc, hipc;
427 Dwarf_Off ranges_off;
428 Dwarf_Signed ranges_cnt;
429 Dwarf_Ranges *ranges;
438 ret = dwarf_attrval_unsigned(die, DW_AT_ranges, &ranges_off, &de);
439 if (ret == DW_DLV_NO_ENTRY) {
440 if (dwarf_attrval_unsigned(die, DW_AT_low_pc, &lopc, &de) ==
443 return (DW_DLV_ERROR);
444 if (dwarf_attrval_unsigned(die, DW_AT_high_pc, &hipc,
447 * Check if the address falls into the PC
450 if (handle_high_pc(die, lopc, &hipc) !=
452 return (DW_DLV_ERROR);
454 /* Assume ~0ULL if DW_AT_high_pc not present */
458 if (addr >= lopc && addr < hipc) {
462 } else if (ret == DW_DLV_OK) {
463 ret = dwarf_get_ranges(dbg, ranges_off, &ranges,
464 &ranges_cnt, NULL, &de);
465 if (ret != DW_DLV_OK)
468 if (!ranges || ranges_cnt <= 0)
469 return (DW_DLV_ERROR);
471 for (i = 0; i < ranges_cnt; i++) {
472 if (ranges[i].dwr_type == DW_RANGES_END)
473 return (DW_DLV_NO_ENTRY);
475 if (ranges[i].dwr_type ==
476 DW_RANGES_ADDRESS_SELECTION) {
477 addr_base = ranges[i].dwr_addr2;
481 /* DW_RANGES_ENTRY */
482 lopc = ranges[i].dwr_addr1 + addr_base;
483 hipc = ranges[i].dwr_addr2 + addr_base;
486 return (DW_DLV_ERROR);
488 if (addr >= lopc && addr < hipc){
494 return (DW_DLV_ERROR);
498 if ((*cu = calloc(1, sizeof(struct CU))) == NULL)
499 err(EXIT_FAILURE, "calloc");
504 STAILQ_INIT(&(*cu)->funclist);
505 RB_INSERT(cutree, &cuhead, *cu);
509 return (DW_DLV_NO_ENTRY);
514 translate(Dwarf_Debug dbg, Elf *e, const char* addrstr)
516 Dwarf_Die die, ret_die;
520 Dwarf_Unsigned addr, lineno, plineno;
522 Dwarf_Addr lineaddr, plineaddr;
525 const char *funcname;
526 char *file, *file0, *pfile;
527 char demangled[1024];
530 addr = strtoull(addrstr, NULL, 16);
531 addr += section_base;
546 * We resume the CU scan from the last place we found a match.
547 * Because when we have 2 sequential addresses, and the second
548 * one is of the next CU, it is faster to just go to the next CU
549 * instead of starting from the beginning.
551 ret = dwarf_next_cu_header(dbg, NULL, NULL, NULL, NULL, NULL,
553 if (ret == DW_DLV_NO_ENTRY) {
554 if (curlopc == ~0ULL)
556 ret = dwarf_next_cu_header(dbg, NULL, NULL, NULL, NULL,
560 while (dwarf_siblingof(dbg, die, &ret_die, &de) == DW_DLV_OK) {
562 dwarf_dealloc(dbg, die, DW_DLA_DIE);
564 if (dwarf_tag(die, &tag, &de) != DW_DLV_OK) {
565 warnx("dwarf_tag failed: %s",
570 /* XXX: What about DW_TAG_partial_unit? */
571 if (tag == DW_TAG_compile_unit)
575 if (ret_die == NULL) {
576 warnx("could not find DW_TAG_compile_unit die");
579 ret = check_range(dbg, die, addr, &cu);
580 if (ret == DW_DLV_OK)
582 if (ret == DW_DLV_ERROR)
586 dwarf_dealloc(dbg, die, DW_DLA_DIE);
591 if (ret != DW_DLV_OK || die == NULL)
595 switch (dwarf_srclines(die, &lbuf, &lcount, &de)) {
598 case DW_DLV_NO_ENTRY:
599 /* If a CU lacks debug info, just skip it. */
602 warnx("dwarf_srclines: %s", dwarf_errmsg(de));
609 for (i = 0; i < lcount; i++) {
610 if (dwarf_lineaddr(lbuf[i], &lineaddr, &de)) {
611 warnx("dwarf_lineaddr: %s", dwarf_errmsg(de));
614 if (dwarf_lineno(lbuf[i], &lineno, &de)) {
615 warnx("dwarf_lineno: %s", dwarf_errmsg(de));
618 if (dwarf_linesrc(lbuf[i], &file0, &de)) {
619 warnx("dwarf_linesrc: %s", dwarf_errmsg(de));
622 if (addr == lineaddr)
624 else if (addr < lineaddr && addr > plineaddr) {
629 plineaddr = lineaddr;
637 if (ret == DW_DLV_OK && (func || inlines) && cu != NULL) {
638 if (cu->srcfiles == NULL)
639 if (dwarf_srcfiles(die, &cu->srcfiles, &cu->nsrcfiles,
641 warnx("dwarf_srcfiles: %s", dwarf_errmsg(de));
642 if (STAILQ_EMPTY(&cu->funclist)) {
643 collect_func(dbg, die, NULL, cu);
646 f = search_func(cu, addr);
652 if ((ec = gelf_getclass(e)) == ELFCLASSNONE) {
653 warnx("gelf_getclass failed: %s", elf_errmsg(-1));
656 if (ec == ELFCLASS32) {
658 printf("0x%08jx: ", (uintmax_t) addr);
660 printf("0x%08jx\n", (uintmax_t) addr);
663 printf("0x%016jx: ", (uintmax_t) addr);
665 printf("0x%016jx\n", (uintmax_t) addr);
670 if (funcname == NULL)
672 if (demangle && !elftc_demangle(funcname, demangled,
673 sizeof(demangled), 0)) {
675 printf("%s at ", demangled);
677 printf("%s\n", demangled);
680 printf("%s at ", funcname);
682 printf("%s\n", funcname);
686 (void) printf("%s:%ju\n", base ? basename(file) : file,
689 if (ret == DW_DLV_OK && inlines && cu != NULL &&
690 cu->srcfiles != NULL && f != NULL && f->inlined_caller != NULL)
691 print_inlines(cu, f->inlined_caller, f->call_file,
696 find_section_base(const char *exe, Elf *e, const char *section)
706 if (gelf_getehdr(e, &eh) != &eh) {
707 warnx("gelf_getehdr failed: %s", elf_errmsg(-1));
711 if (!elf_getshstrndx(e, &shstrndx)) {
712 warnx("elf_getshstrndx failed: %s", elf_errmsg(-1));
719 while ((scn = elf_nextscn(e, scn)) != NULL) {
720 if (gelf_getshdr(scn, &sh) == NULL) {
721 warnx("gelf_getshdr failed: %s", elf_errmsg(-1));
724 if ((name = elf_strptr(e, shstrndx, sh.sh_name)) == NULL)
726 if (!strcmp(section, name)) {
727 if (eh.e_type == ET_EXEC || eh.e_type == ET_DYN) {
729 * For executables, section base is the virtual
730 * address of the specified section.
732 section_base = sh.sh_addr;
733 } else if (eh.e_type == ET_REL) {
735 * For relocatables, section base is the
736 * relative offset of the specified section
737 * to the start of the first section.
741 warnx("unknown e_type %u", eh.e_type);
747 elferr = elf_errno();
749 warnx("elf_nextscn failed: %s", elf_errmsg(elferr));
751 errx(EXIT_FAILURE, "%s: cannot find section %s", exe, section);
755 main(int argc, char **argv)
761 const char *exe, *section;
767 while ((opt = getopt_long(argc, argv, "ab:Ce:fij:psHV", longopts,
812 if ((fd = open(exe, O_RDONLY)) < 0)
813 err(EXIT_FAILURE, "%s", exe);
815 if (caph_rights_limit(fd, cap_rights_init(&rights, CAP_FSTAT,
817 errx(EXIT_FAILURE, "caph_rights_limit");
819 caph_cache_catpages();
820 if (caph_limit_stdio() < 0)
821 errx(EXIT_FAILURE, "failed to limit stdio rights");
822 if (caph_enter() < 0)
823 errx(EXIT_FAILURE, "failed to enter capability mode");
825 if (dwarf_init(fd, DW_DLC_READ, NULL, NULL, &dbg, &de))
826 errx(EXIT_FAILURE, "dwarf_init: %s", dwarf_errmsg(de));
828 if (dwarf_get_elf(dbg, &e, &de) != DW_DLV_OK)
829 errx(EXIT_FAILURE, "dwarf_get_elf: %s", dwarf_errmsg(de));
832 find_section_base(exe, e, section);
837 for (i = 0; i < argc; i++)
838 translate(dbg, e, argv[i]);
840 setvbuf(stdout, NULL, _IOLBF, 0);
841 while (fgets(line, sizeof(line), stdin) != NULL)
842 translate(dbg, e, line);
845 dwarf_finish(dbg, &de);