xref: /freebsd/contrib/elftoolchain/addr2line/addr2line.c (revision cd8537910406e68d4719136a5b0cf6d23bb1b23b)
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 range {
61 	RB_ENTRY(range) 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, range) cuhead = RB_INITIALIZER(&cuhead);
93 
94 static int
95 lopccmp(struct range *e1, struct range *e2)
96 {
97 	return (e1->lopc < e2->lopc ? -1 : e1->lopc > e2->lopc);
98 }
99 
100 RB_PROTOTYPE(cutree, range, entry, lopccmp);
101 RB_GENERATE(cutree, range, 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 range *range, 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, &range->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,
220     struct range *range)
221 {
222 	Dwarf_Die ret_die, abst_die, spec_die;
223 	Dwarf_Error de;
224 	Dwarf_Half tag;
225 	Dwarf_Unsigned lopc, hipc, ranges_off;
226 	Dwarf_Signed ranges_cnt;
227 	Dwarf_Off ref;
228 	Dwarf_Attribute abst_at, spec_at;
229 	Dwarf_Ranges *ranges;
230 	const char *funcname;
231 	struct Func *f;
232 	int found_ranges, ret;
233 
234 	f = NULL;
235 	abst_die = spec_die = NULL;
236 
237 	if (dwarf_tag(die, &tag, &de)) {
238 		warnx("dwarf_tag: %s", dwarf_errmsg(de));
239 		goto cont_search;
240 	}
241 	if (tag == DW_TAG_subprogram || tag == DW_TAG_entry_point ||
242 	    tag == DW_TAG_inlined_subroutine || tag == DW_TAG_label) {
243 		/*
244 		 * Function address range can be specified by either
245 		 * a DW_AT_ranges attribute which points to a range list or
246 		 * by a pair of DW_AT_low_pc and DW_AT_high_pc attributes.
247 		 */
248 		ranges = NULL;
249 		ranges_cnt = 0;
250 		found_ranges = 0;
251 		if (dwarf_attrval_unsigned(die, DW_AT_ranges, &ranges_off,
252 		    &de) == DW_DLV_OK &&
253 		    dwarf_get_ranges(dbg, (Dwarf_Off) ranges_off, &ranges,
254 		    &ranges_cnt, NULL, &de) == DW_DLV_OK) {
255 			if (ranges != NULL && ranges_cnt > 0) {
256 				found_ranges = 1;
257 				goto get_func_name;
258 			}
259 		}
260 
261 		/*
262 		 * Ranges pointer not found.  Search for DW_AT_low_pc, and
263 		 * DW_AT_high_pc iff die is not a label.  Labels doesn't have
264 		 * hipc attr. */
265 		if (tag == DW_TAG_label) {
266 			if (dwarf_attrval_unsigned(die, DW_AT_low_pc, &lopc,
267 			    &de) != DW_DLV_OK)
268 				goto cont_search;
269 		} else {
270 			if (dwarf_attrval_unsigned(die, DW_AT_low_pc, &lopc,
271 			    &de) || dwarf_attrval_unsigned(die, DW_AT_high_pc,
272 			    &hipc, &de))
273 				goto cont_search;
274 			if (handle_high_pc(die, lopc, &hipc) != DW_DLV_OK)
275 				goto cont_search;
276 		}
277 
278 	get_func_name:
279 		/*
280 		 * Most common case the function name is stored in DW_AT_name
281 		 * attribute.
282 		 */
283 		if (dwarf_attrval_string(die, DW_AT_name, &funcname, &de) ==
284 		    DW_DLV_OK)
285 			goto add_func;
286 
287 		/*
288 		 * For inlined function, the actual name is probably in the DIE
289 		 * referenced by DW_AT_abstract_origin. (if present)
290 		 */
291 		if (dwarf_attr(die, DW_AT_abstract_origin, &abst_at, &de) ==
292 		    DW_DLV_OK &&
293 		    dwarf_global_formref(abst_at, &ref, &de) == DW_DLV_OK &&
294 		    dwarf_offdie(dbg, ref, &abst_die, &de) == DW_DLV_OK &&
295 		    dwarf_attrval_string(abst_die, DW_AT_name, &funcname,
296 		    &de) == DW_DLV_OK)
297 			goto add_func;
298 
299 		/*
300 		 * If DW_AT_name is not present, but DW_AT_specification is
301 		 * present, then probably the actual name is in the DIE
302 		 * referenced by DW_AT_specification.
303 		 */
304 		if (dwarf_attr(die, DW_AT_specification, &spec_at, &de) ==
305 		    DW_DLV_OK &&
306 		    dwarf_global_formref(spec_at, &ref, &de) == DW_DLV_OK &&
307 		    dwarf_offdie(dbg, ref, &spec_die, &de) == DW_DLV_OK &&
308 		    dwarf_attrval_string(spec_die, DW_AT_name, &funcname,
309 		    &de) == DW_DLV_OK)
310 			goto add_func;
311 
312 		/* Skip if no name associated with this DIE. */
313 		goto cont_search;
314 
315 	add_func:
316 		if ((f = calloc(1, sizeof(*f))) == NULL)
317 			err(EXIT_FAILURE, "calloc");
318 		if ((f->name = strdup(funcname)) == NULL)
319 			err(EXIT_FAILURE, "strdup");
320 		if (found_ranges) {
321 			f->ranges = ranges;
322 			f->ranges_cnt = ranges_cnt;
323 		} else {
324 			f->lopc = lopc;
325 			f->hipc = hipc;
326 		}
327 		if (tag == DW_TAG_inlined_subroutine) {
328 			f->inlined_caller = parent;
329 			dwarf_attrval_unsigned(die, DW_AT_call_file,
330 			    &f->call_file, &de);
331 			dwarf_attrval_unsigned(die, DW_AT_call_line,
332 			    &f->call_line, &de);
333 		}
334 		STAILQ_INSERT_TAIL(&range->funclist, f, next);
335 	}
336 
337 cont_search:
338 
339 	/* Search children. */
340 	ret = dwarf_child(die, &ret_die, &de);
341 	if (ret == DW_DLV_ERROR)
342 		warnx("dwarf_child: %s", dwarf_errmsg(de));
343 	else if (ret == DW_DLV_OK) {
344 		if (f != NULL)
345 			collect_func(dbg, ret_die, f, range);
346 		else
347 			collect_func(dbg, ret_die, parent, range);
348 	}
349 
350 	/* Search sibling. */
351 	ret = dwarf_siblingof(dbg, die, &ret_die, &de);
352 	if (ret == DW_DLV_ERROR)
353 		warnx("dwarf_siblingof: %s", dwarf_errmsg(de));
354 	else if (ret == DW_DLV_OK)
355 		collect_func(dbg, ret_die, parent, range);
356 
357 	/* Cleanup */
358 	if (die != range->die)
359 		dwarf_dealloc(dbg, die, DW_DLA_DIE);
360 
361 	if (abst_die != NULL)
362 		dwarf_dealloc(dbg, abst_die, DW_DLA_DIE);
363 
364 	if (spec_die != NULL)
365 		dwarf_dealloc(dbg, spec_die, DW_DLA_DIE);
366 }
367 
368 static void
369 print_inlines(struct range *range, struct Func *f, Dwarf_Unsigned call_file,
370     Dwarf_Unsigned call_line)
371 {
372 	char demangled[1024];
373 	char *file;
374 
375 	if (call_file > 0 && (Dwarf_Signed) call_file <= range->nsrcfiles)
376 		file = range->srcfiles[call_file - 1];
377 	else
378 		file = unknown;
379 
380 	if (pretty_print)
381 		printf(" (inlined by) ");
382 
383 	if (func) {
384 		if (demangle && !elftc_demangle(f->name, demangled,
385 		    sizeof(demangled), 0)) {
386 			if (pretty_print)
387 				printf("%s at ", demangled);
388 			else
389 				printf("%s\n", demangled);
390 		} else {
391 			if (pretty_print)
392 				printf("%s at ", f->name);
393 			else
394 				printf("%s\n", f->name);
395 		}
396 	}
397 	(void) printf("%s:%ju\n", base ? basename(file) : file,
398 	    (uintmax_t) call_line);
399 
400 	if (f->inlined_caller != NULL)
401 		print_inlines(range, f->inlined_caller, f->call_file,
402 		    f->call_line);
403 }
404 
405 static struct range *
406 culookup(Dwarf_Unsigned addr)
407 {
408 	struct range find, *res;
409 
410 	find.lopc = addr;
411 	res = RB_NFIND(cutree, &cuhead, &find);
412 	if (res != NULL) {
413 		if (res->lopc != addr)
414 			res = RB_PREV(cutree, &cuhead, res);
415 		if (res != NULL && addr >= res->lopc && addr < res->hipc)
416 			return (res);
417 	} else {
418 		res = RB_MAX(cutree, &cuhead);
419 		if (res != NULL && addr >= res->lopc && addr < res->hipc)
420 			return (res);
421 	}
422 	return (NULL);
423 }
424 
425 /*
426  * When DW_AT_ranges, DW_AT_low_pc/DW_AT_high_pc are all absent, we check the
427  * children of cu die for labels.  If the address falls into one of the labels
428  * ranges(aranges), return the label DIE.
429  */
430 static int
431 check_labels(Dwarf_Debug dbg, Dwarf_Die die, Dwarf_Unsigned addr,
432     struct range **range) {
433 	Dwarf_Addr start;
434 	Dwarf_Arange *aranges;
435 	Dwarf_Die prev_die, ret_die;
436 	Dwarf_Error de;
437 	Dwarf_Half tag;
438 	Dwarf_Off die_off;
439 	Dwarf_Unsigned lopc, length;
440 	Dwarf_Signed arcnt;
441 	struct range *labelp, **labels;
442 	int i, j, label_cnt, ret;
443 
444 	prev_die = ret_die = NULL;
445 	labels = NULL;
446 	i = label_cnt = 0;
447 
448 	/* Find aranges. */
449 	ret = dwarf_get_aranges(dbg, &aranges, &arcnt, &de);
450 	if (ret != DW_DLV_OK && ret != DW_DLV_NO_ENTRY)
451 		warnx("dwarf_get_aranges failed: %s", dwarf_errmsg(de));
452 
453 	/* Child of current CU. */
454 	ret = dwarf_child(die, &prev_die, &de);
455 	if (ret == DW_DLV_ERROR)
456 		warnx("dwarf_child: %s", dwarf_errmsg(de));
457 
458 	/* Count labels. */
459 	while (1) {
460 		if (dwarf_tag(prev_die, &tag, &de) != DW_DLV_OK) {
461 			warnx("dwarf_tag failed: %s",
462 				dwarf_errmsg(de));
463 			return DW_DLV_ERROR;
464 		}
465 		if (tag == DW_TAG_label) {
466 			if (dwarf_attrval_unsigned(prev_die, DW_AT_low_pc,
467 			    &lopc, &de) == DW_DLV_OK)
468 				label_cnt++;
469 		}
470 
471 		if (dwarf_siblingof(dbg, prev_die, &ret_die, &de) != DW_DLV_OK)
472 			break;
473 
474 		if (prev_die != NULL)
475 			dwarf_dealloc(dbg, prev_die, DW_DLA_DIE);
476 		prev_die = ret_die;
477 	}
478 
479 	if (label_cnt == 0)
480 		return (DW_DLV_NO_ENTRY);
481 
482 	/* Allocate space for labels. */
483 	if ((labels = calloc(label_cnt, sizeof(struct range *))) == NULL)
484 		err(EXIT_FAILURE, "calloc");
485 
486 	/* Add labels to list. */
487 	ret = dwarf_child(die, &prev_die, &de);
488 	if (ret == DW_DLV_ERROR)
489 		warnx("dwarf_child: %s", dwarf_errmsg(de));
490 	while (1) {
491 		if (dwarf_tag(prev_die, &tag, &de) != DW_DLV_OK) {
492 			warnx("dwarf_tag failed: %s",
493 				dwarf_errmsg(de));
494 			return DW_DLV_ERROR;
495 		}
496 		if (tag == DW_TAG_label) {
497 			if (dwarf_attrval_unsigned(prev_die, DW_AT_low_pc,
498 			    &lopc, &de) == DW_DLV_OK) {
499 				if (curlopc == lopc) {
500 					for (i = 0; i < label_cnt - 1; i++) {
501 						if (labels[i] != *range)
502 							free(labels[i]);
503 					}
504 					free(labels);
505 					return DW_DLV_ERROR;
506 				}
507 				labelp = calloc(1, sizeof(struct range));
508 				if (labelp == NULL)
509 					err(EXIT_FAILURE, "calloc");
510 				labelp->lopc = lopc;
511 				labelp->die = prev_die;
512 				labelp->dbg = dbg;
513 				STAILQ_INIT(&labelp->funclist);
514 				labels[i++] = labelp;
515 			}
516 		}
517 		if (dwarf_siblingof(dbg, prev_die, &ret_die, &de) != DW_DLV_OK)
518 			break;
519 		if (prev_die != NULL && tag != DW_TAG_label)
520 			dwarf_dealloc(dbg, prev_die, DW_DLA_DIE);
521 		prev_die = ret_die;
522 	}
523 
524 	/* Set hipc for each label using aranges */
525 	for (i = 0; i < label_cnt; i++) {
526 		for (j = 0; j < arcnt; j++) {
527 			if (dwarf_get_arange_info(aranges[j], &start, &length,
528 			    &die_off, &de) != DW_DLV_OK) {
529 				warnx("dwarf_get_arange_info failed: %s",
530 					dwarf_errmsg(de));
531 				continue;
532 			}
533 			if (labels[i]->lopc == (Dwarf_Unsigned)start) {
534 				labels[i]->hipc = start + length;
535 				break;
536 			}
537 		}
538 	}
539 
540 	/* If addr in label's range, we have found the range for this label. */
541 	for (i = 0; i < label_cnt; i++) {
542 		if (addr >= labels[i]->lopc && addr < labels[i]->hipc) {
543 			*range = labels[i];
544 			RB_INSERT(cutree, &cuhead, (*range));
545 			curlopc = (*range)->lopc;
546 			break;
547 		}
548 	}
549 
550 	for (i = 0; i < label_cnt - 1; i++) {
551 		if (labels[i] != *range)
552 			free(labels[i]);
553 	}
554 	free(labels);
555 
556 	if (*range != NULL)
557 		return (DW_DLV_OK);
558 	else
559 		return (DW_DLV_NO_ENTRY);
560 }
561 
562 /*
563  * Check whether addr falls into range(s) of current CU.
564  * If so, save current CU to lookup tree.
565  */
566 static int
567 check_range(Dwarf_Debug dbg, Dwarf_Die die, Dwarf_Unsigned addr,
568     struct range **range)
569 {
570 	Dwarf_Error de;
571 	Dwarf_Unsigned addr_base, lopc, hipc;
572 	Dwarf_Off ranges_off;
573 	Dwarf_Signed ranges_cnt;
574 	Dwarf_Ranges *ranges;
575 	int i, ret;
576 	bool in_cu;
577 
578 	addr_base = 0;
579 	ranges = NULL;
580 	ranges_cnt = 0;
581 	in_cu = false;
582 
583 	ret = dwarf_attrval_unsigned(die, DW_AT_ranges, &ranges_off, &de);
584 	if (ret == DW_DLV_OK) {
585 		ret = dwarf_get_ranges(dbg, ranges_off, &ranges,
586 			&ranges_cnt, NULL, &de);
587 		if (ret != DW_DLV_OK)
588 			return (ret);
589 
590 		if (!ranges || ranges_cnt <= 0)
591 			return (DW_DLV_ERROR);
592 
593 		for (i = 0; i < ranges_cnt; i++) {
594 			if (ranges[i].dwr_type == DW_RANGES_END)
595 				return (DW_DLV_NO_ENTRY);
596 
597 			if (ranges[i].dwr_type ==
598 				DW_RANGES_ADDRESS_SELECTION) {
599 				addr_base = ranges[i].dwr_addr2;
600 				continue;
601 			}
602 
603 			/* DW_RANGES_ENTRY */
604 			lopc = ranges[i].dwr_addr1 + addr_base;
605 			hipc = ranges[i].dwr_addr2 + addr_base;
606 
607 			if (lopc == curlopc)
608 				return (DW_DLV_ERROR);
609 
610 			if (addr >= lopc && addr < hipc){
611 				in_cu = true;
612 				break;
613 			}
614 		}
615 	} else {
616 		if (dwarf_attrval_unsigned(die, DW_AT_low_pc, &lopc, &de) ==
617 		    DW_DLV_OK) {
618 			if (lopc == curlopc)
619 				return (DW_DLV_ERROR);
620 			if (dwarf_attrval_unsigned(die, DW_AT_high_pc, &hipc,
621 				&de) == DW_DLV_OK) {
622 				/*
623 				 * Check if the address falls into the PC
624 				 * range of this CU.
625 				 */
626 				if (handle_high_pc(die, lopc, &hipc) !=
627 					DW_DLV_OK)
628 					return (DW_DLV_ERROR);
629 			} else {
630 				/* Assume ~0ULL if DW_AT_high_pc not present. */
631 				hipc = ~0ULL;
632 			}
633 
634 			if (addr >= lopc && addr < hipc) {
635 				in_cu = true;
636 			}
637 		} else {
638 			/* Addr not in range die, try labels. */
639 			ret = check_labels(dbg, die, addr, range);
640 			return ret;
641 		}
642 	}
643 
644 	if (in_cu) {
645 		if ((*range = calloc(1, sizeof(struct range))) == NULL)
646 			err(EXIT_FAILURE, "calloc");
647 		(*range)->lopc = lopc;
648 		(*range)->hipc = hipc;
649 		(*range)->die = die;
650 		(*range)->dbg = dbg;
651 		STAILQ_INIT(&(*range)->funclist);
652 		RB_INSERT(cutree, &cuhead, *range);
653 		curlopc = lopc;
654 		return (DW_DLV_OK);
655 	} else {
656 		return (DW_DLV_NO_ENTRY);
657 	}
658 }
659 
660 static void
661 translate(Dwarf_Debug dbg, Elf *e, const char* addrstr)
662 {
663 	Dwarf_Die die, ret_die;
664 	Dwarf_Line *lbuf;
665 	Dwarf_Error de;
666 	Dwarf_Half tag;
667 	Dwarf_Unsigned addr, lineno, plineno;
668 	Dwarf_Signed lcount;
669 	Dwarf_Addr lineaddr, plineaddr;
670 	struct range *range;
671 	struct Func *f;
672 	const char *funcname;
673 	char *file, *file0, *pfile;
674 	char demangled[1024];
675 	int ec, i, ret;
676 
677 	addr = strtoull(addrstr, NULL, 16);
678 	addr += section_base;
679 	lineno = 0;
680 	file = unknown;
681 	die = NULL;
682 	ret = DW_DLV_OK;
683 
684 	range = culookup(addr);
685 	if (range != NULL) {
686 		die = range->die;
687 		dbg = range->dbg;
688 		goto status_ok;
689 	}
690 
691 	while (true) {
692 		/*
693 		 * We resume the CU scan from the last place we found a match.
694 		 * Because when we have 2 sequential addresses, and the second
695 		 * one is of the next CU, it is faster to just go to the next CU
696 		 * instead of starting from the beginning.
697 		 */
698 		ret = dwarf_next_cu_header(dbg, NULL, NULL, NULL, NULL, NULL,
699 		    &de);
700 		if (ret == DW_DLV_NO_ENTRY) {
701 			if (curlopc == ~0ULL)
702 				goto out;
703 			ret = dwarf_next_cu_header(dbg, NULL, NULL, NULL, NULL,
704 			    NULL, &de);
705 		}
706 		die = NULL;
707 		while (dwarf_siblingof(dbg, die, &ret_die, &de) == DW_DLV_OK) {
708 			if (die != NULL)
709 				dwarf_dealloc(dbg, die, DW_DLA_DIE);
710 			die = ret_die;
711 			if (dwarf_tag(die, &tag, &de) != DW_DLV_OK) {
712 				warnx("dwarf_tag failed: %s",
713 				    dwarf_errmsg(de));
714 				goto next_cu;
715 			}
716 
717 			/* XXX: What about DW_TAG_partial_unit? */
718 			if (tag == DW_TAG_compile_unit)
719 				break;
720 		}
721 
722 		if (ret_die == NULL) {
723 			warnx("could not find DW_TAG_compile_unit die");
724 			goto next_cu;
725 		}
726 		ret = check_range(dbg, die, addr, &range);
727 		if (ret == DW_DLV_OK)
728 			break;
729 		if (ret == DW_DLV_ERROR)
730 			goto out;
731 next_cu:
732 		if (die != NULL) {
733 			dwarf_dealloc(dbg, die, DW_DLA_DIE);
734 			die = NULL;
735 		}
736 	}
737 
738 	if (ret != DW_DLV_OK || die == NULL)
739 		goto out;
740 
741 status_ok:
742 	switch (dwarf_srclines(die, &lbuf, &lcount, &de)) {
743 	case DW_DLV_OK:
744 		break;
745 	case DW_DLV_NO_ENTRY:
746 		/* If a CU lacks debug info, just skip it. */
747 		goto out;
748 	default:
749 		warnx("dwarf_srclines: %s", dwarf_errmsg(de));
750 		goto out;
751 	}
752 
753 	plineaddr = ~0ULL;
754 	plineno = 0;
755 	pfile = unknown;
756 	for (i = 0; i < lcount; i++) {
757 		if (dwarf_lineaddr(lbuf[i], &lineaddr, &de)) {
758 			warnx("dwarf_lineaddr: %s", dwarf_errmsg(de));
759 			goto out;
760 		}
761 		if (dwarf_lineno(lbuf[i], &lineno, &de)) {
762 			warnx("dwarf_lineno: %s", dwarf_errmsg(de));
763 			goto out;
764 		}
765 		if (dwarf_linesrc(lbuf[i], &file0, &de)) {
766 			warnx("dwarf_linesrc: %s", dwarf_errmsg(de));
767 		} else
768 			file = file0;
769 		if (addr == lineaddr)
770 			goto out;
771 		else if (addr < lineaddr && addr > plineaddr) {
772 			lineno = plineno;
773 			file = pfile;
774 			goto out;
775 		}
776 		plineaddr = lineaddr;
777 		plineno = lineno;
778 		pfile = file;
779 	}
780 
781 out:
782 	f = NULL;
783 	funcname = NULL;
784 	if (ret == DW_DLV_OK && (func || inlines) && range != NULL) {
785 		if (range->srcfiles == NULL)
786 			if (dwarf_srcfiles(die, &range->srcfiles,
787 			    &range->nsrcfiles, &de))
788 				warnx("dwarf_srcfiles: %s", dwarf_errmsg(de));
789 		if (STAILQ_EMPTY(&range->funclist)) {
790 			collect_func(dbg, range->die, NULL, range);
791 			die = NULL;
792 		}
793 		f = search_func(range, addr);
794 		if (f != NULL)
795 			funcname = f->name;
796 	}
797 
798 	if (print_addr) {
799 		if ((ec = gelf_getclass(e)) == ELFCLASSNONE) {
800 			warnx("gelf_getclass failed: %s", elf_errmsg(-1));
801 			ec = ELFCLASS64;
802 		}
803 		if (ec == ELFCLASS32) {
804 			if (pretty_print)
805 				printf("0x%08jx: ", (uintmax_t) addr);
806 			else
807 				printf("0x%08jx\n", (uintmax_t) addr);
808 		} else {
809 			if (pretty_print)
810 				printf("0x%016jx: ", (uintmax_t) addr);
811 			else
812 				printf("0x%016jx\n", (uintmax_t) addr);
813 		}
814 	}
815 
816 	if (func) {
817 		if (funcname == NULL)
818 			funcname = unknown;
819 		if (demangle && !elftc_demangle(funcname, demangled,
820 		    sizeof(demangled), 0)) {
821 			if (pretty_print)
822 				printf("%s at ", demangled);
823 			else
824 				printf("%s\n", demangled);
825 		} else {
826 			if (pretty_print)
827 				printf("%s at ", funcname);
828 			else
829 				printf("%s\n", funcname);
830 		}
831 	}
832 
833 	(void) printf("%s:%ju\n", base ? basename(file) : file,
834 	    (uintmax_t) lineno);
835 
836 	if (ret == DW_DLV_OK && inlines && range != NULL &&
837 	    range->srcfiles != NULL && f != NULL && f->inlined_caller != NULL)
838 		print_inlines(range, f->inlined_caller, f->call_file,
839 		    f->call_line);
840 }
841 
842 static void
843 find_section_base(const char *exe, Elf *e, const char *section)
844 {
845 	Dwarf_Addr off;
846 	Elf_Scn *scn;
847 	GElf_Ehdr eh;
848 	GElf_Shdr sh;
849 	size_t shstrndx;
850 	int elferr;
851 	const char *name;
852 
853 	if (gelf_getehdr(e, &eh) != &eh) {
854 		warnx("gelf_getehdr failed: %s", elf_errmsg(-1));
855 		return;
856 	}
857 
858 	if (!elf_getshstrndx(e, &shstrndx)) {
859 		warnx("elf_getshstrndx failed: %s", elf_errmsg(-1));
860 		return;
861 	}
862 
863 	(void) elf_errno();
864 	off = 0;
865 	scn = NULL;
866 	while ((scn = elf_nextscn(e, scn)) != NULL) {
867 		if (gelf_getshdr(scn, &sh) == NULL) {
868 			warnx("gelf_getshdr failed: %s", elf_errmsg(-1));
869 			continue;
870 		}
871 		if ((name = elf_strptr(e, shstrndx, sh.sh_name)) == NULL)
872 			goto next;
873 		if (!strcmp(section, name)) {
874 			if (eh.e_type == ET_EXEC || eh.e_type == ET_DYN) {
875 				/*
876 				 * For executables, section base is the virtual
877 				 * address of the specified section.
878 				 */
879 				section_base = sh.sh_addr;
880 			} else if (eh.e_type == ET_REL) {
881 				/*
882 				 * For relocatables, section base is the
883 				 * relative offset of the specified section
884 				 * to the start of the first section.
885 				 */
886 				section_base = off;
887 			} else
888 				warnx("unknown e_type %u", eh.e_type);
889 			return;
890 		}
891 	next:
892 		off += sh.sh_size;
893 	}
894 	elferr = elf_errno();
895 	if (elferr != 0)
896 		warnx("elf_nextscn failed: %s", elf_errmsg(elferr));
897 
898 	errx(EXIT_FAILURE, "%s: cannot find section %s", exe, section);
899 }
900 
901 int
902 main(int argc, char **argv)
903 {
904 	cap_rights_t rights;
905 	Elf *e;
906 	Dwarf_Debug dbg;
907 	Dwarf_Error de;
908 	const char *exe, *section;
909 	char line[1024];
910 	int fd, i, opt;
911 
912 	exe = NULL;
913 	section = NULL;
914 	while ((opt = getopt_long(argc, argv, "ab:Ce:fij:psHV", longopts,
915 	    NULL)) != -1) {
916 		switch (opt) {
917 		case 'a':
918 			print_addr = 1;
919 			break;
920 		case 'b':
921 			/* ignored */
922 			break;
923 		case 'C':
924 			demangle = 1;
925 			break;
926 		case 'e':
927 			exe = optarg;
928 			break;
929 		case 'f':
930 			func = 1;
931 			break;
932 		case 'i':
933 			inlines = 1;
934 			break;
935 		case 'j':
936 			section = optarg;
937 			break;
938 		case 'p':
939 			pretty_print = 1;
940 			break;
941 		case 's':
942 			base = 1;
943 			break;
944 		case 'H':
945 			usage();
946 		case 'V':
947 			version();
948 		default:
949 			usage();
950 		}
951 	}
952 
953 	argv += optind;
954 	argc -= optind;
955 
956 	if (exe == NULL)
957 		exe = "a.out";
958 
959 	if ((fd = open(exe, O_RDONLY)) < 0)
960 		err(EXIT_FAILURE, "%s", exe);
961 
962 	if (caph_rights_limit(fd, cap_rights_init(&rights, CAP_FSTAT,
963 	    CAP_MMAP_R)) < 0)
964 		errx(EXIT_FAILURE, "caph_rights_limit");
965 
966 	caph_cache_catpages();
967 	if (caph_limit_stdio() < 0)
968 		errx(EXIT_FAILURE, "failed to limit stdio rights");
969 	if (caph_enter() < 0)
970 		errx(EXIT_FAILURE, "failed to enter capability mode");
971 
972 	if (dwarf_init(fd, DW_DLC_READ, NULL, NULL, &dbg, &de))
973 		errx(EXIT_FAILURE, "dwarf_init: %s", dwarf_errmsg(de));
974 
975 	if (dwarf_get_elf(dbg, &e, &de) != DW_DLV_OK)
976 		errx(EXIT_FAILURE, "dwarf_get_elf: %s", dwarf_errmsg(de));
977 
978 	if (section)
979 		find_section_base(exe, e, section);
980 	else
981 		section_base = 0;
982 
983 	if (argc > 0)
984 		for (i = 0; i < argc; i++)
985 			translate(dbg, e, argv[i]);
986 	else {
987 		setvbuf(stdout, NULL, _IOLBF, 0);
988 		while (fgets(line, sizeof(line), stdin) != NULL)
989 			translate(dbg, e, line);
990 	}
991 
992 	dwarf_finish(dbg, &de);
993 
994 	(void) elf_end(e);
995 
996 	exit(0);
997 }
998