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 #include <sys/tree.h>
29 
30 #include <capsicum_helpers.h>
31 #include <dwarf.h>
32 #include <err.h>
33 #include <fcntl.h>
34 #include <gelf.h>
35 #include <getopt.h>
36 #include <libdwarf.h>
37 #include <libelftc.h>
38 #include <libgen.h>
39 #include <stdbool.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 
44 #include "_elftc.h"
45 
46 ELFTC_VCSID("$Id: addr2line.c 3499 2016-11-25 16:06:29Z emaste $");
47 
48 struct Func {
49 	char *name;
50 	Dwarf_Unsigned lopc;
51 	Dwarf_Unsigned hipc;
52 	Dwarf_Unsigned call_file;
53 	Dwarf_Unsigned call_line;
54 	Dwarf_Ranges *ranges;
55 	Dwarf_Signed ranges_cnt;
56 	struct Func *inlined_caller;
57 	STAILQ_ENTRY(Func) next;
58 };
59 
60 struct CU {
61 	RB_ENTRY(CU) entry;
62 	Dwarf_Off off;
63 	Dwarf_Unsigned lopc;
64 	Dwarf_Unsigned hipc;
65 	char **srcfiles;
66 	Dwarf_Signed nsrcfiles;
67 	STAILQ_HEAD(, Func) funclist;
68 	Dwarf_Die die;
69 	Dwarf_Debug dbg;
70 };
71 
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'},
84 	{NULL, 0, NULL, 0}
85 };
86 
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);
93 
94 static int
95 lopccmp(struct CU *e1, struct CU *e2)
96 {
97 	return (e1->lopc < e2->lopc ? -1 : e1->lopc > e2->lopc);
98 }
99 
100 RB_PROTOTYPE(cutree, CU, entry, lopccmp);
101 RB_GENERATE(cutree, CU, entry, lopccmp)
102 
103 #define	USAGE_MESSAGE	"\
104 Usage: %s [options] hexaddress...\n\
105   Map program addresses to source file names and line numbers.\n\n\
106   Options:\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"
119 
120 static void
121 usage(void)
122 {
123 	(void) fprintf(stderr, USAGE_MESSAGE, ELFTC_GETPROGNAME());
124 	exit(1);
125 }
126 
127 static void
128 version(void)
129 {
130 
131 	fprintf(stderr, "%s (%s)\n", ELFTC_GETPROGNAME(), elftc_version());
132 	exit(0);
133 }
134 
135 /*
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.
139  *
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."
146  *
147  * DWARF4 spec, section 2.17.2.
148  */
149 static int
150 handle_high_pc(Dwarf_Die die, Dwarf_Unsigned lopc, Dwarf_Unsigned *hipc)
151 {
152 	Dwarf_Error de;
153 	Dwarf_Half form;
154 	Dwarf_Attribute at;
155 	int ret;
156 
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));
160 		return (ret);
161 	}
162 	ret = dwarf_whatform(at, &form, &de);
163 	if (ret == DW_DLV_ERROR) {
164 		warnx("dwarf_whatform failed: %s", dwarf_errmsg(de));
165 		return (ret);
166 	}
167 	if (dwarf_get_form_class(2, 0, 0, form) == DW_FORM_CLASS_CONSTANT)
168 		*hipc += lopc;
169 
170 	return (DW_DLV_OK);
171 }
172 
173 static struct Func *
174 search_func(struct CU *cu, Dwarf_Unsigned addr)
175 {
176 	struct Func *f, *f0;
177 	Dwarf_Unsigned lopc, hipc, addr_base;
178 	int i;
179 
180 	f0 = NULL;
181 
182 	STAILQ_FOREACH(f, &cu->funclist, next) {
183 		if (f->ranges != NULL) {
184 			addr_base = 0;
185 			for (i = 0; i < f->ranges_cnt; i++) {
186 				if (f->ranges[i].dwr_type == DW_RANGES_END)
187 					break;
188 				if (f->ranges[i].dwr_type ==
189 				    DW_RANGES_ADDRESS_SELECTION) {
190 					addr_base = f->ranges[i].dwr_addr2;
191 					continue;
192 				}
193 
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) {
198 					if (f0 == NULL ||
199 					    (lopc >= f0->lopc &&
200 					    hipc <= f0->hipc)) {
201 						f0 = f;
202 						f0->lopc = lopc;
203 						f0->hipc = hipc;
204 						break;
205 					}
206 				}
207 			}
208 		} else if (addr >= f->lopc && addr < f->hipc) {
209 			if (f0 == NULL ||
210 			    (f->lopc >= f0->lopc && f->hipc <= f0->hipc))
211 				f0 = f;
212 		}
213 	}
214 
215 	return (f0);
216 }
217 
218 static void
219 collect_func(Dwarf_Debug dbg, Dwarf_Die die, struct Func *parent, struct CU *cu)
220 {
221 	Dwarf_Die ret_die, abst_die, spec_die;
222 	Dwarf_Error de;
223 	Dwarf_Half tag;
224 	Dwarf_Unsigned lopc, hipc, ranges_off;
225 	Dwarf_Signed ranges_cnt;
226 	Dwarf_Off ref;
227 	Dwarf_Attribute abst_at, spec_at;
228 	Dwarf_Ranges *ranges;
229 	const char *funcname;
230 	struct Func *f;
231 	int found_ranges, ret;
232 
233 	f = NULL;
234 	abst_die = spec_die = NULL;
235 
236 	if (dwarf_tag(die, &tag, &de)) {
237 		warnx("dwarf_tag: %s", dwarf_errmsg(de));
238 		goto cont_search;
239 	}
240 	if (tag == DW_TAG_subprogram || tag == DW_TAG_entry_point ||
241 	    tag == DW_TAG_inlined_subroutine) {
242 		/*
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.
246 		 */
247 		ranges = NULL;
248 		ranges_cnt = 0;
249 		found_ranges = 0;
250 		if (dwarf_attrval_unsigned(die, DW_AT_ranges, &ranges_off,
251 		    &de) == DW_DLV_OK &&
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) {
255 				found_ranges = 1;
256 				goto get_func_name;
257 			}
258 		}
259 
260 		/*
261 		 * Search for DW_AT_low_pc/DW_AT_high_pc if ranges pointer
262 		 * not found.
263 		 */
264 		if (dwarf_attrval_unsigned(die, DW_AT_low_pc, &lopc, &de) ||
265 		    dwarf_attrval_unsigned(die, DW_AT_high_pc, &hipc, &de))
266 			goto cont_search;
267 		if (handle_high_pc(die, lopc, &hipc) != DW_DLV_OK)
268 			goto cont_search;
269 
270 	get_func_name:
271 		/*
272 		 * Most common case the function name is stored in DW_AT_name
273 		 * attribute.
274 		 */
275 		if (dwarf_attrval_string(die, DW_AT_name, &funcname, &de) ==
276 		    DW_DLV_OK)
277 			goto add_func;
278 
279 		/*
280 		 * For inlined function, the actual name is probably in the DIE
281 		 * referenced by DW_AT_abstract_origin. (if present)
282 		 */
283 		if (dwarf_attr(die, DW_AT_abstract_origin, &abst_at, &de) ==
284 		    DW_DLV_OK &&
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,
288 		    &de) == DW_DLV_OK)
289 			goto add_func;
290 
291 		/*
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.
295 		 */
296 		if (dwarf_attr(die, DW_AT_specification, &spec_at, &de) ==
297 		    DW_DLV_OK &&
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,
301 		    &de) == DW_DLV_OK)
302 			goto add_func;
303 
304 		/* Skip if no name associated with this DIE. */
305 		goto cont_search;
306 
307 	add_func:
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");
312 		if (found_ranges) {
313 			f->ranges = ranges;
314 			f->ranges_cnt = ranges_cnt;
315 		} else {
316 			f->lopc = lopc;
317 			f->hipc = hipc;
318 		}
319 		if (tag == DW_TAG_inlined_subroutine) {
320 			f->inlined_caller = parent;
321 			dwarf_attrval_unsigned(die, DW_AT_call_file,
322 			    &f->call_file, &de);
323 			dwarf_attrval_unsigned(die, DW_AT_call_line,
324 			    &f->call_line, &de);
325 		}
326 		STAILQ_INSERT_TAIL(&cu->funclist, f, next);
327 	}
328 
329 cont_search:
330 
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) {
336 		if (f != NULL)
337 			collect_func(dbg, ret_die, f, cu);
338 		else
339 			collect_func(dbg, ret_die, parent, cu);
340 	}
341 
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);
348 
349 	/* Cleanup */
350 	if (die != cu->die)
351 		dwarf_dealloc(dbg, die, DW_DLA_DIE);
352 
353 	if (abst_die != NULL)
354 		dwarf_dealloc(dbg, abst_die, DW_DLA_DIE);
355 
356 	if (spec_die != NULL)
357 		dwarf_dealloc(dbg, spec_die, DW_DLA_DIE);
358 }
359 
360 static void
361 print_inlines(struct CU *cu, struct Func *f, Dwarf_Unsigned call_file,
362     Dwarf_Unsigned call_line)
363 {
364 	char demangled[1024];
365 	char *file;
366 
367 	if (call_file > 0 && (Dwarf_Signed) call_file <= cu->nsrcfiles)
368 		file = cu->srcfiles[call_file - 1];
369 	else
370 		file = unknown;
371 
372 	if (pretty_print)
373 		printf(" (inlined by) ");
374 
375 	if (func) {
376 		if (demangle && !elftc_demangle(f->name, demangled,
377 		    sizeof(demangled), 0)) {
378 			if (pretty_print)
379 				printf("%s at ", demangled);
380 			else
381 				printf("%s\n", demangled);
382 		} else {
383 			if (pretty_print)
384 				printf("%s at ", f->name);
385 			else
386 				printf("%s\n", f->name);
387 		}
388 	}
389 	(void) printf("%s:%ju\n", base ? basename(file) : file,
390 	    (uintmax_t) call_line);
391 
392 	if (f->inlined_caller != NULL)
393 		print_inlines(cu, f->inlined_caller, f->call_file,
394 		    f->call_line);
395 }
396 
397 static struct CU *
398 culookup(Dwarf_Unsigned addr)
399 {
400 	struct CU find, *res;
401 
402 	find.lopc = addr;
403 	res = RB_NFIND(cutree, &cuhead, &find);
404 	if (res != NULL) {
405 		if (res->lopc != addr)
406 			res = RB_PREV(cutree, &cuhead, res);
407 		if (res != NULL && addr >= res->lopc && addr < res->hipc)
408 			return (res);
409 	} else {
410 		res = RB_MAX(cutree, &cuhead);
411 		if (res != NULL && addr >= res->lopc && addr < res->hipc)
412 			return (res);
413 	}
414 	return (NULL);
415 }
416 
417 /*
418  * Check whether addr falls into range(s) of current CU, and save current CU
419  * to lookup tree if so.
420  */
421 static int
422 check_range(Dwarf_Debug dbg, Dwarf_Die die, Dwarf_Unsigned addr,
423     struct CU **cu)
424 {
425 	Dwarf_Error de;
426 	Dwarf_Unsigned addr_base, lopc, hipc;
427 	Dwarf_Off ranges_off;
428 	Dwarf_Signed ranges_cnt;
429 	Dwarf_Ranges *ranges;
430 	int i, ret;
431 	bool in_range;
432 
433 	addr_base = 0;
434 	ranges = NULL;
435 	ranges_cnt = 0;
436 	in_range = false;
437 
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) ==
441 		    DW_DLV_OK) {
442 			if (lopc == curlopc)
443 				return (DW_DLV_ERROR);
444 			if (dwarf_attrval_unsigned(die, DW_AT_high_pc, &hipc,
445 				&de) == DW_DLV_OK) {
446 				/*
447 				 * Check if the address falls into the PC
448 				 * range of this CU.
449 				 */
450 				if (handle_high_pc(die, lopc, &hipc) !=
451 					DW_DLV_OK)
452 					return (DW_DLV_ERROR);
453 			} else {
454 				/* Assume ~0ULL if DW_AT_high_pc not present */
455 				hipc = ~0ULL;
456 			}
457 
458 			if (addr >= lopc && addr < hipc) {
459 				in_range = true;
460 			}
461 		}
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)
466 			return (ret);
467 
468 		if (!ranges || ranges_cnt <= 0)
469 			return (DW_DLV_ERROR);
470 
471 		for (i = 0; i < ranges_cnt; i++) {
472 			if (ranges[i].dwr_type == DW_RANGES_END)
473 				return (DW_DLV_NO_ENTRY);
474 
475 			if (ranges[i].dwr_type ==
476 				DW_RANGES_ADDRESS_SELECTION) {
477 				addr_base = ranges[i].dwr_addr2;
478 				continue;
479 			}
480 
481 			/* DW_RANGES_ENTRY */
482 			lopc = ranges[i].dwr_addr1 + addr_base;
483 			hipc = ranges[i].dwr_addr2 + addr_base;
484 
485 			if (lopc == curlopc)
486 				return (DW_DLV_ERROR);
487 
488 			if (addr >= lopc && addr < hipc){
489 				in_range = true;
490 				break;
491 			}
492 		}
493 	} else {
494 		return (DW_DLV_ERROR);
495 	}
496 
497 	if (in_range) {
498 		if ((*cu = calloc(1, sizeof(struct CU))) == NULL)
499 			err(EXIT_FAILURE, "calloc");
500 		(*cu)->lopc = lopc;
501 		(*cu)->hipc = hipc;
502 		(*cu)->die = die;
503 		(*cu)->dbg = dbg;
504 		STAILQ_INIT(&(*cu)->funclist);
505 		RB_INSERT(cutree, &cuhead, *cu);
506 		curlopc = lopc;
507 		return (DW_DLV_OK);
508 	} else {
509 		return (DW_DLV_NO_ENTRY);
510 	}
511 }
512 
513 static void
514 translate(Dwarf_Debug dbg, Elf *e, const char* addrstr)
515 {
516 	Dwarf_Die die, ret_die;
517 	Dwarf_Line *lbuf;
518 	Dwarf_Error de;
519 	Dwarf_Half tag;
520 	Dwarf_Unsigned addr, lineno, plineno;
521 	Dwarf_Signed lcount;
522 	Dwarf_Addr lineaddr, plineaddr;
523 	struct CU *cu;
524 	struct Func *f;
525 	const char *funcname;
526 	char *file, *file0, *pfile;
527 	char demangled[1024];
528 	int ec, i, ret;
529 
530 	addr = strtoull(addrstr, NULL, 16);
531 	addr += section_base;
532 	lineno = 0;
533 	file = unknown;
534 	die = NULL;
535 	ret = DW_DLV_OK;
536 
537 	cu = culookup(addr);
538 	if (cu != NULL) {
539 		die = cu->die;
540 		dbg = cu->dbg;
541 		goto status_ok;
542 	}
543 
544 	while (true) {
545 		/*
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.
550 		 */
551 		ret = dwarf_next_cu_header(dbg, NULL, NULL, NULL, NULL, NULL,
552 		    &de);
553 		if (ret == DW_DLV_NO_ENTRY) {
554 			if (curlopc == ~0ULL)
555 				goto out;
556 			ret = dwarf_next_cu_header(dbg, NULL, NULL, NULL, NULL,
557 			    NULL, &de);
558 		}
559 		die = NULL;
560 		while (dwarf_siblingof(dbg, die, &ret_die, &de) == DW_DLV_OK) {
561 			if (die != NULL)
562 				dwarf_dealloc(dbg, die, DW_DLA_DIE);
563 			die = ret_die;
564 			if (dwarf_tag(die, &tag, &de) != DW_DLV_OK) {
565 				warnx("dwarf_tag failed: %s",
566 				    dwarf_errmsg(de));
567 				goto next_cu;
568 			}
569 
570 			/* XXX: What about DW_TAG_partial_unit? */
571 			if (tag == DW_TAG_compile_unit)
572 				break;
573 		}
574 
575 		if (ret_die == NULL) {
576 			warnx("could not find DW_TAG_compile_unit die");
577 			goto next_cu;
578 		}
579 		ret = check_range(dbg, die, addr, &cu);
580 		if (ret == DW_DLV_OK)
581 			break;
582 		if (ret == DW_DLV_ERROR)
583 			goto out;
584 next_cu:
585 		if (die != NULL) {
586 			dwarf_dealloc(dbg, die, DW_DLA_DIE);
587 			die = NULL;
588 		}
589 	}
590 
591 	if (ret != DW_DLV_OK || die == NULL)
592 		goto out;
593 
594 status_ok:
595 	switch (dwarf_srclines(die, &lbuf, &lcount, &de)) {
596 	case DW_DLV_OK:
597 		break;
598 	case DW_DLV_NO_ENTRY:
599 		/* If a CU lacks debug info, just skip it. */
600 		goto out;
601 	default:
602 		warnx("dwarf_srclines: %s", dwarf_errmsg(de));
603 		goto out;
604 	}
605 
606 	plineaddr = ~0ULL;
607 	plineno = 0;
608 	pfile = unknown;
609 	for (i = 0; i < lcount; i++) {
610 		if (dwarf_lineaddr(lbuf[i], &lineaddr, &de)) {
611 			warnx("dwarf_lineaddr: %s", dwarf_errmsg(de));
612 			goto out;
613 		}
614 		if (dwarf_lineno(lbuf[i], &lineno, &de)) {
615 			warnx("dwarf_lineno: %s", dwarf_errmsg(de));
616 			goto out;
617 		}
618 		if (dwarf_linesrc(lbuf[i], &file0, &de)) {
619 			warnx("dwarf_linesrc: %s", dwarf_errmsg(de));
620 		} else
621 			file = file0;
622 		if (addr == lineaddr)
623 			goto out;
624 		else if (addr < lineaddr && addr > plineaddr) {
625 			lineno = plineno;
626 			file = pfile;
627 			goto out;
628 		}
629 		plineaddr = lineaddr;
630 		plineno = lineno;
631 		pfile = file;
632 	}
633 
634 out:
635 	f = NULL;
636 	funcname = NULL;
637 	if (ret == DW_DLV_OK && (func || inlines) && cu != NULL) {
638 		if (cu->srcfiles == NULL)
639 			if (dwarf_srcfiles(die, &cu->srcfiles, &cu->nsrcfiles,
640 			    &de))
641 				warnx("dwarf_srcfiles: %s", dwarf_errmsg(de));
642 		if (STAILQ_EMPTY(&cu->funclist)) {
643 			collect_func(dbg, die, NULL, cu);
644 			die = NULL;
645 		}
646 		f = search_func(cu, addr);
647 		if (f != NULL)
648 			funcname = f->name;
649 	}
650 
651 	if (print_addr) {
652 		if ((ec = gelf_getclass(e)) == ELFCLASSNONE) {
653 			warnx("gelf_getclass failed: %s", elf_errmsg(-1));
654 			ec = ELFCLASS64;
655 		}
656 		if (ec == ELFCLASS32) {
657 			if (pretty_print)
658 				printf("0x%08jx: ", (uintmax_t) addr);
659 			else
660 				printf("0x%08jx\n", (uintmax_t) addr);
661 		} else {
662 			if (pretty_print)
663 				printf("0x%016jx: ", (uintmax_t) addr);
664 			else
665 				printf("0x%016jx\n", (uintmax_t) addr);
666 		}
667 	}
668 
669 	if (func) {
670 		if (funcname == NULL)
671 			funcname = unknown;
672 		if (demangle && !elftc_demangle(funcname, demangled,
673 		    sizeof(demangled), 0)) {
674 			if (pretty_print)
675 				printf("%s at ", demangled);
676 			else
677 				printf("%s\n", demangled);
678 		} else {
679 			if (pretty_print)
680 				printf("%s at ", funcname);
681 			else
682 				printf("%s\n", funcname);
683 		}
684 	}
685 
686 	(void) printf("%s:%ju\n", base ? basename(file) : file,
687 	    (uintmax_t) lineno);
688 
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,
692 		    f->call_line);
693 }
694 
695 static void
696 find_section_base(const char *exe, Elf *e, const char *section)
697 {
698 	Dwarf_Addr off;
699 	Elf_Scn *scn;
700 	GElf_Ehdr eh;
701 	GElf_Shdr sh;
702 	size_t shstrndx;
703 	int elferr;
704 	const char *name;
705 
706 	if (gelf_getehdr(e, &eh) != &eh) {
707 		warnx("gelf_getehdr failed: %s", elf_errmsg(-1));
708 		return;
709 	}
710 
711 	if (!elf_getshstrndx(e, &shstrndx)) {
712 		warnx("elf_getshstrndx failed: %s", elf_errmsg(-1));
713 		return;
714 	}
715 
716 	(void) elf_errno();
717 	off = 0;
718 	scn = NULL;
719 	while ((scn = elf_nextscn(e, scn)) != NULL) {
720 		if (gelf_getshdr(scn, &sh) == NULL) {
721 			warnx("gelf_getshdr failed: %s", elf_errmsg(-1));
722 			continue;
723 		}
724 		if ((name = elf_strptr(e, shstrndx, sh.sh_name)) == NULL)
725 			goto next;
726 		if (!strcmp(section, name)) {
727 			if (eh.e_type == ET_EXEC || eh.e_type == ET_DYN) {
728 				/*
729 				 * For executables, section base is the virtual
730 				 * address of the specified section.
731 				 */
732 				section_base = sh.sh_addr;
733 			} else if (eh.e_type == ET_REL) {
734 				/*
735 				 * For relocatables, section base is the
736 				 * relative offset of the specified section
737 				 * to the start of the first section.
738 				 */
739 				section_base = off;
740 			} else
741 				warnx("unknown e_type %u", eh.e_type);
742 			return;
743 		}
744 	next:
745 		off += sh.sh_size;
746 	}
747 	elferr = elf_errno();
748 	if (elferr != 0)
749 		warnx("elf_nextscn failed: %s", elf_errmsg(elferr));
750 
751 	errx(EXIT_FAILURE, "%s: cannot find section %s", exe, section);
752 }
753 
754 int
755 main(int argc, char **argv)
756 {
757 	cap_rights_t rights;
758 	Elf *e;
759 	Dwarf_Debug dbg;
760 	Dwarf_Error de;
761 	const char *exe, *section;
762 	char line[1024];
763 	int fd, i, opt;
764 
765 	exe = NULL;
766 	section = NULL;
767 	while ((opt = getopt_long(argc, argv, "ab:Ce:fij:psHV", longopts,
768 	    NULL)) != -1) {
769 		switch (opt) {
770 		case 'a':
771 			print_addr = 1;
772 			break;
773 		case 'b':
774 			/* ignored */
775 			break;
776 		case 'C':
777 			demangle = 1;
778 			break;
779 		case 'e':
780 			exe = optarg;
781 			break;
782 		case 'f':
783 			func = 1;
784 			break;
785 		case 'i':
786 			inlines = 1;
787 			break;
788 		case 'j':
789 			section = optarg;
790 			break;
791 		case 'p':
792 			pretty_print = 1;
793 			break;
794 		case 's':
795 			base = 1;
796 			break;
797 		case 'H':
798 			usage();
799 		case 'V':
800 			version();
801 		default:
802 			usage();
803 		}
804 	}
805 
806 	argv += optind;
807 	argc -= optind;
808 
809 	if (exe == NULL)
810 		exe = "a.out";
811 
812 	if ((fd = open(exe, O_RDONLY)) < 0)
813 		err(EXIT_FAILURE, "%s", exe);
814 
815 	if (caph_rights_limit(fd, cap_rights_init(&rights, CAP_FSTAT,
816 	    CAP_MMAP_R)) < 0)
817 		errx(EXIT_FAILURE, "caph_rights_limit");
818 
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");
824 
825 	if (dwarf_init(fd, DW_DLC_READ, NULL, NULL, &dbg, &de))
826 		errx(EXIT_FAILURE, "dwarf_init: %s", dwarf_errmsg(de));
827 
828 	if (dwarf_get_elf(dbg, &e, &de) != DW_DLV_OK)
829 		errx(EXIT_FAILURE, "dwarf_get_elf: %s", dwarf_errmsg(de));
830 
831 	if (section)
832 		find_section_base(exe, e, section);
833 	else
834 		section_base = 0;
835 
836 	if (argc > 0)
837 		for (i = 0; i < argc; i++)
838 			translate(dbg, e, argv[i]);
839 	else {
840 		setvbuf(stdout, NULL, _IOLBF, 0);
841 		while (fgets(line, sizeof(line), stdin) != NULL)
842 			translate(dbg, e, line);
843 	}
844 
845 	dwarf_finish(dbg, &de);
846 
847 	(void) elf_end(e);
848 
849 	exit(0);
850 }
851