xref: /freebsd/contrib/elftoolchain/addr2line/addr2line.c (revision f6a3b357e9be4c6423c85eff9a847163a0d307c8)
1 /*-
2  * Copyright (c) 2009 Kai Wang
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
13  *
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
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/param.h>
28 
29 #include <capsicum_helpers.h>
30 #include <dwarf.h>
31 #include <err.h>
32 #include <fcntl.h>
33 #include <gelf.h>
34 #include <getopt.h>
35 #include <libdwarf.h>
36 #include <libelftc.h>
37 #include <libgen.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 
42 #include "uthash.h"
43 #include "_elftc.h"
44 
45 ELFTC_VCSID("$Id: addr2line.c 3544 2017-06-05 14:51:44Z emaste $");
46 
47 struct Func {
48 	char *name;
49 	Dwarf_Unsigned lopc;
50 	Dwarf_Unsigned hipc;
51 	Dwarf_Unsigned call_file;
52 	Dwarf_Unsigned call_line;
53 	Dwarf_Ranges *ranges;
54 	Dwarf_Signed ranges_cnt;
55 	struct Func *inlined_caller;
56 	STAILQ_ENTRY(Func) next;
57 };
58 
59 struct CU {
60 	Dwarf_Off off;
61 	Dwarf_Unsigned lopc;
62 	Dwarf_Unsigned hipc;
63 	char **srcfiles;
64 	Dwarf_Signed nsrcfiles;
65 	STAILQ_HEAD(, Func) funclist;
66 	UT_hash_handle hh;
67 };
68 
69 static struct option longopts[] = {
70 	{"addresses", no_argument, NULL, 'a'},
71 	{"target" , required_argument, NULL, 'b'},
72 	{"demangle", no_argument, NULL, 'C'},
73 	{"exe", required_argument, NULL, 'e'},
74 	{"functions", no_argument, NULL, 'f'},
75 	{"inlines", no_argument, NULL, 'i'},
76 	{"section", required_argument, NULL, 'j'},
77 	{"pretty-print", no_argument, NULL, 'p'},
78 	{"basename", no_argument, NULL, 's'},
79 	{"help", no_argument, NULL, 'H'},
80 	{"version", no_argument, NULL, 'V'},
81 	{NULL, 0, NULL, 0}
82 };
83 static int demangle, func, base, inlines, print_addr, pretty_print;
84 static char unknown[] = { '?', '?', '\0' };
85 static Dwarf_Addr section_base;
86 static struct CU *culist;
87 
88 #define	USAGE_MESSAGE	"\
89 Usage: %s [options] hexaddress...\n\
90   Map program addresses to source file names and line numbers.\n\n\
91   Options:\n\
92   -a      | --addresses       Display address prior to line number info.\n\
93   -b TGT  | --target=TGT      (Accepted but ignored).\n\
94   -e EXE  | --exe=EXE         Use program \"EXE\" to translate addresses.\n\
95   -f      | --functions       Display function names.\n\
96   -i      | --inlines         Display caller info for inlined functions.\n\
97   -j NAME | --section=NAME    Values are offsets into section \"NAME\".\n\
98   -p      | --pretty-print    Display line number info and function name\n\
99                               in human readable manner.\n\
100   -s      | --basename        Only show the base name for each file name.\n\
101   -C      | --demangle        Demangle C++ names.\n\
102   -H      | --help            Print a help message.\n\
103   -V      | --version         Print a version identifier and exit.\n"
104 
105 static void
106 usage(void)
107 {
108 	(void) fprintf(stderr, USAGE_MESSAGE, ELFTC_GETPROGNAME());
109 	exit(1);
110 }
111 
112 static void
113 version(void)
114 {
115 
116 	fprintf(stderr, "%s (%s)\n", ELFTC_GETPROGNAME(), elftc_version());
117 	exit(0);
118 }
119 
120 /*
121  * Handle DWARF 4 'offset from' DW_AT_high_pc.  Although we don't
122  * fully support DWARF 4, some compilers (like FreeBSD Clang 3.5.1)
123  * generate DW_AT_high_pc as an offset from DW_AT_low_pc.
124  *
125  * "If the value of the DW_AT_high_pc is of class address, it is the
126  * relocated address of the first location past the last instruction
127  * associated with the entity; if it is of class constant, the value
128  * is an unsigned integer offset which when added to the low PC gives
129  * the address of the first location past the last instruction
130  * associated with the entity."
131  *
132  * DWARF4 spec, section 2.17.2.
133  */
134 static int
135 handle_high_pc(Dwarf_Die die, Dwarf_Unsigned lopc, Dwarf_Unsigned *hipc)
136 {
137 	Dwarf_Error de;
138 	Dwarf_Half form;
139 	Dwarf_Attribute at;
140 	int ret;
141 
142 	ret = dwarf_attr(die, DW_AT_high_pc, &at, &de);
143 	if (ret == DW_DLV_ERROR) {
144 		warnx("dwarf_attr failed: %s", dwarf_errmsg(de));
145 		return (ret);
146 	}
147 	ret = dwarf_whatform(at, &form, &de);
148 	if (ret == DW_DLV_ERROR) {
149 		warnx("dwarf_whatform failed: %s", dwarf_errmsg(de));
150 		return (ret);
151 	}
152 	if (dwarf_get_form_class(2, 0, 0, form) == DW_FORM_CLASS_CONSTANT)
153 		*hipc += lopc;
154 
155 	return (DW_DLV_OK);
156 }
157 
158 static struct Func *
159 search_func(struct CU *cu, Dwarf_Unsigned addr)
160 {
161 	struct Func *f, *f0;
162 	Dwarf_Unsigned lopc, hipc, addr_base;
163 	int i;
164 
165 	f0 = NULL;
166 
167 	STAILQ_FOREACH(f, &cu->funclist, next) {
168 		if (f->ranges != NULL) {
169 			addr_base = 0;
170 			for (i = 0; i < f->ranges_cnt; i++) {
171 				if (f->ranges[i].dwr_type == DW_RANGES_END)
172 					break;
173 				if (f->ranges[i].dwr_type ==
174 				    DW_RANGES_ADDRESS_SELECTION) {
175 					addr_base = f->ranges[i].dwr_addr2;
176 					continue;
177 				}
178 
179 				/* DW_RANGES_ENTRY */
180 				lopc = f->ranges[i].dwr_addr1 + addr_base;
181 				hipc = f->ranges[i].dwr_addr2 + addr_base;
182 				if (addr >= lopc && addr < hipc) {
183 					if (f0 == NULL ||
184 					    (lopc >= f0->lopc &&
185 					    hipc <= f0->hipc)) {
186 						f0 = f;
187 						f0->lopc = lopc;
188 						f0->hipc = hipc;
189 						break;
190 					}
191 				}
192 			}
193 		} else if (addr >= f->lopc && addr < f->hipc) {
194 			if (f0 == NULL ||
195 			    (f->lopc >= f0->lopc && f->hipc <= f0->hipc))
196 				f0 = f;
197 		}
198 	}
199 
200 	return (f0);
201 }
202 
203 static void
204 collect_func(Dwarf_Debug dbg, Dwarf_Die die, struct Func *parent, struct CU *cu)
205 {
206 	Dwarf_Die ret_die, abst_die, spec_die;
207 	Dwarf_Error de;
208 	Dwarf_Half tag;
209 	Dwarf_Unsigned lopc, hipc, ranges_off;
210 	Dwarf_Signed ranges_cnt;
211 	Dwarf_Off ref;
212 	Dwarf_Attribute abst_at, spec_at;
213 	Dwarf_Ranges *ranges;
214 	const char *funcname;
215 	struct Func *f;
216 	int found_ranges, ret;
217 
218 	f = NULL;
219 	abst_die = spec_die = NULL;
220 
221 	if (dwarf_tag(die, &tag, &de)) {
222 		warnx("dwarf_tag: %s", dwarf_errmsg(de));
223 		goto cont_search;
224 	}
225 	if (tag == DW_TAG_subprogram || tag == DW_TAG_entry_point ||
226 	    tag == DW_TAG_inlined_subroutine) {
227 		/*
228 		 * Function address range can be specified by either
229 		 * a DW_AT_ranges attribute which points to a range list or
230 		 * by a pair of DW_AT_low_pc and DW_AT_high_pc attributes.
231 		 */
232 		ranges = NULL;
233 		ranges_cnt = 0;
234 		found_ranges = 0;
235 		if (dwarf_attrval_unsigned(die, DW_AT_ranges, &ranges_off,
236 		    &de) == DW_DLV_OK &&
237 		    dwarf_get_ranges(dbg, (Dwarf_Off) ranges_off, &ranges,
238 		    &ranges_cnt, NULL, &de) == DW_DLV_OK) {
239 			if (ranges != NULL && ranges_cnt > 0) {
240 				found_ranges = 1;
241 				goto get_func_name;
242 			}
243 		}
244 
245 		/*
246 		 * Search for DW_AT_low_pc/DW_AT_high_pc if ranges pointer
247 		 * not found.
248 		 */
249 		if (dwarf_attrval_unsigned(die, DW_AT_low_pc, &lopc, &de) ||
250 		    dwarf_attrval_unsigned(die, DW_AT_high_pc, &hipc, &de))
251 			goto cont_search;
252 		if (handle_high_pc(die, lopc, &hipc) != DW_DLV_OK)
253 			goto cont_search;
254 
255 	get_func_name:
256 		/*
257 		 * Most common case the function name is stored in DW_AT_name
258 		 * attribute.
259 		 */
260 		if (dwarf_attrval_string(die, DW_AT_name, &funcname, &de) ==
261 		    DW_DLV_OK)
262 			goto add_func;
263 
264 		/*
265 		 * For inlined function, the actual name is probably in the DIE
266 		 * referenced by DW_AT_abstract_origin. (if present)
267 		 */
268 		if (dwarf_attr(die, DW_AT_abstract_origin, &abst_at, &de) ==
269 		    DW_DLV_OK &&
270 		    dwarf_global_formref(abst_at, &ref, &de) == DW_DLV_OK &&
271 		    dwarf_offdie(dbg, ref, &abst_die, &de) == DW_DLV_OK &&
272 		    dwarf_attrval_string(abst_die, DW_AT_name, &funcname,
273 		    &de) == DW_DLV_OK)
274 			goto add_func;
275 
276 		/*
277 		 * If DW_AT_name is not present, but DW_AT_specification is
278 		 * present, then probably the actual name is in the DIE
279 		 * referenced by DW_AT_specification.
280 		 */
281 		if (dwarf_attr(die, DW_AT_specification, &spec_at, &de) ==
282 		    DW_DLV_OK &&
283 		    dwarf_global_formref(spec_at, &ref, &de) == DW_DLV_OK &&
284 		    dwarf_offdie(dbg, ref, &spec_die, &de) == DW_DLV_OK &&
285 		    dwarf_attrval_string(spec_die, DW_AT_name, &funcname,
286 		    &de) == DW_DLV_OK)
287 			goto add_func;
288 
289 		/* Skip if no name associated with this DIE. */
290 		goto cont_search;
291 
292 	add_func:
293 		if ((f = calloc(1, sizeof(*f))) == NULL)
294 			err(EXIT_FAILURE, "calloc");
295 		if ((f->name = strdup(funcname)) == NULL)
296 			err(EXIT_FAILURE, "strdup");
297 		if (found_ranges) {
298 			f->ranges = ranges;
299 			f->ranges_cnt = ranges_cnt;
300 		} else {
301 			f->lopc = lopc;
302 			f->hipc = hipc;
303 		}
304 		if (tag == DW_TAG_inlined_subroutine) {
305 			f->inlined_caller = parent;
306 			dwarf_attrval_unsigned(die, DW_AT_call_file,
307 			    &f->call_file, &de);
308 			dwarf_attrval_unsigned(die, DW_AT_call_line,
309 			    &f->call_line, &de);
310 		}
311 		STAILQ_INSERT_TAIL(&cu->funclist, f, next);
312 	}
313 
314 cont_search:
315 
316 	/* Search children. */
317 	ret = dwarf_child(die, &ret_die, &de);
318 	if (ret == DW_DLV_ERROR)
319 		warnx("dwarf_child: %s", dwarf_errmsg(de));
320 	else if (ret == DW_DLV_OK) {
321 		if (f != NULL)
322 			collect_func(dbg, ret_die, f, cu);
323 		else
324 			collect_func(dbg, ret_die, parent, cu);
325 	}
326 
327 	/* Search sibling. */
328 	ret = dwarf_siblingof(dbg, die, &ret_die, &de);
329 	if (ret == DW_DLV_ERROR)
330 		warnx("dwarf_siblingof: %s", dwarf_errmsg(de));
331 	else if (ret == DW_DLV_OK)
332 		collect_func(dbg, ret_die, parent, cu);
333 
334 	/* Cleanup */
335 	dwarf_dealloc(dbg, die, DW_DLA_DIE);
336 
337 	if (abst_die != NULL)
338 		dwarf_dealloc(dbg, abst_die, DW_DLA_DIE);
339 
340 	if (spec_die != NULL)
341 		dwarf_dealloc(dbg, spec_die, DW_DLA_DIE);
342 }
343 
344 static void
345 print_inlines(struct CU *cu, struct Func *f, Dwarf_Unsigned call_file,
346     Dwarf_Unsigned call_line)
347 {
348 	char demangled[1024];
349 	char *file;
350 
351 	if (call_file > 0 && (Dwarf_Signed) call_file <= cu->nsrcfiles)
352 		file = cu->srcfiles[call_file - 1];
353 	else
354 		file = unknown;
355 
356 	if (pretty_print)
357 		printf(" (inlined by) ");
358 
359 	if (func) {
360 		if (demangle && !elftc_demangle(f->name, demangled,
361 		    sizeof(demangled), 0)) {
362 			if (pretty_print)
363 				printf("%s at ", demangled);
364 			else
365 				printf("%s\n", demangled);
366 		} else {
367 			if (pretty_print)
368 				printf("%s at ", f->name);
369 			else
370 				printf("%s\n", f->name);
371 		}
372 	}
373 	(void) printf("%s:%ju\n", base ? basename(file) : file,
374 	    (uintmax_t) call_line);
375 
376 	if (f->inlined_caller != NULL)
377 		print_inlines(cu, f->inlined_caller, f->call_file,
378 		    f->call_line);
379 }
380 
381 static void
382 translate(Dwarf_Debug dbg, Elf *e, const char* addrstr)
383 {
384 	Dwarf_Die die, ret_die;
385 	Dwarf_Line *lbuf;
386 	Dwarf_Error de;
387 	Dwarf_Half tag;
388 	Dwarf_Unsigned lopc, hipc, addr, lineno, plineno;
389 	Dwarf_Signed lcount;
390 	Dwarf_Addr lineaddr, plineaddr;
391 	Dwarf_Off off;
392 	struct CU *cu;
393 	struct Func *f;
394 	const char *funcname;
395 	char *file, *file0, *pfile;
396 	char demangled[1024];
397 	int ec, i, ret;
398 
399 	addr = strtoull(addrstr, NULL, 16);
400 	addr += section_base;
401 	lineno = 0;
402 	file = unknown;
403 	cu = NULL;
404 	die = NULL;
405 
406 	while ((ret = dwarf_next_cu_header(dbg, NULL, NULL, NULL, NULL, NULL,
407 	    &de)) ==  DW_DLV_OK) {
408 		die = NULL;
409 		while (dwarf_siblingof(dbg, die, &ret_die, &de) == DW_DLV_OK) {
410 			if (die != NULL)
411 				dwarf_dealloc(dbg, die, DW_DLA_DIE);
412 			die = ret_die;
413 			if (dwarf_tag(die, &tag, &de) != DW_DLV_OK) {
414 				warnx("dwarf_tag failed: %s",
415 				    dwarf_errmsg(de));
416 				goto next_cu;
417 			}
418 
419 			/* XXX: What about DW_TAG_partial_unit? */
420 			if (tag == DW_TAG_compile_unit)
421 				break;
422 		}
423 		if (ret_die == NULL) {
424 			warnx("could not find DW_TAG_compile_unit die");
425 			goto next_cu;
426 		}
427 		if (dwarf_attrval_unsigned(die, DW_AT_low_pc, &lopc, &de) ==
428 		    DW_DLV_OK) {
429 			if (dwarf_attrval_unsigned(die, DW_AT_high_pc, &hipc,
430 			   &de) == DW_DLV_OK) {
431 				/*
432 				 * Check if the address falls into the PC
433 				 * range of this CU.
434 				 */
435 				if (handle_high_pc(die, lopc, &hipc) !=
436 				    DW_DLV_OK)
437 					goto out;
438 			} else {
439 				/* Assume ~0ULL if DW_AT_high_pc not present */
440 				hipc = ~0ULL;
441 			}
442 
443 			/*
444 			 * Record the CU in the hash table for faster lookup
445 			 * later.
446 			 */
447 			if (dwarf_dieoffset(die, &off, &de) != DW_DLV_OK) {
448 				warnx("dwarf_dieoffset failed: %s",
449 				    dwarf_errmsg(de));
450 				goto out;
451 			}
452 			HASH_FIND(hh, culist, &off, sizeof(off), cu);
453 			if (cu == NULL) {
454 				if ((cu = calloc(1, sizeof(*cu))) == NULL)
455 					err(EXIT_FAILURE, "calloc");
456 				cu->off = off;
457 				cu->lopc = lopc;
458 				cu->hipc = hipc;
459 				STAILQ_INIT(&cu->funclist);
460 				HASH_ADD(hh, culist, off, sizeof(off), cu);
461 			}
462 
463 			if (addr >= lopc && addr < hipc)
464 				break;
465 		}
466 
467 	next_cu:
468 		if (die != NULL) {
469 			dwarf_dealloc(dbg, die, DW_DLA_DIE);
470 			die = NULL;
471 		}
472 	}
473 
474 	if (ret != DW_DLV_OK || die == NULL)
475 		goto out;
476 
477 	switch (dwarf_srclines(die, &lbuf, &lcount, &de)) {
478 	case DW_DLV_OK:
479 		break;
480 	case DW_DLV_NO_ENTRY:
481 		/* If a CU lacks debug info, just skip it. */
482 		goto out;
483 	default:
484 		warnx("dwarf_srclines: %s", dwarf_errmsg(de));
485 		goto out;
486 	}
487 
488 	plineaddr = ~0ULL;
489 	plineno = 0;
490 	pfile = unknown;
491 	for (i = 0; i < lcount; i++) {
492 		if (dwarf_lineaddr(lbuf[i], &lineaddr, &de)) {
493 			warnx("dwarf_lineaddr: %s", dwarf_errmsg(de));
494 			goto out;
495 		}
496 		if (dwarf_lineno(lbuf[i], &lineno, &de)) {
497 			warnx("dwarf_lineno: %s", dwarf_errmsg(de));
498 			goto out;
499 		}
500 		if (dwarf_linesrc(lbuf[i], &file0, &de)) {
501 			warnx("dwarf_linesrc: %s", dwarf_errmsg(de));
502 		} else
503 			file = file0;
504 		if (addr == lineaddr)
505 			goto out;
506 		else if (addr < lineaddr && addr > plineaddr) {
507 			lineno = plineno;
508 			file = pfile;
509 			goto out;
510 		}
511 		plineaddr = lineaddr;
512 		plineno = lineno;
513 		pfile = file;
514 	}
515 
516 out:
517 	f = NULL;
518 	funcname = NULL;
519 	if (ret == DW_DLV_OK && (func || inlines) && cu != NULL) {
520 		if (cu->srcfiles == NULL)
521 			if (dwarf_srcfiles(die, &cu->srcfiles, &cu->nsrcfiles,
522 			    &de))
523 				warnx("dwarf_srcfiles: %s", dwarf_errmsg(de));
524 		if (STAILQ_EMPTY(&cu->funclist)) {
525 			collect_func(dbg, die, NULL, cu);
526 			die = NULL;
527 		}
528 		f = search_func(cu, addr);
529 		if (f != NULL)
530 			funcname = f->name;
531 	}
532 
533 	if (print_addr) {
534 		if ((ec = gelf_getclass(e)) == ELFCLASSNONE) {
535 			warnx("gelf_getclass failed: %s", elf_errmsg(-1));
536 			ec = ELFCLASS64;
537 		}
538 		if (ec == ELFCLASS32) {
539 			if (pretty_print)
540 				printf("0x%08jx: ", (uintmax_t) addr);
541 			else
542 				printf("0x%08jx\n", (uintmax_t) addr);
543 		} else {
544 			if (pretty_print)
545 				printf("0x%016jx: ", (uintmax_t) addr);
546 			else
547 				printf("0x%016jx\n", (uintmax_t) addr);
548 		}
549 	}
550 
551 	if (func) {
552 		if (funcname == NULL)
553 			funcname = unknown;
554 		if (demangle && !elftc_demangle(funcname, demangled,
555 		    sizeof(demangled), 0)) {
556 			if (pretty_print)
557 				printf("%s at ", demangled);
558 			else
559 				printf("%s\n", demangled);
560 		} else {
561 			if (pretty_print)
562 				printf("%s at ", funcname);
563 			else
564 				printf("%s\n", funcname);
565 		}
566 	}
567 
568 	(void) printf("%s:%ju\n", base ? basename(file) : file,
569 	    (uintmax_t) lineno);
570 
571 	if (ret == DW_DLV_OK && inlines && cu != NULL &&
572 	    cu->srcfiles != NULL && f != NULL && f->inlined_caller != NULL)
573 		print_inlines(cu, f->inlined_caller, f->call_file,
574 		    f->call_line);
575 
576 	if (die != NULL)
577 		dwarf_dealloc(dbg, die, DW_DLA_DIE);
578 
579 	/*
580 	 * Reset internal CU pointer, so we will start from the first CU
581 	 * next round.
582 	 */
583 	while (ret != DW_DLV_NO_ENTRY) {
584 		if (ret == DW_DLV_ERROR)
585 			errx(EXIT_FAILURE, "dwarf_next_cu_header: %s",
586 			    dwarf_errmsg(de));
587 		ret = dwarf_next_cu_header(dbg, NULL, NULL, NULL, NULL, NULL,
588 		    &de);
589 	}
590 }
591 
592 static void
593 find_section_base(const char *exe, Elf *e, const char *section)
594 {
595 	Dwarf_Addr off;
596 	Elf_Scn *scn;
597 	GElf_Ehdr eh;
598 	GElf_Shdr sh;
599 	size_t shstrndx;
600 	int elferr;
601 	const char *name;
602 
603 	if (gelf_getehdr(e, &eh) != &eh) {
604 		warnx("gelf_getehdr failed: %s", elf_errmsg(-1));
605 		return;
606 	}
607 
608 	if (!elf_getshstrndx(e, &shstrndx)) {
609 		warnx("elf_getshstrndx failed: %s", elf_errmsg(-1));
610 		return;
611 	}
612 
613 	(void) elf_errno();
614 	off = 0;
615 	scn = NULL;
616 	while ((scn = elf_nextscn(e, scn)) != NULL) {
617 		if (gelf_getshdr(scn, &sh) == NULL) {
618 			warnx("gelf_getshdr failed: %s", elf_errmsg(-1));
619 			continue;
620 		}
621 		if ((name = elf_strptr(e, shstrndx, sh.sh_name)) == NULL)
622 			goto next;
623 		if (!strcmp(section, name)) {
624 			if (eh.e_type == ET_EXEC || eh.e_type == ET_DYN) {
625 				/*
626 				 * For executables, section base is the virtual
627 				 * address of the specified section.
628 				 */
629 				section_base = sh.sh_addr;
630 			} else if (eh.e_type == ET_REL) {
631 				/*
632 				 * For relocatables, section base is the
633 				 * relative offset of the specified section
634 				 * to the start of the first section.
635 				 */
636 				section_base = off;
637 			} else
638 				warnx("unknown e_type %u", eh.e_type);
639 			return;
640 		}
641 	next:
642 		off += sh.sh_size;
643 	}
644 	elferr = elf_errno();
645 	if (elferr != 0)
646 		warnx("elf_nextscn failed: %s", elf_errmsg(elferr));
647 
648 	errx(EXIT_FAILURE, "%s: cannot find section %s", exe, section);
649 }
650 
651 int
652 main(int argc, char **argv)
653 {
654 	cap_rights_t rights;
655 	Elf *e;
656 	Dwarf_Debug dbg;
657 	Dwarf_Error de;
658 	const char *exe, *section;
659 	char line[1024];
660 	int fd, i, opt;
661 
662 	exe = NULL;
663 	section = NULL;
664 	while ((opt = getopt_long(argc, argv, "ab:Ce:fij:psHV", longopts,
665 	    NULL)) != -1) {
666 		switch (opt) {
667 		case 'a':
668 			print_addr = 1;
669 			break;
670 		case 'b':
671 			/* ignored */
672 			break;
673 		case 'C':
674 			demangle = 1;
675 			break;
676 		case 'e':
677 			exe = optarg;
678 			break;
679 		case 'f':
680 			func = 1;
681 			break;
682 		case 'i':
683 			inlines = 1;
684 			break;
685 		case 'j':
686 			section = optarg;
687 			break;
688 		case 'p':
689 			pretty_print = 1;
690 			break;
691 		case 's':
692 			base = 1;
693 			break;
694 		case 'H':
695 			usage();
696 		case 'V':
697 			version();
698 		default:
699 			usage();
700 		}
701 	}
702 
703 	argv += optind;
704 	argc -= optind;
705 
706 	if (exe == NULL)
707 		exe = "a.out";
708 
709 	if ((fd = open(exe, O_RDONLY)) < 0)
710 		err(EXIT_FAILURE, "%s", exe);
711 
712 	if (caph_rights_limit(fd, cap_rights_init(&rights, CAP_FSTAT,
713 	    CAP_MMAP_R)) < 0)
714 		errx(EXIT_FAILURE, "caph_rights_limit");
715 
716 	caph_cache_catpages();
717 	if (caph_limit_stdio() < 0)
718 		errx(EXIT_FAILURE, "failed to limit stdio rights");
719 	if (caph_enter() < 0)
720 		errx(EXIT_FAILURE, "failed to enter capability mode");
721 
722 	if (dwarf_init(fd, DW_DLC_READ, NULL, NULL, &dbg, &de))
723 		errx(EXIT_FAILURE, "dwarf_init: %s", dwarf_errmsg(de));
724 
725 	if (dwarf_get_elf(dbg, &e, &de) != DW_DLV_OK)
726 		errx(EXIT_FAILURE, "dwarf_get_elf: %s", dwarf_errmsg(de));
727 
728 	if (section)
729 		find_section_base(exe, e, section);
730 	else
731 		section_base = 0;
732 
733 	if (argc > 0)
734 		for (i = 0; i < argc; i++)
735 			translate(dbg, e, argv[i]);
736 	else {
737 		setvbuf(stdout, NULL, _IOLBF, 0);
738 		while (fgets(line, sizeof(line), stdin) != NULL)
739 			translate(dbg, e, line);
740 	}
741 
742 	dwarf_finish(dbg, &de);
743 
744 	(void) elf_end(e);
745 
746 	exit(0);
747 }
748