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>
45 ELFTC_VCSID("$Id: addr2line.c 3499 2016-11-25 16:06:29Z emaste $");
51 Dwarf_Unsigned call_file;
52 Dwarf_Unsigned call_line;
54 Dwarf_Signed ranges_cnt;
55 struct Func *inlined_caller;
56 STAILQ_ENTRY(Func) next;
65 Dwarf_Signed nsrcfiles;
66 STAILQ_HEAD(, Func) funclist;
70 static struct option longopts[] = {
71 {"addresses", no_argument, NULL, 'a'},
72 {"target" , required_argument, NULL, 'b'},
73 {"demangle", no_argument, NULL, 'C'},
74 {"exe", required_argument, NULL, 'e'},
75 {"functions", no_argument, NULL, 'f'},
76 {"inlines", no_argument, NULL, 'i'},
77 {"section", required_argument, NULL, 'j'},
78 {"pretty-print", no_argument, NULL, 'p'},
79 {"basename", no_argument, NULL, 's'},
80 {"help", no_argument, NULL, 'H'},
81 {"version", no_argument, NULL, 'V'},
85 static int demangle, func, base, inlines, print_addr, pretty_print;
86 static char unknown[] = { '?', '?', '\0' };
87 static Dwarf_Addr section_base;
88 /* Need a new curlopc that stores last lopc value. */
89 static Dwarf_Unsigned curlopc = ~0ULL;
90 static RB_HEAD(cutree, CU) cuhead = RB_INITIALIZER(&cuhead);
93 lopccmp(struct CU *e1, struct CU *e2)
95 return (e1->lopc < e2->lopc ? -1 : e1->lopc > e2->lopc);
98 RB_PROTOTYPE(cutree, CU, entry, lopccmp);
99 RB_GENERATE(cutree, CU, entry, lopccmp)
101 #define USAGE_MESSAGE "\
102 Usage: %s [options] hexaddress...\n\
103 Map program addresses to source file names and line numbers.\n\n\
105 -a | --addresses Display address prior to line number info.\n\
106 -b TGT | --target=TGT (Accepted but ignored).\n\
107 -e EXE | --exe=EXE Use program \"EXE\" to translate addresses.\n\
108 -f | --functions Display function names.\n\
109 -i | --inlines Display caller info for inlined functions.\n\
110 -j NAME | --section=NAME Values are offsets into section \"NAME\".\n\
111 -p | --pretty-print Display line number info and function name\n\
112 in human readable manner.\n\
113 -s | --basename Only show the base name for each file name.\n\
114 -C | --demangle Demangle C++ names.\n\
115 -H | --help Print a help message.\n\
116 -V | --version Print a version identifier and exit.\n"
121 (void) fprintf(stderr, USAGE_MESSAGE, ELFTC_GETPROGNAME());
129 fprintf(stderr, "%s (%s)\n", ELFTC_GETPROGNAME(), elftc_version());
134 * Handle DWARF 4 'offset from' DW_AT_high_pc. Although we don't
135 * fully support DWARF 4, some compilers (like FreeBSD Clang 3.5.1)
136 * generate DW_AT_high_pc as an offset from DW_AT_low_pc.
138 * "If the value of the DW_AT_high_pc is of class address, it is the
139 * relocated address of the first location past the last instruction
140 * associated with the entity; if it is of class constant, the value
141 * is an unsigned integer offset which when added to the low PC gives
142 * the address of the first location past the last instruction
143 * associated with the entity."
145 * DWARF4 spec, section 2.17.2.
148 handle_high_pc(Dwarf_Die die, Dwarf_Unsigned lopc, Dwarf_Unsigned *hipc)
155 ret = dwarf_attr(die, DW_AT_high_pc, &at, &de);
156 if (ret == DW_DLV_ERROR) {
157 warnx("dwarf_attr failed: %s", dwarf_errmsg(de));
160 ret = dwarf_whatform(at, &form, &de);
161 if (ret == DW_DLV_ERROR) {
162 warnx("dwarf_whatform failed: %s", dwarf_errmsg(de));
165 if (dwarf_get_form_class(2, 0, 0, form) == DW_FORM_CLASS_CONSTANT)
172 search_func(struct CU *cu, Dwarf_Unsigned addr)
175 Dwarf_Unsigned lopc, hipc, addr_base;
180 STAILQ_FOREACH(f, &cu->funclist, next) {
181 if (f->ranges != NULL) {
183 for (i = 0; i < f->ranges_cnt; i++) {
184 if (f->ranges[i].dwr_type == DW_RANGES_END)
186 if (f->ranges[i].dwr_type ==
187 DW_RANGES_ADDRESS_SELECTION) {
188 addr_base = f->ranges[i].dwr_addr2;
192 /* DW_RANGES_ENTRY */
193 lopc = f->ranges[i].dwr_addr1 + addr_base;
194 hipc = f->ranges[i].dwr_addr2 + addr_base;
195 if (addr >= lopc && addr < hipc) {
206 } else if (addr >= f->lopc && addr < f->hipc) {
208 (f->lopc >= f0->lopc && f->hipc <= f0->hipc))
217 collect_func(Dwarf_Debug dbg, Dwarf_Die die, struct Func *parent, struct CU *cu)
219 Dwarf_Die ret_die, abst_die, spec_die;
222 Dwarf_Unsigned lopc, hipc, ranges_off;
223 Dwarf_Signed ranges_cnt;
225 Dwarf_Attribute abst_at, spec_at;
226 Dwarf_Ranges *ranges;
227 const char *funcname;
229 int found_ranges, ret;
232 abst_die = spec_die = NULL;
234 if (dwarf_tag(die, &tag, &de)) {
235 warnx("dwarf_tag: %s", dwarf_errmsg(de));
238 if (tag == DW_TAG_subprogram || tag == DW_TAG_entry_point ||
239 tag == DW_TAG_inlined_subroutine) {
241 * Function address range can be specified by either
242 * a DW_AT_ranges attribute which points to a range list or
243 * by a pair of DW_AT_low_pc and DW_AT_high_pc attributes.
248 if (dwarf_attrval_unsigned(die, DW_AT_ranges, &ranges_off,
250 dwarf_get_ranges(dbg, (Dwarf_Off) ranges_off, &ranges,
251 &ranges_cnt, NULL, &de) == DW_DLV_OK) {
252 if (ranges != NULL && ranges_cnt > 0) {
259 * Search for DW_AT_low_pc/DW_AT_high_pc if ranges pointer
262 if (dwarf_attrval_unsigned(die, DW_AT_low_pc, &lopc, &de) ||
263 dwarf_attrval_unsigned(die, DW_AT_high_pc, &hipc, &de))
265 if (handle_high_pc(die, lopc, &hipc) != DW_DLV_OK)
270 * Most common case the function name is stored in DW_AT_name
273 if (dwarf_attrval_string(die, DW_AT_name, &funcname, &de) ==
278 * For inlined function, the actual name is probably in the DIE
279 * referenced by DW_AT_abstract_origin. (if present)
281 if (dwarf_attr(die, DW_AT_abstract_origin, &abst_at, &de) ==
283 dwarf_global_formref(abst_at, &ref, &de) == DW_DLV_OK &&
284 dwarf_offdie(dbg, ref, &abst_die, &de) == DW_DLV_OK &&
285 dwarf_attrval_string(abst_die, DW_AT_name, &funcname,
290 * If DW_AT_name is not present, but DW_AT_specification is
291 * present, then probably the actual name is in the DIE
292 * referenced by DW_AT_specification.
294 if (dwarf_attr(die, DW_AT_specification, &spec_at, &de) ==
296 dwarf_global_formref(spec_at, &ref, &de) == DW_DLV_OK &&
297 dwarf_offdie(dbg, ref, &spec_die, &de) == DW_DLV_OK &&
298 dwarf_attrval_string(spec_die, DW_AT_name, &funcname,
302 /* Skip if no name associated with this DIE. */
306 if ((f = calloc(1, sizeof(*f))) == NULL)
307 err(EXIT_FAILURE, "calloc");
308 if ((f->name = strdup(funcname)) == NULL)
309 err(EXIT_FAILURE, "strdup");
312 f->ranges_cnt = ranges_cnt;
317 if (tag == DW_TAG_inlined_subroutine) {
318 f->inlined_caller = parent;
319 dwarf_attrval_unsigned(die, DW_AT_call_file,
321 dwarf_attrval_unsigned(die, DW_AT_call_line,
324 STAILQ_INSERT_TAIL(&cu->funclist, f, next);
329 /* Search children. */
330 ret = dwarf_child(die, &ret_die, &de);
331 if (ret == DW_DLV_ERROR)
332 warnx("dwarf_child: %s", dwarf_errmsg(de));
333 else if (ret == DW_DLV_OK) {
335 collect_func(dbg, ret_die, f, cu);
337 collect_func(dbg, ret_die, parent, cu);
340 /* Search sibling. */
341 ret = dwarf_siblingof(dbg, die, &ret_die, &de);
342 if (ret == DW_DLV_ERROR)
343 warnx("dwarf_siblingof: %s", dwarf_errmsg(de));
344 else if (ret == DW_DLV_OK)
345 collect_func(dbg, ret_die, parent, cu);
348 dwarf_dealloc(dbg, die, DW_DLA_DIE);
350 if (abst_die != NULL)
351 dwarf_dealloc(dbg, abst_die, DW_DLA_DIE);
353 if (spec_die != NULL)
354 dwarf_dealloc(dbg, spec_die, DW_DLA_DIE);
358 print_inlines(struct CU *cu, struct Func *f, Dwarf_Unsigned call_file,
359 Dwarf_Unsigned call_line)
361 char demangled[1024];
364 if (call_file > 0 && (Dwarf_Signed) call_file <= cu->nsrcfiles)
365 file = cu->srcfiles[call_file - 1];
370 printf(" (inlined by) ");
373 if (demangle && !elftc_demangle(f->name, demangled,
374 sizeof(demangled), 0)) {
376 printf("%s at ", demangled);
378 printf("%s\n", demangled);
381 printf("%s at ", f->name);
383 printf("%s\n", f->name);
386 (void) printf("%s:%ju\n", base ? basename(file) : file,
387 (uintmax_t) call_line);
389 if (f->inlined_caller != NULL)
390 print_inlines(cu, f->inlined_caller, f->call_file,
395 culookup(Dwarf_Unsigned addr)
397 struct CU find, *res;
400 res = RB_NFIND(cutree, &cuhead, &find);
402 if (res->lopc != addr)
403 res = RB_PREV(cutree, &cuhead, res);
404 if (res != NULL && addr >= res->lopc && addr < res->hipc)
407 res = RB_MAX(cutree, &cuhead);
408 if (res != NULL && addr >= res->lopc && addr < res->hipc)
415 translate(Dwarf_Debug dbg, Elf *e, const char* addrstr)
417 Dwarf_Die die, ret_die;
421 Dwarf_Unsigned lopc, hipc, addr, lineno, plineno;
423 Dwarf_Addr lineaddr, plineaddr;
427 const char *funcname;
428 char *file, *file0, *pfile;
429 char demangled[1024];
432 addr = strtoull(addrstr, NULL, 16);
433 addr += section_base;
447 * We resume the CU scan from the last place we found a match.
448 * Because when we have 2 sequential addresses, and the second
449 * one is of the next CU, it is faster to just go to the next CU
450 * instead of starting from the beginning.
452 ret = dwarf_next_cu_header(dbg, NULL, NULL, NULL, NULL, NULL,
454 if (ret == DW_DLV_NO_ENTRY) {
455 if (curlopc == ~0ULL)
457 ret = dwarf_next_cu_header(dbg, NULL, NULL, NULL, NULL,
461 while (dwarf_siblingof(dbg, die, &ret_die, &de) == DW_DLV_OK) {
463 dwarf_dealloc(dbg, die, DW_DLA_DIE);
465 if (dwarf_tag(die, &tag, &de) != DW_DLV_OK) {
466 warnx("dwarf_tag failed: %s",
471 /* XXX: What about DW_TAG_partial_unit? */
472 if (tag == DW_TAG_compile_unit)
476 if (ret_die == NULL) {
477 warnx("could not find DW_TAG_compile_unit die");
480 if (dwarf_attrval_unsigned(die, DW_AT_low_pc, &lopc, &de) ==
484 if (dwarf_attrval_unsigned(die, DW_AT_high_pc, &hipc,
487 * Check if the address falls into the PC
490 if (handle_high_pc(die, lopc, &hipc) !=
494 /* Assume ~0ULL if DW_AT_high_pc not present */
498 if (dwarf_dieoffset(die, &off, &de) != DW_DLV_OK) {
499 warnx("dwarf_dieoffset failed: %s",
504 if (addr >= lopc && addr < hipc) {
505 if ((cu = calloc(1, sizeof(*cu))) == NULL)
506 err(EXIT_FAILURE, "calloc");
511 STAILQ_INIT(&cu->funclist);
512 RB_INSERT(cutree, &cuhead, cu);
520 dwarf_dealloc(dbg, die, DW_DLA_DIE);
525 if (ret != DW_DLV_OK || die == NULL)
529 switch (dwarf_srclines(die, &lbuf, &lcount, &de)) {
532 case DW_DLV_NO_ENTRY:
533 /* If a CU lacks debug info, just skip it. */
536 warnx("dwarf_srclines: %s", dwarf_errmsg(de));
543 for (i = 0; i < lcount; i++) {
544 if (dwarf_lineaddr(lbuf[i], &lineaddr, &de)) {
545 warnx("dwarf_lineaddr: %s", dwarf_errmsg(de));
548 if (dwarf_lineno(lbuf[i], &lineno, &de)) {
549 warnx("dwarf_lineno: %s", dwarf_errmsg(de));
552 if (dwarf_linesrc(lbuf[i], &file0, &de)) {
553 warnx("dwarf_linesrc: %s", dwarf_errmsg(de));
556 if (addr == lineaddr)
558 else if (addr < lineaddr && addr > plineaddr) {
563 plineaddr = lineaddr;
571 if (ret == DW_DLV_OK && (func || inlines) && cu != NULL) {
572 if (cu->srcfiles == NULL)
573 if (dwarf_srcfiles(die, &cu->srcfiles, &cu->nsrcfiles,
575 warnx("dwarf_srcfiles: %s", dwarf_errmsg(de));
576 if (STAILQ_EMPTY(&cu->funclist)) {
577 collect_func(dbg, die, NULL, cu);
580 f = search_func(cu, addr);
586 if ((ec = gelf_getclass(e)) == ELFCLASSNONE) {
587 warnx("gelf_getclass failed: %s", elf_errmsg(-1));
590 if (ec == ELFCLASS32) {
592 printf("0x%08jx: ", (uintmax_t) addr);
594 printf("0x%08jx\n", (uintmax_t) addr);
597 printf("0x%016jx: ", (uintmax_t) addr);
599 printf("0x%016jx\n", (uintmax_t) addr);
604 if (funcname == NULL)
606 if (demangle && !elftc_demangle(funcname, demangled,
607 sizeof(demangled), 0)) {
609 printf("%s at ", demangled);
611 printf("%s\n", demangled);
614 printf("%s at ", funcname);
616 printf("%s\n", funcname);
620 (void) printf("%s:%ju\n", base ? basename(file) : file,
623 if (ret == DW_DLV_OK && inlines && cu != NULL &&
624 cu->srcfiles != NULL && f != NULL && f->inlined_caller != NULL)
625 print_inlines(cu, f->inlined_caller, f->call_file,
630 find_section_base(const char *exe, Elf *e, const char *section)
640 if (gelf_getehdr(e, &eh) != &eh) {
641 warnx("gelf_getehdr failed: %s", elf_errmsg(-1));
645 if (!elf_getshstrndx(e, &shstrndx)) {
646 warnx("elf_getshstrndx failed: %s", elf_errmsg(-1));
653 while ((scn = elf_nextscn(e, scn)) != NULL) {
654 if (gelf_getshdr(scn, &sh) == NULL) {
655 warnx("gelf_getshdr failed: %s", elf_errmsg(-1));
658 if ((name = elf_strptr(e, shstrndx, sh.sh_name)) == NULL)
660 if (!strcmp(section, name)) {
661 if (eh.e_type == ET_EXEC || eh.e_type == ET_DYN) {
663 * For executables, section base is the virtual
664 * address of the specified section.
666 section_base = sh.sh_addr;
667 } else if (eh.e_type == ET_REL) {
669 * For relocatables, section base is the
670 * relative offset of the specified section
671 * to the start of the first section.
675 warnx("unknown e_type %u", eh.e_type);
681 elferr = elf_errno();
683 warnx("elf_nextscn failed: %s", elf_errmsg(elferr));
685 errx(EXIT_FAILURE, "%s: cannot find section %s", exe, section);
689 main(int argc, char **argv)
695 const char *exe, *section;
701 while ((opt = getopt_long(argc, argv, "ab:Ce:fij:psHV", longopts,
746 if ((fd = open(exe, O_RDONLY)) < 0)
747 err(EXIT_FAILURE, "%s", exe);
749 if (caph_rights_limit(fd, cap_rights_init(&rights, CAP_FSTAT,
751 errx(EXIT_FAILURE, "caph_rights_limit");
753 caph_cache_catpages();
754 if (caph_limit_stdio() < 0)
755 errx(EXIT_FAILURE, "failed to limit stdio rights");
756 if (caph_enter() < 0)
757 errx(EXIT_FAILURE, "failed to enter capability mode");
759 if (dwarf_init(fd, DW_DLC_READ, NULL, NULL, &dbg, &de))
760 errx(EXIT_FAILURE, "dwarf_init: %s", dwarf_errmsg(de));
762 if (dwarf_get_elf(dbg, &e, &de) != DW_DLV_OK)
763 errx(EXIT_FAILURE, "dwarf_get_elf: %s", dwarf_errmsg(de));
766 find_section_base(exe, e, section);
771 for (i = 0; i < argc; i++)
772 translate(dbg, e, argv[i]);
774 setvbuf(stdout, NULL, _IOLBF, 0);
775 while (fgets(line, sizeof(line), stdin) != NULL)
776 translate(dbg, e, line);
779 dwarf_finish(dbg, &de);