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