]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/elftoolchain/readelf/readelf.c
MFHead@r345677
[FreeBSD/FreeBSD.git] / contrib / elftoolchain / readelf / readelf.c
1 /*-
2  * Copyright (c) 2009-2015 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/queue.h>
29 #include <ar.h>
30 #include <assert.h>
31 #include <ctype.h>
32 #include <dwarf.h>
33 #include <err.h>
34 #include <fcntl.h>
35 #include <gelf.h>
36 #include <getopt.h>
37 #include <libdwarf.h>
38 #include <libelftc.h>
39 #include <libgen.h>
40 #include <stdarg.h>
41 #include <stdint.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <time.h>
46 #include <unistd.h>
47
48 #include "_elftc.h"
49
50 ELFTC_VCSID("$Id: readelf.c 3649 2018-11-24 03:26:23Z emaste $");
51
52 /* Backwards compatability for older FreeBSD releases. */
53 #ifndef STB_GNU_UNIQUE
54 #define STB_GNU_UNIQUE 10
55 #endif
56 #ifndef STT_SPARC_REGISTER
57 #define STT_SPARC_REGISTER 13
58 #endif
59
60
61 /*
62  * readelf(1) options.
63  */
64 #define RE_AA   0x00000001
65 #define RE_C    0x00000002
66 #define RE_DD   0x00000004
67 #define RE_D    0x00000008
68 #define RE_G    0x00000010
69 #define RE_H    0x00000020
70 #define RE_II   0x00000040
71 #define RE_I    0x00000080
72 #define RE_L    0x00000100
73 #define RE_NN   0x00000200
74 #define RE_N    0x00000400
75 #define RE_P    0x00000800
76 #define RE_R    0x00001000
77 #define RE_SS   0x00002000
78 #define RE_S    0x00004000
79 #define RE_T    0x00008000
80 #define RE_U    0x00010000
81 #define RE_VV   0x00020000
82 #define RE_WW   0x00040000
83 #define RE_W    0x00080000
84 #define RE_X    0x00100000
85
86 /*
87  * dwarf dump options.
88  */
89 #define DW_A    0x00000001
90 #define DW_FF   0x00000002
91 #define DW_F    0x00000004
92 #define DW_I    0x00000008
93 #define DW_LL   0x00000010
94 #define DW_L    0x00000020
95 #define DW_M    0x00000040
96 #define DW_O    0x00000080
97 #define DW_P    0x00000100
98 #define DW_RR   0x00000200
99 #define DW_R    0x00000400
100 #define DW_S    0x00000800
101
102 #define DW_DEFAULT_OPTIONS (DW_A | DW_F | DW_I | DW_L | DW_O | DW_P | \
103             DW_R | DW_RR | DW_S)
104
105 /*
106  * readelf(1) run control flags.
107  */
108 #define DISPLAY_FILENAME        0x0001
109
110 /*
111  * Internal data structure for sections.
112  */
113 struct section {
114         const char      *name;          /* section name */
115         Elf_Scn         *scn;           /* section scn */
116         uint64_t         off;           /* section offset */
117         uint64_t         sz;            /* section size */
118         uint64_t         entsize;       /* section entsize */
119         uint64_t         align;         /* section alignment */
120         uint64_t         type;          /* section type */
121         uint64_t         flags;         /* section flags */
122         uint64_t         addr;          /* section virtual addr */
123         uint32_t         link;          /* section link ndx */
124         uint32_t         info;          /* section info ndx */
125 };
126
127 struct dumpop {
128         union {
129                 size_t si;              /* section index */
130                 const char *sn;         /* section name */
131         } u;
132         enum {
133                 DUMP_BY_INDEX = 0,
134                 DUMP_BY_NAME
135         } type;                         /* dump type */
136 #define HEX_DUMP        0x0001
137 #define STR_DUMP        0x0002
138         int op;                         /* dump operation */
139         STAILQ_ENTRY(dumpop) dumpop_list;
140 };
141
142 struct symver {
143         const char *name;
144         int type;
145 };
146
147 /*
148  * Structure encapsulates the global data for readelf(1).
149  */
150 struct readelf {
151         const char       *filename;     /* current processing file. */
152         int               options;      /* command line options. */
153         int               flags;        /* run control flags. */
154         int               dop;          /* dwarf dump options. */
155         Elf              *elf;          /* underlying ELF descriptor. */
156         Elf              *ar;           /* archive ELF descriptor. */
157         Dwarf_Debug       dbg;          /* DWARF handle. */
158         Dwarf_Half        cu_psize;     /* DWARF CU pointer size. */
159         Dwarf_Half        cu_osize;     /* DWARF CU offset size. */
160         Dwarf_Half        cu_ver;       /* DWARF CU version. */
161         GElf_Ehdr         ehdr;         /* ELF header. */
162         int               ec;           /* ELF class. */
163         size_t            shnum;        /* #sections. */
164         struct section   *vd_s;         /* Verdef section. */
165         struct section   *vn_s;         /* Verneed section. */
166         struct section   *vs_s;         /* Versym section. */
167         uint16_t         *vs;           /* Versym array. */
168         int               vs_sz;        /* Versym array size. */
169         struct symver    *ver;          /* Version array. */
170         int               ver_sz;       /* Size of version array. */
171         struct section   *sl;           /* list of sections. */
172         STAILQ_HEAD(, dumpop) v_dumpop; /* list of dump ops. */
173         uint64_t        (*dw_read)(Elf_Data *, uint64_t *, int);
174         uint64_t        (*dw_decode)(uint8_t **, int);
175 };
176
177 enum options
178 {
179         OPTION_DEBUG_DUMP
180 };
181
182 static struct option longopts[] = {
183         {"all", no_argument, NULL, 'a'},
184         {"arch-specific", no_argument, NULL, 'A'},
185         {"archive-index", no_argument, NULL, 'c'},
186         {"debug-dump", optional_argument, NULL, OPTION_DEBUG_DUMP},
187         {"dynamic", no_argument, NULL, 'd'},
188         {"file-header", no_argument, NULL, 'h'},
189         {"full-section-name", no_argument, NULL, 'N'},
190         {"headers", no_argument, NULL, 'e'},
191         {"help", no_argument, 0, 'H'},
192         {"hex-dump", required_argument, NULL, 'x'},
193         {"histogram", no_argument, NULL, 'I'},
194         {"notes", no_argument, NULL, 'n'},
195         {"program-headers", no_argument, NULL, 'l'},
196         {"relocs", no_argument, NULL, 'r'},
197         {"sections", no_argument, NULL, 'S'},
198         {"section-headers", no_argument, NULL, 'S'},
199         {"section-groups", no_argument, NULL, 'g'},
200         {"section-details", no_argument, NULL, 't'},
201         {"segments", no_argument, NULL, 'l'},
202         {"string-dump", required_argument, NULL, 'p'},
203         {"symbols", no_argument, NULL, 's'},
204         {"syms", no_argument, NULL, 's'},
205         {"unwind", no_argument, NULL, 'u'},
206         {"use-dynamic", no_argument, NULL, 'D'},
207         {"version-info", no_argument, 0, 'V'},
208         {"version", no_argument, 0, 'v'},
209         {"wide", no_argument, 0, 'W'},
210         {NULL, 0, NULL, 0}
211 };
212
213 struct eflags_desc {
214         uint64_t flag;
215         const char *desc;
216 };
217
218 struct mips_option {
219         uint64_t flag;
220         const char *desc;
221 };
222
223 struct flag_desc {
224         uint64_t flag;
225         const char *desc;
226 };
227
228 static void add_dumpop(struct readelf *re, size_t si, const char *sn, int op,
229     int t);
230 static const char *aeabi_adv_simd_arch(uint64_t simd);
231 static const char *aeabi_align_needed(uint64_t an);
232 static const char *aeabi_align_preserved(uint64_t ap);
233 static const char *aeabi_arm_isa(uint64_t ai);
234 static const char *aeabi_cpu_arch(uint64_t arch);
235 static const char *aeabi_cpu_arch_profile(uint64_t pf);
236 static const char *aeabi_div(uint64_t du);
237 static const char *aeabi_enum_size(uint64_t es);
238 static const char *aeabi_fp_16bit_format(uint64_t fp16);
239 static const char *aeabi_fp_arch(uint64_t fp);
240 static const char *aeabi_fp_denormal(uint64_t fd);
241 static const char *aeabi_fp_exceptions(uint64_t fe);
242 static const char *aeabi_fp_hpext(uint64_t fh);
243 static const char *aeabi_fp_number_model(uint64_t fn);
244 static const char *aeabi_fp_optm_goal(uint64_t fog);
245 static const char *aeabi_fp_rounding(uint64_t fr);
246 static const char *aeabi_hardfp(uint64_t hfp);
247 static const char *aeabi_mpext(uint64_t mp);
248 static const char *aeabi_optm_goal(uint64_t og);
249 static const char *aeabi_pcs_config(uint64_t pcs);
250 static const char *aeabi_pcs_got(uint64_t got);
251 static const char *aeabi_pcs_r9(uint64_t r9);
252 static const char *aeabi_pcs_ro(uint64_t ro);
253 static const char *aeabi_pcs_rw(uint64_t rw);
254 static const char *aeabi_pcs_wchar_t(uint64_t wt);
255 static const char *aeabi_t2ee(uint64_t t2ee);
256 static const char *aeabi_thumb_isa(uint64_t ti);
257 static const char *aeabi_fp_user_exceptions(uint64_t fu);
258 static const char *aeabi_unaligned_access(uint64_t ua);
259 static const char *aeabi_vfp_args(uint64_t va);
260 static const char *aeabi_virtual(uint64_t vt);
261 static const char *aeabi_wmmx_arch(uint64_t wmmx);
262 static const char *aeabi_wmmx_args(uint64_t wa);
263 static const char *elf_class(unsigned int class);
264 static const char *elf_endian(unsigned int endian);
265 static const char *elf_machine(unsigned int mach);
266 static const char *elf_osabi(unsigned int abi);
267 static const char *elf_type(unsigned int type);
268 static const char *elf_ver(unsigned int ver);
269 static const char *dt_type(unsigned int mach, unsigned int dtype);
270 static void dump_ar(struct readelf *re, int);
271 static void dump_arm_attributes(struct readelf *re, uint8_t *p, uint8_t *pe);
272 static void dump_attributes(struct readelf *re);
273 static uint8_t *dump_compatibility_tag(uint8_t *p, uint8_t *pe);
274 static void dump_dwarf(struct readelf *re);
275 static void dump_dwarf_abbrev(struct readelf *re);
276 static void dump_dwarf_aranges(struct readelf *re);
277 static void dump_dwarf_block(struct readelf *re, uint8_t *b,
278     Dwarf_Unsigned len);
279 static void dump_dwarf_die(struct readelf *re, Dwarf_Die die, int level);
280 static void dump_dwarf_frame(struct readelf *re, int alt);
281 static void dump_dwarf_frame_inst(struct readelf *re, Dwarf_Cie cie,
282     uint8_t *insts, Dwarf_Unsigned len, Dwarf_Unsigned caf, Dwarf_Signed daf,
283     Dwarf_Addr pc, Dwarf_Debug dbg);
284 static int dump_dwarf_frame_regtable(struct readelf *re, Dwarf_Fde fde,
285     Dwarf_Addr pc, Dwarf_Unsigned func_len, Dwarf_Half cie_ra);
286 static void dump_dwarf_frame_section(struct readelf *re, struct section *s,
287     int alt);
288 static void dump_dwarf_info(struct readelf *re, Dwarf_Bool is_info);
289 static void dump_dwarf_macinfo(struct readelf *re);
290 static void dump_dwarf_line(struct readelf *re);
291 static void dump_dwarf_line_decoded(struct readelf *re);
292 static void dump_dwarf_loc(struct readelf *re, Dwarf_Loc *lr);
293 static void dump_dwarf_loclist(struct readelf *re);
294 static void dump_dwarf_pubnames(struct readelf *re);
295 static void dump_dwarf_ranges(struct readelf *re);
296 static void dump_dwarf_ranges_foreach(struct readelf *re, Dwarf_Die die,
297     Dwarf_Addr base);
298 static void dump_dwarf_str(struct readelf *re);
299 static void dump_eflags(struct readelf *re, uint64_t e_flags);
300 static void dump_elf(struct readelf *re);
301 static void dump_flags(struct flag_desc *fd, uint64_t flags);
302 static void dump_dyn_val(struct readelf *re, GElf_Dyn *dyn, uint32_t stab);
303 static void dump_dynamic(struct readelf *re);
304 static void dump_liblist(struct readelf *re);
305 static void dump_mips_abiflags(struct readelf *re, struct section *s);
306 static void dump_mips_attributes(struct readelf *re, uint8_t *p, uint8_t *pe);
307 static void dump_mips_odk_reginfo(struct readelf *re, uint8_t *p, size_t sz);
308 static void dump_mips_options(struct readelf *re, struct section *s);
309 static void dump_mips_option_flags(const char *name, struct mips_option *opt,
310     uint64_t info);
311 static void dump_mips_reginfo(struct readelf *re, struct section *s);
312 static void dump_mips_specific_info(struct readelf *re);
313 static void dump_notes(struct readelf *re);
314 static void dump_notes_content(struct readelf *re, const char *buf, size_t sz,
315     off_t off);
316 static void dump_notes_data(const char *name, uint32_t type, const char *buf,
317     size_t sz);
318 static void dump_svr4_hash(struct section *s);
319 static void dump_svr4_hash64(struct readelf *re, struct section *s);
320 static void dump_gnu_hash(struct readelf *re, struct section *s);
321 static void dump_hash(struct readelf *re);
322 static void dump_phdr(struct readelf *re);
323 static void dump_ppc_attributes(uint8_t *p, uint8_t *pe);
324 static void dump_section_groups(struct readelf *re);
325 static void dump_symtab(struct readelf *re, int i);
326 static void dump_symtabs(struct readelf *re);
327 static uint8_t *dump_unknown_tag(uint64_t tag, uint8_t *p, uint8_t *pe);
328 static void dump_ver(struct readelf *re);
329 static void dump_verdef(struct readelf *re, int dump);
330 static void dump_verneed(struct readelf *re, int dump);
331 static void dump_versym(struct readelf *re);
332 static const char *dwarf_reg(unsigned int mach, unsigned int reg);
333 static const char *dwarf_regname(struct readelf *re, unsigned int num);
334 static struct dumpop *find_dumpop(struct readelf *re, size_t si,
335     const char *sn, int op, int t);
336 static int get_ent_count(struct section *s, int *ent_count);
337 static int get_mips_register_size(uint8_t flag);
338 static char *get_regoff_str(struct readelf *re, Dwarf_Half reg,
339     Dwarf_Addr off);
340 static const char *get_string(struct readelf *re, int strtab, size_t off);
341 static const char *get_symbol_name(struct readelf *re, int symtab, int i);
342 static uint64_t get_symbol_value(struct readelf *re, int symtab, int i);
343 static void load_sections(struct readelf *re);
344 static const char *mips_abi_fp(uint64_t fp);
345 static const char *note_type(const char *note_name, unsigned int et,
346     unsigned int nt);
347 static const char *note_type_freebsd(unsigned int nt);
348 static const char *note_type_freebsd_core(unsigned int nt);
349 static const char *note_type_linux_core(unsigned int nt);
350 static const char *note_type_gnu(unsigned int nt);
351 static const char *note_type_netbsd(unsigned int nt);
352 static const char *note_type_openbsd(unsigned int nt);
353 static const char *note_type_unknown(unsigned int nt);
354 static const char *note_type_xen(unsigned int nt);
355 static const char *option_kind(uint8_t kind);
356 static const char *phdr_type(unsigned int mach, unsigned int ptype);
357 static const char *ppc_abi_fp(uint64_t fp);
358 static const char *ppc_abi_vector(uint64_t vec);
359 static void readelf_usage(int status);
360 static void readelf_version(void);
361 static void search_loclist_at(struct readelf *re, Dwarf_Die die,
362     Dwarf_Unsigned lowpc);
363 static void search_ver(struct readelf *re);
364 static const char *section_type(unsigned int mach, unsigned int stype);
365 static void set_cu_context(struct readelf *re, Dwarf_Half psize,
366     Dwarf_Half osize, Dwarf_Half ver);
367 static const char *st_bind(unsigned int sbind);
368 static const char *st_shndx(unsigned int shndx);
369 static const char *st_type(unsigned int mach, unsigned int os,
370     unsigned int stype);
371 static const char *st_vis(unsigned int svis);
372 static const char *top_tag(unsigned int tag);
373 static void unload_sections(struct readelf *re);
374 static uint64_t _read_lsb(Elf_Data *d, uint64_t *offsetp,
375     int bytes_to_read);
376 static uint64_t _read_msb(Elf_Data *d, uint64_t *offsetp,
377     int bytes_to_read);
378 static uint64_t _decode_lsb(uint8_t **data, int bytes_to_read);
379 static uint64_t _decode_msb(uint8_t **data, int bytes_to_read);
380 static int64_t _decode_sleb128(uint8_t **dp, uint8_t *dpe);
381 static uint64_t _decode_uleb128(uint8_t **dp, uint8_t *dpe);
382
383 static struct eflags_desc arm_eflags_desc[] = {
384         {EF_ARM_RELEXEC, "relocatable executable"},
385         {EF_ARM_HASENTRY, "has entry point"},
386         {EF_ARM_SYMSARESORTED, "sorted symbol tables"},
387         {EF_ARM_DYNSYMSUSESEGIDX, "dynamic symbols use segment index"},
388         {EF_ARM_MAPSYMSFIRST, "mapping symbols precede others"},
389         {EF_ARM_BE8, "BE8"},
390         {EF_ARM_LE8, "LE8"},
391         {EF_ARM_INTERWORK, "interworking enabled"},
392         {EF_ARM_APCS_26, "uses APCS/26"},
393         {EF_ARM_APCS_FLOAT, "uses APCS/float"},
394         {EF_ARM_PIC, "position independent"},
395         {EF_ARM_ALIGN8, "8 bit structure alignment"},
396         {EF_ARM_NEW_ABI, "uses new ABI"},
397         {EF_ARM_OLD_ABI, "uses old ABI"},
398         {EF_ARM_SOFT_FLOAT, "software FP"},
399         {EF_ARM_VFP_FLOAT, "VFP"},
400         {EF_ARM_MAVERICK_FLOAT, "Maverick FP"},
401         {0, NULL}
402 };
403
404 static struct eflags_desc mips_eflags_desc[] = {
405         {EF_MIPS_NOREORDER, "noreorder"},
406         {EF_MIPS_PIC, "pic"},
407         {EF_MIPS_CPIC, "cpic"},
408         {EF_MIPS_UCODE, "ugen_reserved"},
409         {EF_MIPS_ABI2, "abi2"},
410         {EF_MIPS_OPTIONS_FIRST, "odk first"},
411         {EF_MIPS_ARCH_ASE_MDMX, "mdmx"},
412         {EF_MIPS_ARCH_ASE_M16, "mips16"},
413         {0, NULL}
414 };
415
416 static struct eflags_desc powerpc_eflags_desc[] = {
417         {EF_PPC_EMB, "emb"},
418         {EF_PPC_RELOCATABLE, "relocatable"},
419         {EF_PPC_RELOCATABLE_LIB, "relocatable-lib"},
420         {0, NULL}
421 };
422
423 static struct eflags_desc sparc_eflags_desc[] = {
424         {EF_SPARC_32PLUS, "v8+"},
425         {EF_SPARC_SUN_US1, "ultrasparcI"},
426         {EF_SPARC_HAL_R1, "halr1"},
427         {EF_SPARC_SUN_US3, "ultrasparcIII"},
428         {0, NULL}
429 };
430
431 static const char *
432 elf_osabi(unsigned int abi)
433 {
434         static char s_abi[32];
435
436         switch(abi) {
437         case ELFOSABI_NONE: return "NONE";
438         case ELFOSABI_HPUX: return "HPUX";
439         case ELFOSABI_NETBSD: return "NetBSD";
440         case ELFOSABI_GNU: return "GNU";
441         case ELFOSABI_HURD: return "HURD";
442         case ELFOSABI_86OPEN: return "86OPEN";
443         case ELFOSABI_SOLARIS: return "Solaris";
444         case ELFOSABI_AIX: return "AIX";
445         case ELFOSABI_IRIX: return "IRIX";
446         case ELFOSABI_FREEBSD: return "FreeBSD";
447         case ELFOSABI_TRU64: return "TRU64";
448         case ELFOSABI_MODESTO: return "MODESTO";
449         case ELFOSABI_OPENBSD: return "OpenBSD";
450         case ELFOSABI_OPENVMS: return "OpenVMS";
451         case ELFOSABI_NSK: return "NSK";
452         case ELFOSABI_CLOUDABI: return "CloudABI";
453         case ELFOSABI_ARM_AEABI: return "ARM EABI";
454         case ELFOSABI_ARM: return "ARM";
455         case ELFOSABI_STANDALONE: return "StandAlone";
456         default:
457                 snprintf(s_abi, sizeof(s_abi), "<unknown: %#x>", abi);
458                 return (s_abi);
459         }
460 };
461
462 static const char *
463 elf_machine(unsigned int mach)
464 {
465         static char s_mach[32];
466
467         switch (mach) {
468         case EM_NONE: return "Unknown machine";
469         case EM_M32: return "AT&T WE32100";
470         case EM_SPARC: return "Sun SPARC";
471         case EM_386: return "Intel i386";
472         case EM_68K: return "Motorola 68000";
473         case EM_IAMCU: return "Intel MCU";
474         case EM_88K: return "Motorola 88000";
475         case EM_860: return "Intel i860";
476         case EM_MIPS: return "MIPS R3000 Big-Endian only";
477         case EM_S370: return "IBM System/370";
478         case EM_MIPS_RS3_LE: return "MIPS R3000 Little-Endian";
479         case EM_PARISC: return "HP PA-RISC";
480         case EM_VPP500: return "Fujitsu VPP500";
481         case EM_SPARC32PLUS: return "SPARC v8plus";
482         case EM_960: return "Intel 80960";
483         case EM_PPC: return "PowerPC 32-bit";
484         case EM_PPC64: return "PowerPC 64-bit";
485         case EM_S390: return "IBM System/390";
486         case EM_V800: return "NEC V800";
487         case EM_FR20: return "Fujitsu FR20";
488         case EM_RH32: return "TRW RH-32";
489         case EM_RCE: return "Motorola RCE";
490         case EM_ARM: return "ARM";
491         case EM_SH: return "Hitachi SH";
492         case EM_SPARCV9: return "SPARC v9 64-bit";
493         case EM_TRICORE: return "Siemens TriCore embedded processor";
494         case EM_ARC: return "Argonaut RISC Core";
495         case EM_H8_300: return "Hitachi H8/300";
496         case EM_H8_300H: return "Hitachi H8/300H";
497         case EM_H8S: return "Hitachi H8S";
498         case EM_H8_500: return "Hitachi H8/500";
499         case EM_IA_64: return "Intel IA-64 Processor";
500         case EM_MIPS_X: return "Stanford MIPS-X";
501         case EM_COLDFIRE: return "Motorola ColdFire";
502         case EM_68HC12: return "Motorola M68HC12";
503         case EM_MMA: return "Fujitsu MMA";
504         case EM_PCP: return "Siemens PCP";
505         case EM_NCPU: return "Sony nCPU";
506         case EM_NDR1: return "Denso NDR1 microprocessor";
507         case EM_STARCORE: return "Motorola Star*Core processor";
508         case EM_ME16: return "Toyota ME16 processor";
509         case EM_ST100: return "STMicroelectronics ST100 processor";
510         case EM_TINYJ: return "Advanced Logic Corp. TinyJ processor";
511         case EM_X86_64: return "Advanced Micro Devices x86-64";
512         case EM_PDSP: return "Sony DSP Processor";
513         case EM_FX66: return "Siemens FX66 microcontroller";
514         case EM_ST9PLUS: return "STMicroelectronics ST9+ 8/16 microcontroller";
515         case EM_ST7: return "STmicroelectronics ST7 8-bit microcontroller";
516         case EM_68HC16: return "Motorola MC68HC16 microcontroller";
517         case EM_68HC11: return "Motorola MC68HC11 microcontroller";
518         case EM_68HC08: return "Motorola MC68HC08 microcontroller";
519         case EM_68HC05: return "Motorola MC68HC05 microcontroller";
520         case EM_SVX: return "Silicon Graphics SVx";
521         case EM_ST19: return "STMicroelectronics ST19 8-bit mc";
522         case EM_VAX: return "Digital VAX";
523         case EM_CRIS: return "Axis Communications 32-bit embedded processor";
524         case EM_JAVELIN: return "Infineon Tech. 32bit embedded processor";
525         case EM_FIREPATH: return "Element 14 64-bit DSP Processor";
526         case EM_ZSP: return "LSI Logic 16-bit DSP Processor";
527         case EM_MMIX: return "Donald Knuth's educational 64-bit proc";
528         case EM_HUANY: return "Harvard University MI object files";
529         case EM_PRISM: return "SiTera Prism";
530         case EM_AVR: return "Atmel AVR 8-bit microcontroller";
531         case EM_FR30: return "Fujitsu FR30";
532         case EM_D10V: return "Mitsubishi D10V";
533         case EM_D30V: return "Mitsubishi D30V";
534         case EM_V850: return "NEC v850";
535         case EM_M32R: return "Mitsubishi M32R";
536         case EM_MN10300: return "Matsushita MN10300";
537         case EM_MN10200: return "Matsushita MN10200";
538         case EM_PJ: return "picoJava";
539         case EM_OPENRISC: return "OpenRISC 32-bit embedded processor";
540         case EM_ARC_A5: return "ARC Cores Tangent-A5";
541         case EM_XTENSA: return "Tensilica Xtensa Architecture";
542         case EM_VIDEOCORE: return "Alphamosaic VideoCore processor";
543         case EM_TMM_GPP: return "Thompson Multimedia General Purpose Processor";
544         case EM_NS32K: return "National Semiconductor 32000 series";
545         case EM_TPC: return "Tenor Network TPC processor";
546         case EM_SNP1K: return "Trebia SNP 1000 processor";
547         case EM_ST200: return "STMicroelectronics ST200 microcontroller";
548         case EM_IP2K: return "Ubicom IP2xxx microcontroller family";
549         case EM_MAX: return "MAX Processor";
550         case EM_CR: return "National Semiconductor CompactRISC microprocessor";
551         case EM_F2MC16: return "Fujitsu F2MC16";
552         case EM_MSP430: return "TI embedded microcontroller msp430";
553         case EM_BLACKFIN: return "Analog Devices Blackfin (DSP) processor";
554         case EM_SE_C33: return "S1C33 Family of Seiko Epson processors";
555         case EM_SEP: return "Sharp embedded microprocessor";
556         case EM_ARCA: return "Arca RISC Microprocessor";
557         case EM_UNICORE: return "Microprocessor series from PKU-Unity Ltd";
558         case EM_AARCH64: return "AArch64";
559         case EM_RISCV: return "RISC-V";
560         default:
561                 snprintf(s_mach, sizeof(s_mach), "<unknown: %#x>", mach);
562                 return (s_mach);
563         }
564
565 }
566
567 static const char *
568 elf_class(unsigned int class)
569 {
570         static char s_class[32];
571
572         switch (class) {
573         case ELFCLASSNONE: return "none";
574         case ELFCLASS32: return "ELF32";
575         case ELFCLASS64: return "ELF64";
576         default:
577                 snprintf(s_class, sizeof(s_class), "<unknown: %#x>", class);
578                 return (s_class);
579         }
580 }
581
582 static const char *
583 elf_endian(unsigned int endian)
584 {
585         static char s_endian[32];
586
587         switch (endian) {
588         case ELFDATANONE: return "none";
589         case ELFDATA2LSB: return "2's complement, little endian";
590         case ELFDATA2MSB: return "2's complement, big endian";
591         default:
592                 snprintf(s_endian, sizeof(s_endian), "<unknown: %#x>", endian);
593                 return (s_endian);
594         }
595 }
596
597 static const char *
598 elf_type(unsigned int type)
599 {
600         static char s_type[32];
601
602         switch (type) {
603         case ET_NONE: return "NONE (None)";
604         case ET_REL: return "REL (Relocatable file)";
605         case ET_EXEC: return "EXEC (Executable file)";
606         case ET_DYN: return "DYN (Shared object file)";
607         case ET_CORE: return "CORE (Core file)";
608         default:
609                 if (type >= ET_LOPROC)
610                         snprintf(s_type, sizeof(s_type), "<proc: %#x>", type);
611                 else if (type >= ET_LOOS && type <= ET_HIOS)
612                         snprintf(s_type, sizeof(s_type), "<os: %#x>", type);
613                 else
614                         snprintf(s_type, sizeof(s_type), "<unknown: %#x>",
615                             type);
616                 return (s_type);
617         }
618 }
619
620 static const char *
621 elf_ver(unsigned int ver)
622 {
623         static char s_ver[32];
624
625         switch (ver) {
626         case EV_CURRENT: return "(current)";
627         case EV_NONE: return "(none)";
628         default:
629                 snprintf(s_ver, sizeof(s_ver), "<unknown: %#x>",
630                     ver);
631                 return (s_ver);
632         }
633 }
634
635 static const char *
636 phdr_type(unsigned int mach, unsigned int ptype)
637 {
638         static char s_ptype[32];
639
640         if (ptype >= PT_LOPROC && ptype <= PT_HIPROC) {
641                 switch (mach) {
642                 case EM_ARM:
643                         switch (ptype) {
644                         case PT_ARM_ARCHEXT: return "ARM_ARCHEXT";
645                         case PT_ARM_EXIDX: return "ARM_EXIDX";
646                         }
647                         break;
648                 }
649                 snprintf(s_ptype, sizeof(s_ptype), "LOPROC+%#x",
650                     ptype - PT_LOPROC);
651                 return (s_ptype);
652         }
653
654         switch (ptype) {
655         case PT_NULL: return "NULL";
656         case PT_LOAD: return "LOAD";
657         case PT_DYNAMIC: return "DYNAMIC";
658         case PT_INTERP: return "INTERP";
659         case PT_NOTE: return "NOTE";
660         case PT_SHLIB: return "SHLIB";
661         case PT_PHDR: return "PHDR";
662         case PT_TLS: return "TLS";
663         case PT_GNU_EH_FRAME: return "GNU_EH_FRAME";
664         case PT_GNU_STACK: return "GNU_STACK";
665         case PT_GNU_RELRO: return "GNU_RELRO";
666         default:
667                 if (ptype >= PT_LOOS && ptype <= PT_HIOS)
668                         snprintf(s_ptype, sizeof(s_ptype), "LOOS+%#x",
669                             ptype - PT_LOOS);
670                 else
671                         snprintf(s_ptype, sizeof(s_ptype), "<unknown: %#x>",
672                             ptype);
673                 return (s_ptype);
674         }
675 }
676
677 static const char *
678 section_type(unsigned int mach, unsigned int stype)
679 {
680         static char s_stype[32];
681
682         if (stype >= SHT_LOPROC && stype <= SHT_HIPROC) {
683                 switch (mach) {
684                 case EM_ARM:
685                         switch (stype) {
686                         case SHT_ARM_EXIDX: return "ARM_EXIDX";
687                         case SHT_ARM_PREEMPTMAP: return "ARM_PREEMPTMAP";
688                         case SHT_ARM_ATTRIBUTES: return "ARM_ATTRIBUTES";
689                         case SHT_ARM_DEBUGOVERLAY: return "ARM_DEBUGOVERLAY";
690                         case SHT_ARM_OVERLAYSECTION: return "ARM_OVERLAYSECTION";
691                         }
692                         break;
693                 case EM_X86_64:
694                         switch (stype) {
695                         case SHT_X86_64_UNWIND: return "X86_64_UNWIND";
696                         default:
697                                 break;
698                         }
699                         break;
700                 case EM_MIPS:
701                 case EM_MIPS_RS3_LE:
702                         switch (stype) {
703                         case SHT_MIPS_LIBLIST: return "MIPS_LIBLIST";
704                         case SHT_MIPS_MSYM: return "MIPS_MSYM";
705                         case SHT_MIPS_CONFLICT: return "MIPS_CONFLICT";
706                         case SHT_MIPS_GPTAB: return "MIPS_GPTAB";
707                         case SHT_MIPS_UCODE: return "MIPS_UCODE";
708                         case SHT_MIPS_DEBUG: return "MIPS_DEBUG";
709                         case SHT_MIPS_REGINFO: return "MIPS_REGINFO";
710                         case SHT_MIPS_PACKAGE: return "MIPS_PACKAGE";
711                         case SHT_MIPS_PACKSYM: return "MIPS_PACKSYM";
712                         case SHT_MIPS_RELD: return "MIPS_RELD";
713                         case SHT_MIPS_IFACE: return "MIPS_IFACE";
714                         case SHT_MIPS_CONTENT: return "MIPS_CONTENT";
715                         case SHT_MIPS_OPTIONS: return "MIPS_OPTIONS";
716                         case SHT_MIPS_DELTASYM: return "MIPS_DELTASYM";
717                         case SHT_MIPS_DELTAINST: return "MIPS_DELTAINST";
718                         case SHT_MIPS_DELTACLASS: return "MIPS_DELTACLASS";
719                         case SHT_MIPS_DWARF: return "MIPS_DWARF";
720                         case SHT_MIPS_DELTADECL: return "MIPS_DELTADECL";
721                         case SHT_MIPS_SYMBOL_LIB: return "MIPS_SYMBOL_LIB";
722                         case SHT_MIPS_EVENTS: return "MIPS_EVENTS";
723                         case SHT_MIPS_TRANSLATE: return "MIPS_TRANSLATE";
724                         case SHT_MIPS_PIXIE: return "MIPS_PIXIE";
725                         case SHT_MIPS_XLATE: return "MIPS_XLATE";
726                         case SHT_MIPS_XLATE_DEBUG: return "MIPS_XLATE_DEBUG";
727                         case SHT_MIPS_WHIRL: return "MIPS_WHIRL";
728                         case SHT_MIPS_EH_REGION: return "MIPS_EH_REGION";
729                         case SHT_MIPS_XLATE_OLD: return "MIPS_XLATE_OLD";
730                         case SHT_MIPS_PDR_EXCEPTION: return "MIPS_PDR_EXCEPTION";
731                         case SHT_MIPS_ABIFLAGS: return "MIPS_ABIFLAGS";
732                         default:
733                                 break;
734                         }
735                         break;
736                 default:
737                         break;
738                 }
739
740                 snprintf(s_stype, sizeof(s_stype), "LOPROC+%#x",
741                     stype - SHT_LOPROC);
742                 return (s_stype);
743         }
744
745         switch (stype) {
746         case SHT_NULL: return "NULL";
747         case SHT_PROGBITS: return "PROGBITS";
748         case SHT_SYMTAB: return "SYMTAB";
749         case SHT_STRTAB: return "STRTAB";
750         case SHT_RELA: return "RELA";
751         case SHT_HASH: return "HASH";
752         case SHT_DYNAMIC: return "DYNAMIC";
753         case SHT_NOTE: return "NOTE";
754         case SHT_NOBITS: return "NOBITS";
755         case SHT_REL: return "REL";
756         case SHT_SHLIB: return "SHLIB";
757         case SHT_DYNSYM: return "DYNSYM";
758         case SHT_INIT_ARRAY: return "INIT_ARRAY";
759         case SHT_FINI_ARRAY: return "FINI_ARRAY";
760         case SHT_PREINIT_ARRAY: return "PREINIT_ARRAY";
761         case SHT_GROUP: return "GROUP";
762         case SHT_SYMTAB_SHNDX: return "SYMTAB_SHNDX";
763         case SHT_SUNW_dof: return "SUNW_dof";
764         case SHT_SUNW_cap: return "SUNW_cap";
765         case SHT_GNU_HASH: return "GNU_HASH";
766         case SHT_SUNW_ANNOTATE: return "SUNW_ANNOTATE";
767         case SHT_SUNW_DEBUGSTR: return "SUNW_DEBUGSTR";
768         case SHT_SUNW_DEBUG: return "SUNW_DEBUG";
769         case SHT_SUNW_move: return "SUNW_move";
770         case SHT_SUNW_COMDAT: return "SUNW_COMDAT";
771         case SHT_SUNW_syminfo: return "SUNW_syminfo";
772         case SHT_SUNW_verdef: return "SUNW_verdef";
773         case SHT_SUNW_verneed: return "SUNW_verneed";
774         case SHT_SUNW_versym: return "SUNW_versym";
775         default:
776                 if (stype >= SHT_LOOS && stype <= SHT_HIOS)
777                         snprintf(s_stype, sizeof(s_stype), "LOOS+%#x",
778                             stype - SHT_LOOS);
779                 else if (stype >= SHT_LOUSER)
780                         snprintf(s_stype, sizeof(s_stype), "LOUSER+%#x",
781                             stype - SHT_LOUSER);
782                 else
783                         snprintf(s_stype, sizeof(s_stype), "<unknown: %#x>",
784                             stype);
785                 return (s_stype);
786         }
787 }
788
789 static const char *
790 dt_type(unsigned int mach, unsigned int dtype)
791 {
792         static char s_dtype[32];
793
794         switch (dtype) {
795         case DT_NULL: return "NULL";
796         case DT_NEEDED: return "NEEDED";
797         case DT_PLTRELSZ: return "PLTRELSZ";
798         case DT_PLTGOT: return "PLTGOT";
799         case DT_HASH: return "HASH";
800         case DT_STRTAB: return "STRTAB";
801         case DT_SYMTAB: return "SYMTAB";
802         case DT_RELA: return "RELA";
803         case DT_RELASZ: return "RELASZ";
804         case DT_RELAENT: return "RELAENT";
805         case DT_STRSZ: return "STRSZ";
806         case DT_SYMENT: return "SYMENT";
807         case DT_INIT: return "INIT";
808         case DT_FINI: return "FINI";
809         case DT_SONAME: return "SONAME";
810         case DT_RPATH: return "RPATH";
811         case DT_SYMBOLIC: return "SYMBOLIC";
812         case DT_REL: return "REL";
813         case DT_RELSZ: return "RELSZ";
814         case DT_RELENT: return "RELENT";
815         case DT_PLTREL: return "PLTREL";
816         case DT_DEBUG: return "DEBUG";
817         case DT_TEXTREL: return "TEXTREL";
818         case DT_JMPREL: return "JMPREL";
819         case DT_BIND_NOW: return "BIND_NOW";
820         case DT_INIT_ARRAY: return "INIT_ARRAY";
821         case DT_FINI_ARRAY: return "FINI_ARRAY";
822         case DT_INIT_ARRAYSZ: return "INIT_ARRAYSZ";
823         case DT_FINI_ARRAYSZ: return "FINI_ARRAYSZ";
824         case DT_RUNPATH: return "RUNPATH";
825         case DT_FLAGS: return "FLAGS";
826         case DT_PREINIT_ARRAY: return "PREINIT_ARRAY";
827         case DT_PREINIT_ARRAYSZ: return "PREINIT_ARRAYSZ";
828         case DT_MAXPOSTAGS: return "MAXPOSTAGS";
829         case DT_SUNW_AUXILIARY: return "SUNW_AUXILIARY";
830         case DT_SUNW_RTLDINF: return "SUNW_RTLDINF";
831         case DT_SUNW_FILTER: return "SUNW_FILTER";
832         case DT_SUNW_CAP: return "SUNW_CAP";
833         case DT_SUNW_ASLR: return "SUNW_ASLR";
834         case DT_CHECKSUM: return "CHECKSUM";
835         case DT_PLTPADSZ: return "PLTPADSZ";
836         case DT_MOVEENT: return "MOVEENT";
837         case DT_MOVESZ: return "MOVESZ";
838         case DT_FEATURE: return "FEATURE";
839         case DT_POSFLAG_1: return "POSFLAG_1";
840         case DT_SYMINSZ: return "SYMINSZ";
841         case DT_SYMINENT: return "SYMINENT";
842         case DT_GNU_HASH: return "GNU_HASH";
843         case DT_TLSDESC_PLT: return "DT_TLSDESC_PLT";
844         case DT_TLSDESC_GOT: return "DT_TLSDESC_GOT";
845         case DT_GNU_CONFLICT: return "GNU_CONFLICT";
846         case DT_GNU_LIBLIST: return "GNU_LIBLIST";
847         case DT_CONFIG: return "CONFIG";
848         case DT_DEPAUDIT: return "DEPAUDIT";
849         case DT_AUDIT: return "AUDIT";
850         case DT_PLTPAD: return "PLTPAD";
851         case DT_MOVETAB: return "MOVETAB";
852         case DT_SYMINFO: return "SYMINFO";
853         case DT_VERSYM: return "VERSYM";
854         case DT_RELACOUNT: return "RELACOUNT";
855         case DT_RELCOUNT: return "RELCOUNT";
856         case DT_FLAGS_1: return "FLAGS_1";
857         case DT_VERDEF: return "VERDEF";
858         case DT_VERDEFNUM: return "VERDEFNUM";
859         case DT_VERNEED: return "VERNEED";
860         case DT_VERNEEDNUM: return "VERNEEDNUM";
861         case DT_AUXILIARY: return "AUXILIARY";
862         case DT_USED: return "USED";
863         case DT_FILTER: return "FILTER";
864         case DT_GNU_PRELINKED: return "GNU_PRELINKED";
865         case DT_GNU_CONFLICTSZ: return "GNU_CONFLICTSZ";
866         case DT_GNU_LIBLISTSZ: return "GNU_LIBLISTSZ";
867         }
868
869         if (dtype >= DT_LOPROC && dtype <= DT_HIPROC) {
870                 switch (mach) {
871                 case EM_ARM:
872                         switch (dtype) {
873                         case DT_ARM_SYMTABSZ:
874                                 return "ARM_SYMTABSZ";
875                         default:
876                                 break;
877                         }
878                         break;
879                 case EM_MIPS:
880                 case EM_MIPS_RS3_LE:
881                         switch (dtype) {
882                         case DT_MIPS_RLD_VERSION:
883                                 return "MIPS_RLD_VERSION";
884                         case DT_MIPS_TIME_STAMP:
885                                 return "MIPS_TIME_STAMP";
886                         case DT_MIPS_ICHECKSUM:
887                                 return "MIPS_ICHECKSUM";
888                         case DT_MIPS_IVERSION:
889                                 return "MIPS_IVERSION";
890                         case DT_MIPS_FLAGS:
891                                 return "MIPS_FLAGS";
892                         case DT_MIPS_BASE_ADDRESS:
893                                 return "MIPS_BASE_ADDRESS";
894                         case DT_MIPS_CONFLICT:
895                                 return "MIPS_CONFLICT";
896                         case DT_MIPS_LIBLIST:
897                                 return "MIPS_LIBLIST";
898                         case DT_MIPS_LOCAL_GOTNO:
899                                 return "MIPS_LOCAL_GOTNO";
900                         case DT_MIPS_CONFLICTNO:
901                                 return "MIPS_CONFLICTNO";
902                         case DT_MIPS_LIBLISTNO:
903                                 return "MIPS_LIBLISTNO";
904                         case DT_MIPS_SYMTABNO:
905                                 return "MIPS_SYMTABNO";
906                         case DT_MIPS_UNREFEXTNO:
907                                 return "MIPS_UNREFEXTNO";
908                         case DT_MIPS_GOTSYM:
909                                 return "MIPS_GOTSYM";
910                         case DT_MIPS_HIPAGENO:
911                                 return "MIPS_HIPAGENO";
912                         case DT_MIPS_RLD_MAP:
913                                 return "MIPS_RLD_MAP";
914                         case DT_MIPS_DELTA_CLASS:
915                                 return "MIPS_DELTA_CLASS";
916                         case DT_MIPS_DELTA_CLASS_NO:
917                                 return "MIPS_DELTA_CLASS_NO";
918                         case DT_MIPS_DELTA_INSTANCE:
919                                 return "MIPS_DELTA_INSTANCE";
920                         case DT_MIPS_DELTA_INSTANCE_NO:
921                                 return "MIPS_DELTA_INSTANCE_NO";
922                         case DT_MIPS_DELTA_RELOC:
923                                 return "MIPS_DELTA_RELOC";
924                         case DT_MIPS_DELTA_RELOC_NO:
925                                 return "MIPS_DELTA_RELOC_NO";
926                         case DT_MIPS_DELTA_SYM:
927                                 return "MIPS_DELTA_SYM";
928                         case DT_MIPS_DELTA_SYM_NO:
929                                 return "MIPS_DELTA_SYM_NO";
930                         case DT_MIPS_DELTA_CLASSSYM:
931                                 return "MIPS_DELTA_CLASSSYM";
932                         case DT_MIPS_DELTA_CLASSSYM_NO:
933                                 return "MIPS_DELTA_CLASSSYM_NO";
934                         case DT_MIPS_CXX_FLAGS:
935                                 return "MIPS_CXX_FLAGS";
936                         case DT_MIPS_PIXIE_INIT:
937                                 return "MIPS_PIXIE_INIT";
938                         case DT_MIPS_SYMBOL_LIB:
939                                 return "MIPS_SYMBOL_LIB";
940                         case DT_MIPS_LOCALPAGE_GOTIDX:
941                                 return "MIPS_LOCALPAGE_GOTIDX";
942                         case DT_MIPS_LOCAL_GOTIDX:
943                                 return "MIPS_LOCAL_GOTIDX";
944                         case DT_MIPS_HIDDEN_GOTIDX:
945                                 return "MIPS_HIDDEN_GOTIDX";
946                         case DT_MIPS_PROTECTED_GOTIDX:
947                                 return "MIPS_PROTECTED_GOTIDX";
948                         case DT_MIPS_OPTIONS:
949                                 return "MIPS_OPTIONS";
950                         case DT_MIPS_INTERFACE:
951                                 return "MIPS_INTERFACE";
952                         case DT_MIPS_DYNSTR_ALIGN:
953                                 return "MIPS_DYNSTR_ALIGN";
954                         case DT_MIPS_INTERFACE_SIZE:
955                                 return "MIPS_INTERFACE_SIZE";
956                         case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
957                                 return "MIPS_RLD_TEXT_RESOLVE_ADDR";
958                         case DT_MIPS_PERF_SUFFIX:
959                                 return "MIPS_PERF_SUFFIX";
960                         case DT_MIPS_COMPACT_SIZE:
961                                 return "MIPS_COMPACT_SIZE";
962                         case DT_MIPS_GP_VALUE:
963                                 return "MIPS_GP_VALUE";
964                         case DT_MIPS_AUX_DYNAMIC:
965                                 return "MIPS_AUX_DYNAMIC";
966                         case DT_MIPS_PLTGOT:
967                                 return "MIPS_PLTGOT";
968                         case DT_MIPS_RLD_OBJ_UPDATE:
969                                 return "MIPS_RLD_OBJ_UPDATE";
970                         case DT_MIPS_RWPLT:
971                                 return "MIPS_RWPLT";
972                         default:
973                                 break;
974                         }
975                         break;
976                 case EM_SPARC:
977                 case EM_SPARC32PLUS:
978                 case EM_SPARCV9:
979                         switch (dtype) {
980                         case DT_SPARC_REGISTER:
981                                 return "DT_SPARC_REGISTER";
982                         default:
983                                 break;
984                         }
985                         break;
986                 default:
987                         break;
988                 }
989         }
990
991         snprintf(s_dtype, sizeof(s_dtype), "<unknown: %#x>", dtype);
992         return (s_dtype);
993 }
994
995 static const char *
996 st_bind(unsigned int sbind)
997 {
998         static char s_sbind[32];
999
1000         switch (sbind) {
1001         case STB_LOCAL: return "LOCAL";
1002         case STB_GLOBAL: return "GLOBAL";
1003         case STB_WEAK: return "WEAK";
1004         case STB_GNU_UNIQUE: return "UNIQUE";
1005         default:
1006                 if (sbind >= STB_LOOS && sbind <= STB_HIOS)
1007                         return "OS";
1008                 else if (sbind >= STB_LOPROC && sbind <= STB_HIPROC)
1009                         return "PROC";
1010                 else
1011                         snprintf(s_sbind, sizeof(s_sbind), "<unknown: %#x>",
1012                             sbind);
1013                 return (s_sbind);
1014         }
1015 }
1016
1017 static const char *
1018 st_type(unsigned int mach, unsigned int os, unsigned int stype)
1019 {
1020         static char s_stype[32];
1021
1022         switch (stype) {
1023         case STT_NOTYPE: return "NOTYPE";
1024         case STT_OBJECT: return "OBJECT";
1025         case STT_FUNC: return "FUNC";
1026         case STT_SECTION: return "SECTION";
1027         case STT_FILE: return "FILE";
1028         case STT_COMMON: return "COMMON";
1029         case STT_TLS: return "TLS";
1030         default:
1031                 if (stype >= STT_LOOS && stype <= STT_HIOS) {
1032                         if ((os == ELFOSABI_GNU || os == ELFOSABI_FREEBSD) &&
1033                             stype == STT_GNU_IFUNC)
1034                                 return "IFUNC";
1035                         snprintf(s_stype, sizeof(s_stype), "OS+%#x",
1036                             stype - STT_LOOS);
1037                 } else if (stype >= STT_LOPROC && stype <= STT_HIPROC) {
1038                         if (mach == EM_SPARCV9 && stype == STT_SPARC_REGISTER)
1039                                 return "REGISTER";
1040                         snprintf(s_stype, sizeof(s_stype), "PROC+%#x",
1041                             stype - STT_LOPROC);
1042                 } else
1043                         snprintf(s_stype, sizeof(s_stype), "<unknown: %#x>",
1044                             stype);
1045                 return (s_stype);
1046         }
1047 }
1048
1049 static const char *
1050 st_vis(unsigned int svis)
1051 {
1052         static char s_svis[32];
1053
1054         switch(svis) {
1055         case STV_DEFAULT: return "DEFAULT";
1056         case STV_INTERNAL: return "INTERNAL";
1057         case STV_HIDDEN: return "HIDDEN";
1058         case STV_PROTECTED: return "PROTECTED";
1059         default:
1060                 snprintf(s_svis, sizeof(s_svis), "<unknown: %#x>", svis);
1061                 return (s_svis);
1062         }
1063 }
1064
1065 static const char *
1066 st_shndx(unsigned int shndx)
1067 {
1068         static char s_shndx[32];
1069
1070         switch (shndx) {
1071         case SHN_UNDEF: return "UND";
1072         case SHN_ABS: return "ABS";
1073         case SHN_COMMON: return "COM";
1074         default:
1075                 if (shndx >= SHN_LOPROC && shndx <= SHN_HIPROC)
1076                         return "PRC";
1077                 else if (shndx >= SHN_LOOS && shndx <= SHN_HIOS)
1078                         return "OS";
1079                 else
1080                         snprintf(s_shndx, sizeof(s_shndx), "%u", shndx);
1081                 return (s_shndx);
1082         }
1083 }
1084
1085 static struct {
1086         const char *ln;
1087         char sn;
1088         int value;
1089 } section_flag[] = {
1090         {"WRITE", 'W', SHF_WRITE},
1091         {"ALLOC", 'A', SHF_ALLOC},
1092         {"EXEC", 'X', SHF_EXECINSTR},
1093         {"MERGE", 'M', SHF_MERGE},
1094         {"STRINGS", 'S', SHF_STRINGS},
1095         {"INFO LINK", 'I', SHF_INFO_LINK},
1096         {"OS NONCONF", 'O', SHF_OS_NONCONFORMING},
1097         {"GROUP", 'G', SHF_GROUP},
1098         {"TLS", 'T', SHF_TLS},
1099         {"COMPRESSED", 'C', SHF_COMPRESSED},
1100         {NULL, 0, 0}
1101 };
1102
1103 static const char *
1104 note_type(const char *name, unsigned int et, unsigned int nt)
1105 {
1106         if ((strcmp(name, "CORE") == 0 || strcmp(name, "LINUX") == 0) &&
1107             et == ET_CORE)
1108                 return note_type_linux_core(nt);
1109         else if (strcmp(name, "FreeBSD") == 0)
1110                 if (et == ET_CORE)
1111                         return note_type_freebsd_core(nt);
1112                 else
1113                         return note_type_freebsd(nt);
1114         else if (strcmp(name, "GNU") == 0 && et != ET_CORE)
1115                 return note_type_gnu(nt);
1116         else if (strcmp(name, "NetBSD") == 0 && et != ET_CORE)
1117                 return note_type_netbsd(nt);
1118         else if (strcmp(name, "OpenBSD") == 0 && et != ET_CORE)
1119                 return note_type_openbsd(nt);
1120         else if (strcmp(name, "Xen") == 0 && et != ET_CORE)
1121                 return note_type_xen(nt);
1122         return note_type_unknown(nt);
1123 }
1124
1125 static const char *
1126 note_type_freebsd(unsigned int nt)
1127 {
1128         switch (nt) {
1129         case 1: return "NT_FREEBSD_ABI_TAG";
1130         case 2: return "NT_FREEBSD_NOINIT_TAG";
1131         case 3: return "NT_FREEBSD_ARCH_TAG";
1132         case 4: return "NT_FREEBSD_FEATURE_CTL";
1133         default: return (note_type_unknown(nt));
1134         }
1135 }
1136
1137 static const char *
1138 note_type_freebsd_core(unsigned int nt)
1139 {
1140         switch (nt) {
1141         case 1: return "NT_PRSTATUS";
1142         case 2: return "NT_FPREGSET";
1143         case 3: return "NT_PRPSINFO";
1144         case 7: return "NT_THRMISC";
1145         case 8: return "NT_PROCSTAT_PROC";
1146         case 9: return "NT_PROCSTAT_FILES";
1147         case 10: return "NT_PROCSTAT_VMMAP";
1148         case 11: return "NT_PROCSTAT_GROUPS";
1149         case 12: return "NT_PROCSTAT_UMASK";
1150         case 13: return "NT_PROCSTAT_RLIMIT";
1151         case 14: return "NT_PROCSTAT_OSREL";
1152         case 15: return "NT_PROCSTAT_PSSTRINGS";
1153         case 16: return "NT_PROCSTAT_AUXV";
1154         case 17: return "NT_PTLWPINFO";
1155         case 0x202: return "NT_X86_XSTATE (x86 XSAVE extended state)";
1156         case 0x400: return "NT_ARM_VFP (arm VFP registers)";
1157         default: return (note_type_unknown(nt));
1158         }
1159 }
1160
1161 static const char *
1162 note_type_linux_core(unsigned int nt)
1163 {
1164         switch (nt) {
1165         case 1: return "NT_PRSTATUS (Process status)";
1166         case 2: return "NT_FPREGSET (Floating point information)";
1167         case 3: return "NT_PRPSINFO (Process information)";
1168         case 4: return "NT_TASKSTRUCT (Task structure)";
1169         case 6: return "NT_AUXV (Auxiliary vector)";
1170         case 10: return "NT_PSTATUS (Linux process status)";
1171         case 12: return "NT_FPREGS (Linux floating point regset)";
1172         case 13: return "NT_PSINFO (Linux process information)";
1173         case 16: return "NT_LWPSTATUS (Linux lwpstatus_t type)";
1174         case 17: return "NT_LWPSINFO (Linux lwpinfo_t type)";
1175         case 18: return "NT_WIN32PSTATUS (win32_pstatus structure)";
1176         case 0x100: return "NT_PPC_VMX (ppc Altivec registers)";
1177         case 0x102: return "NT_PPC_VSX (ppc VSX registers)";
1178         case 0x202: return "NT_X86_XSTATE (x86 XSAVE extended state)";
1179         case 0x300: return "NT_S390_HIGH_GPRS (s390 upper register halves)";
1180         case 0x301: return "NT_S390_TIMER (s390 timer register)";
1181         case 0x302: return "NT_S390_TODCMP (s390 TOD comparator register)";
1182         case 0x303: return "NT_S390_TODPREG (s390 TOD programmable register)";
1183         case 0x304: return "NT_S390_CTRS (s390 control registers)";
1184         case 0x305: return "NT_S390_PREFIX (s390 prefix register)";
1185         case 0x400: return "NT_ARM_VFP (arm VFP registers)";
1186         case 0x46494c45UL: return "NT_FILE (mapped files)";
1187         case 0x46E62B7FUL: return "NT_PRXFPREG (Linux user_xfpregs structure)";
1188         case 0x53494749UL: return "NT_SIGINFO (siginfo_t data)";
1189         default: return (note_type_unknown(nt));
1190         }
1191 }
1192
1193 static const char *
1194 note_type_gnu(unsigned int nt)
1195 {
1196         switch (nt) {
1197         case 1: return "NT_GNU_ABI_TAG";
1198         case 2: return "NT_GNU_HWCAP (Hardware capabilities)";
1199         case 3: return "NT_GNU_BUILD_ID (Build id set by ld(1))";
1200         case 4: return "NT_GNU_GOLD_VERSION (GNU gold version)";
1201         case 5: return "NT_GNU_PROPERTY_TYPE_0";
1202         default: return (note_type_unknown(nt));
1203         }
1204 }
1205
1206 static const char *
1207 note_type_netbsd(unsigned int nt)
1208 {
1209         switch (nt) {
1210         case 1: return "NT_NETBSD_IDENT";
1211         default: return (note_type_unknown(nt));
1212         }
1213 }
1214
1215 static const char *
1216 note_type_openbsd(unsigned int nt)
1217 {
1218         switch (nt) {
1219         case 1: return "NT_OPENBSD_IDENT";
1220         default: return (note_type_unknown(nt));
1221         }
1222 }
1223
1224 static const char *
1225 note_type_unknown(unsigned int nt)
1226 {
1227         static char s_nt[32];
1228
1229         snprintf(s_nt, sizeof(s_nt),
1230             nt >= 0x100 ? "<unknown: 0x%x>" : "<unknown: %u>", nt);
1231         return (s_nt);
1232 }
1233
1234 static const char *
1235 note_type_xen(unsigned int nt)
1236 {
1237         switch (nt) {
1238         case 0: return "XEN_ELFNOTE_INFO";
1239         case 1: return "XEN_ELFNOTE_ENTRY";
1240         case 2: return "XEN_ELFNOTE_HYPERCALL_PAGE";
1241         case 3: return "XEN_ELFNOTE_VIRT_BASE";
1242         case 4: return "XEN_ELFNOTE_PADDR_OFFSET";
1243         case 5: return "XEN_ELFNOTE_XEN_VERSION";
1244         case 6: return "XEN_ELFNOTE_GUEST_OS";
1245         case 7: return "XEN_ELFNOTE_GUEST_VERSION";
1246         case 8: return "XEN_ELFNOTE_LOADER";
1247         case 9: return "XEN_ELFNOTE_PAE_MODE";
1248         case 10: return "XEN_ELFNOTE_FEATURES";
1249         case 11: return "XEN_ELFNOTE_BSD_SYMTAB";
1250         case 12: return "XEN_ELFNOTE_HV_START_LOW";
1251         case 13: return "XEN_ELFNOTE_L1_MFN_VALID";
1252         case 14: return "XEN_ELFNOTE_SUSPEND_CANCEL";
1253         case 15: return "XEN_ELFNOTE_INIT_P2M";
1254         case 16: return "XEN_ELFNOTE_MOD_START_PFN";
1255         case 17: return "XEN_ELFNOTE_SUPPORTED_FEATURES";
1256         default: return (note_type_unknown(nt));
1257         }
1258 }
1259
1260 static struct {
1261         const char *name;
1262         int value;
1263 } l_flag[] = {
1264         {"EXACT_MATCH", LL_EXACT_MATCH},
1265         {"IGNORE_INT_VER", LL_IGNORE_INT_VER},
1266         {"REQUIRE_MINOR", LL_REQUIRE_MINOR},
1267         {"EXPORTS", LL_EXPORTS},
1268         {"DELAY_LOAD", LL_DELAY_LOAD},
1269         {"DELTA", LL_DELTA},
1270         {NULL, 0}
1271 };
1272
1273 static struct mips_option mips_exceptions_option[] = {
1274         {OEX_PAGE0, "PAGE0"},
1275         {OEX_SMM, "SMM"},
1276         {OEX_PRECISEFP, "PRECISEFP"},
1277         {OEX_DISMISS, "DISMISS"},
1278         {0, NULL}
1279 };
1280
1281 static struct mips_option mips_pad_option[] = {
1282         {OPAD_PREFIX, "PREFIX"},
1283         {OPAD_POSTFIX, "POSTFIX"},
1284         {OPAD_SYMBOL, "SYMBOL"},
1285         {0, NULL}
1286 };
1287
1288 static struct mips_option mips_hwpatch_option[] = {
1289         {OHW_R4KEOP, "R4KEOP"},
1290         {OHW_R8KPFETCH, "R8KPFETCH"},
1291         {OHW_R5KEOP, "R5KEOP"},
1292         {OHW_R5KCVTL, "R5KCVTL"},
1293         {0, NULL}
1294 };
1295
1296 static struct mips_option mips_hwa_option[] = {
1297         {OHWA0_R4KEOP_CHECKED, "R4KEOP_CHECKED"},
1298         {OHWA0_R4KEOP_CLEAN, "R4KEOP_CLEAN"},
1299         {0, NULL}
1300 };
1301
1302 static struct mips_option mips_hwo_option[] = {
1303         {OHWO0_FIXADE, "FIXADE"},
1304         {0, NULL}
1305 };
1306
1307 static const char *
1308 option_kind(uint8_t kind)
1309 {
1310         static char s_kind[32];
1311
1312         switch (kind) {
1313         case ODK_NULL: return "NULL";
1314         case ODK_REGINFO: return "REGINFO";
1315         case ODK_EXCEPTIONS: return "EXCEPTIONS";
1316         case ODK_PAD: return "PAD";
1317         case ODK_HWPATCH: return "HWPATCH";
1318         case ODK_FILL: return "FILL";
1319         case ODK_TAGS: return "TAGS";
1320         case ODK_HWAND: return "HWAND";
1321         case ODK_HWOR: return "HWOR";
1322         case ODK_GP_GROUP: return "GP_GROUP";
1323         case ODK_IDENT: return "IDENT";
1324         default:
1325                 snprintf(s_kind, sizeof(s_kind), "<unknown: %u>", kind);
1326                 return (s_kind);
1327         }
1328 }
1329
1330 static const char *
1331 top_tag(unsigned int tag)
1332 {
1333         static char s_top_tag[32];
1334
1335         switch (tag) {
1336         case 1: return "File Attributes";
1337         case 2: return "Section Attributes";
1338         case 3: return "Symbol Attributes";
1339         default:
1340                 snprintf(s_top_tag, sizeof(s_top_tag), "Unknown tag: %u", tag);
1341                 return (s_top_tag);
1342         }
1343 }
1344
1345 static const char *
1346 aeabi_cpu_arch(uint64_t arch)
1347 {
1348         static char s_cpu_arch[32];
1349
1350         switch (arch) {
1351         case 0: return "Pre-V4";
1352         case 1: return "ARM v4";
1353         case 2: return "ARM v4T";
1354         case 3: return "ARM v5T";
1355         case 4: return "ARM v5TE";
1356         case 5: return "ARM v5TEJ";
1357         case 6: return "ARM v6";
1358         case 7: return "ARM v6KZ";
1359         case 8: return "ARM v6T2";
1360         case 9: return "ARM v6K";
1361         case 10: return "ARM v7";
1362         case 11: return "ARM v6-M";
1363         case 12: return "ARM v6S-M";
1364         case 13: return "ARM v7E-M";
1365         default:
1366                 snprintf(s_cpu_arch, sizeof(s_cpu_arch),
1367                     "Unknown (%ju)", (uintmax_t) arch);
1368                 return (s_cpu_arch);
1369         }
1370 }
1371
1372 static const char *
1373 aeabi_cpu_arch_profile(uint64_t pf)
1374 {
1375         static char s_arch_profile[32];
1376
1377         switch (pf) {
1378         case 0:
1379                 return "Not applicable";
1380         case 0x41:              /* 'A' */
1381                 return "Application Profile";
1382         case 0x52:              /* 'R' */
1383                 return "Real-Time Profile";
1384         case 0x4D:              /* 'M' */
1385                 return "Microcontroller Profile";
1386         case 0x53:              /* 'S' */
1387                 return "Application or Real-Time Profile";
1388         default:
1389                 snprintf(s_arch_profile, sizeof(s_arch_profile),
1390                     "Unknown (%ju)\n", (uintmax_t) pf);
1391                 return (s_arch_profile);
1392         }
1393 }
1394
1395 static const char *
1396 aeabi_arm_isa(uint64_t ai)
1397 {
1398         static char s_ai[32];
1399
1400         switch (ai) {
1401         case 0: return "No";
1402         case 1: return "Yes";
1403         default:
1404                 snprintf(s_ai, sizeof(s_ai), "Unknown (%ju)\n",
1405                     (uintmax_t) ai);
1406                 return (s_ai);
1407         }
1408 }
1409
1410 static const char *
1411 aeabi_thumb_isa(uint64_t ti)
1412 {
1413         static char s_ti[32];
1414
1415         switch (ti) {
1416         case 0: return "No";
1417         case 1: return "16-bit Thumb";
1418         case 2: return "32-bit Thumb";
1419         default:
1420                 snprintf(s_ti, sizeof(s_ti), "Unknown (%ju)\n",
1421                     (uintmax_t) ti);
1422                 return (s_ti);
1423         }
1424 }
1425
1426 static const char *
1427 aeabi_fp_arch(uint64_t fp)
1428 {
1429         static char s_fp_arch[32];
1430
1431         switch (fp) {
1432         case 0: return "No";
1433         case 1: return "VFPv1";
1434         case 2: return "VFPv2";
1435         case 3: return "VFPv3";
1436         case 4: return "VFPv3-D16";
1437         case 5: return "VFPv4";
1438         case 6: return "VFPv4-D16";
1439         default:
1440                 snprintf(s_fp_arch, sizeof(s_fp_arch), "Unknown (%ju)",
1441                     (uintmax_t) fp);
1442                 return (s_fp_arch);
1443         }
1444 }
1445
1446 static const char *
1447 aeabi_wmmx_arch(uint64_t wmmx)
1448 {
1449         static char s_wmmx[32];
1450
1451         switch (wmmx) {
1452         case 0: return "No";
1453         case 1: return "WMMXv1";
1454         case 2: return "WMMXv2";
1455         default:
1456                 snprintf(s_wmmx, sizeof(s_wmmx), "Unknown (%ju)",
1457                     (uintmax_t) wmmx);
1458                 return (s_wmmx);
1459         }
1460 }
1461
1462 static const char *
1463 aeabi_adv_simd_arch(uint64_t simd)
1464 {
1465         static char s_simd[32];
1466
1467         switch (simd) {
1468         case 0: return "No";
1469         case 1: return "NEONv1";
1470         case 2: return "NEONv2";
1471         default:
1472                 snprintf(s_simd, sizeof(s_simd), "Unknown (%ju)",
1473                     (uintmax_t) simd);
1474                 return (s_simd);
1475         }
1476 }
1477
1478 static const char *
1479 aeabi_pcs_config(uint64_t pcs)
1480 {
1481         static char s_pcs[32];
1482
1483         switch (pcs) {
1484         case 0: return "None";
1485         case 1: return "Bare platform";
1486         case 2: return "Linux";
1487         case 3: return "Linux DSO";
1488         case 4: return "Palm OS 2004";
1489         case 5: return "Palm OS (future)";
1490         case 6: return "Symbian OS 2004";
1491         case 7: return "Symbian OS (future)";
1492         default:
1493                 snprintf(s_pcs, sizeof(s_pcs), "Unknown (%ju)",
1494                     (uintmax_t) pcs);
1495                 return (s_pcs);
1496         }
1497 }
1498
1499 static const char *
1500 aeabi_pcs_r9(uint64_t r9)
1501 {
1502         static char s_r9[32];
1503
1504         switch (r9) {
1505         case 0: return "V6";
1506         case 1: return "SB";
1507         case 2: return "TLS pointer";
1508         case 3: return "Unused";
1509         default:
1510                 snprintf(s_r9, sizeof(s_r9), "Unknown (%ju)", (uintmax_t) r9);
1511                 return (s_r9);
1512         }
1513 }
1514
1515 static const char *
1516 aeabi_pcs_rw(uint64_t rw)
1517 {
1518         static char s_rw[32];
1519
1520         switch (rw) {
1521         case 0: return "Absolute";
1522         case 1: return "PC-relative";
1523         case 2: return "SB-relative";
1524         case 3: return "None";
1525         default:
1526                 snprintf(s_rw, sizeof(s_rw), "Unknown (%ju)", (uintmax_t) rw);
1527                 return (s_rw);
1528         }
1529 }
1530
1531 static const char *
1532 aeabi_pcs_ro(uint64_t ro)
1533 {
1534         static char s_ro[32];
1535
1536         switch (ro) {
1537         case 0: return "Absolute";
1538         case 1: return "PC-relative";
1539         case 2: return "None";
1540         default:
1541                 snprintf(s_ro, sizeof(s_ro), "Unknown (%ju)", (uintmax_t) ro);
1542                 return (s_ro);
1543         }
1544 }
1545
1546 static const char *
1547 aeabi_pcs_got(uint64_t got)
1548 {
1549         static char s_got[32];
1550
1551         switch (got) {
1552         case 0: return "None";
1553         case 1: return "direct";
1554         case 2: return "indirect via GOT";
1555         default:
1556                 snprintf(s_got, sizeof(s_got), "Unknown (%ju)",
1557                     (uintmax_t) got);
1558                 return (s_got);
1559         }
1560 }
1561
1562 static const char *
1563 aeabi_pcs_wchar_t(uint64_t wt)
1564 {
1565         static char s_wt[32];
1566
1567         switch (wt) {
1568         case 0: return "None";
1569         case 2: return "wchar_t size 2";
1570         case 4: return "wchar_t size 4";
1571         default:
1572                 snprintf(s_wt, sizeof(s_wt), "Unknown (%ju)", (uintmax_t) wt);
1573                 return (s_wt);
1574         }
1575 }
1576
1577 static const char *
1578 aeabi_enum_size(uint64_t es)
1579 {
1580         static char s_es[32];
1581
1582         switch (es) {
1583         case 0: return "None";
1584         case 1: return "smallest";
1585         case 2: return "32-bit";
1586         case 3: return "visible 32-bit";
1587         default:
1588                 snprintf(s_es, sizeof(s_es), "Unknown (%ju)", (uintmax_t) es);
1589                 return (s_es);
1590         }
1591 }
1592
1593 static const char *
1594 aeabi_align_needed(uint64_t an)
1595 {
1596         static char s_align_n[64];
1597
1598         switch (an) {
1599         case 0: return "No";
1600         case 1: return "8-byte align";
1601         case 2: return "4-byte align";
1602         case 3: return "Reserved";
1603         default:
1604                 if (an >= 4 && an <= 12)
1605                         snprintf(s_align_n, sizeof(s_align_n), "8-byte align"
1606                             " and up to 2^%ju-byte extended align",
1607                             (uintmax_t) an);
1608                 else
1609                         snprintf(s_align_n, sizeof(s_align_n), "Unknown (%ju)",
1610                             (uintmax_t) an);
1611                 return (s_align_n);
1612         }
1613 }
1614
1615 static const char *
1616 aeabi_align_preserved(uint64_t ap)
1617 {
1618         static char s_align_p[128];
1619
1620         switch (ap) {
1621         case 0: return "No";
1622         case 1: return "8-byte align";
1623         case 2: return "8-byte align and SP % 8 == 0";
1624         case 3: return "Reserved";
1625         default:
1626                 if (ap >= 4 && ap <= 12)
1627                         snprintf(s_align_p, sizeof(s_align_p), "8-byte align"
1628                             " and SP %% 8 == 0 and up to 2^%ju-byte extended"
1629                             " align", (uintmax_t) ap);
1630                 else
1631                         snprintf(s_align_p, sizeof(s_align_p), "Unknown (%ju)",
1632                             (uintmax_t) ap);
1633                 return (s_align_p);
1634         }
1635 }
1636
1637 static const char *
1638 aeabi_fp_rounding(uint64_t fr)
1639 {
1640         static char s_fp_r[32];
1641
1642         switch (fr) {
1643         case 0: return "Unused";
1644         case 1: return "Needed";
1645         default:
1646                 snprintf(s_fp_r, sizeof(s_fp_r), "Unknown (%ju)",
1647                     (uintmax_t) fr);
1648                 return (s_fp_r);
1649         }
1650 }
1651
1652 static const char *
1653 aeabi_fp_denormal(uint64_t fd)
1654 {
1655         static char s_fp_d[32];
1656
1657         switch (fd) {
1658         case 0: return "Unused";
1659         case 1: return "Needed";
1660         case 2: return "Sign Only";
1661         default:
1662                 snprintf(s_fp_d, sizeof(s_fp_d), "Unknown (%ju)",
1663                     (uintmax_t) fd);
1664                 return (s_fp_d);
1665         }
1666 }
1667
1668 static const char *
1669 aeabi_fp_exceptions(uint64_t fe)
1670 {
1671         static char s_fp_e[32];
1672
1673         switch (fe) {
1674         case 0: return "Unused";
1675         case 1: return "Needed";
1676         default:
1677                 snprintf(s_fp_e, sizeof(s_fp_e), "Unknown (%ju)",
1678                     (uintmax_t) fe);
1679                 return (s_fp_e);
1680         }
1681 }
1682
1683 static const char *
1684 aeabi_fp_user_exceptions(uint64_t fu)
1685 {
1686         static char s_fp_u[32];
1687
1688         switch (fu) {
1689         case 0: return "Unused";
1690         case 1: return "Needed";
1691         default:
1692                 snprintf(s_fp_u, sizeof(s_fp_u), "Unknown (%ju)",
1693                     (uintmax_t) fu);
1694                 return (s_fp_u);
1695         }
1696 }
1697
1698 static const char *
1699 aeabi_fp_number_model(uint64_t fn)
1700 {
1701         static char s_fp_n[32];
1702
1703         switch (fn) {
1704         case 0: return "Unused";
1705         case 1: return "IEEE 754 normal";
1706         case 2: return "RTABI";
1707         case 3: return "IEEE 754";
1708         default:
1709                 snprintf(s_fp_n, sizeof(s_fp_n), "Unknown (%ju)",
1710                     (uintmax_t) fn);
1711                 return (s_fp_n);
1712         }
1713 }
1714
1715 static const char *
1716 aeabi_fp_16bit_format(uint64_t fp16)
1717 {
1718         static char s_fp_16[64];
1719
1720         switch (fp16) {
1721         case 0: return "None";
1722         case 1: return "IEEE 754";
1723         case 2: return "VFPv3/Advanced SIMD (alternative format)";
1724         default:
1725                 snprintf(s_fp_16, sizeof(s_fp_16), "Unknown (%ju)",
1726                     (uintmax_t) fp16);
1727                 return (s_fp_16);
1728         }
1729 }
1730
1731 static const char *
1732 aeabi_mpext(uint64_t mp)
1733 {
1734         static char s_mp[32];
1735
1736         switch (mp) {
1737         case 0: return "Not allowed";
1738         case 1: return "Allowed";
1739         default:
1740                 snprintf(s_mp, sizeof(s_mp), "Unknown (%ju)",
1741                     (uintmax_t) mp);
1742                 return (s_mp);
1743         }
1744 }
1745
1746 static const char *
1747 aeabi_div(uint64_t du)
1748 {
1749         static char s_du[32];
1750
1751         switch (du) {
1752         case 0: return "Yes (V7-R/V7-M)";
1753         case 1: return "No";
1754         case 2: return "Yes (V7-A)";
1755         default:
1756                 snprintf(s_du, sizeof(s_du), "Unknown (%ju)",
1757                     (uintmax_t) du);
1758                 return (s_du);
1759         }
1760 }
1761
1762 static const char *
1763 aeabi_t2ee(uint64_t t2ee)
1764 {
1765         static char s_t2ee[32];
1766
1767         switch (t2ee) {
1768         case 0: return "Not allowed";
1769         case 1: return "Allowed";
1770         default:
1771                 snprintf(s_t2ee, sizeof(s_t2ee), "Unknown(%ju)",
1772                     (uintmax_t) t2ee);
1773                 return (s_t2ee);
1774         }
1775
1776 }
1777
1778 static const char *
1779 aeabi_hardfp(uint64_t hfp)
1780 {
1781         static char s_hfp[32];
1782
1783         switch (hfp) {
1784         case 0: return "Tag_FP_arch";
1785         case 1: return "only SP";
1786         case 2: return "only DP";
1787         case 3: return "both SP and DP";
1788         default:
1789                 snprintf(s_hfp, sizeof(s_hfp), "Unknown (%ju)",
1790                     (uintmax_t) hfp);
1791                 return (s_hfp);
1792         }
1793 }
1794
1795 static const char *
1796 aeabi_vfp_args(uint64_t va)
1797 {
1798         static char s_va[32];
1799
1800         switch (va) {
1801         case 0: return "AAPCS (base variant)";
1802         case 1: return "AAPCS (VFP variant)";
1803         case 2: return "toolchain-specific";
1804         default:
1805                 snprintf(s_va, sizeof(s_va), "Unknown (%ju)", (uintmax_t) va);
1806                 return (s_va);
1807         }
1808 }
1809
1810 static const char *
1811 aeabi_wmmx_args(uint64_t wa)
1812 {
1813         static char s_wa[32];
1814
1815         switch (wa) {
1816         case 0: return "AAPCS (base variant)";
1817         case 1: return "Intel WMMX";
1818         case 2: return "toolchain-specific";
1819         default:
1820                 snprintf(s_wa, sizeof(s_wa), "Unknown(%ju)", (uintmax_t) wa);
1821                 return (s_wa);
1822         }
1823 }
1824
1825 static const char *
1826 aeabi_unaligned_access(uint64_t ua)
1827 {
1828         static char s_ua[32];
1829
1830         switch (ua) {
1831         case 0: return "Not allowed";
1832         case 1: return "Allowed";
1833         default:
1834                 snprintf(s_ua, sizeof(s_ua), "Unknown(%ju)", (uintmax_t) ua);
1835                 return (s_ua);
1836         }
1837 }
1838
1839 static const char *
1840 aeabi_fp_hpext(uint64_t fh)
1841 {
1842         static char s_fh[32];
1843
1844         switch (fh) {
1845         case 0: return "Not allowed";
1846         case 1: return "Allowed";
1847         default:
1848                 snprintf(s_fh, sizeof(s_fh), "Unknown(%ju)", (uintmax_t) fh);
1849                 return (s_fh);
1850         }
1851 }
1852
1853 static const char *
1854 aeabi_optm_goal(uint64_t og)
1855 {
1856         static char s_og[32];
1857
1858         switch (og) {
1859         case 0: return "None";
1860         case 1: return "Speed";
1861         case 2: return "Speed aggressive";
1862         case 3: return "Space";
1863         case 4: return "Space aggressive";
1864         case 5: return "Debugging";
1865         case 6: return "Best Debugging";
1866         default:
1867                 snprintf(s_og, sizeof(s_og), "Unknown(%ju)", (uintmax_t) og);
1868                 return (s_og);
1869         }
1870 }
1871
1872 static const char *
1873 aeabi_fp_optm_goal(uint64_t fog)
1874 {
1875         static char s_fog[32];
1876
1877         switch (fog) {
1878         case 0: return "None";
1879         case 1: return "Speed";
1880         case 2: return "Speed aggressive";
1881         case 3: return "Space";
1882         case 4: return "Space aggressive";
1883         case 5: return "Accurary";
1884         case 6: return "Best Accurary";
1885         default:
1886                 snprintf(s_fog, sizeof(s_fog), "Unknown(%ju)",
1887                     (uintmax_t) fog);
1888                 return (s_fog);
1889         }
1890 }
1891
1892 static const char *
1893 aeabi_virtual(uint64_t vt)
1894 {
1895         static char s_virtual[64];
1896
1897         switch (vt) {
1898         case 0: return "No";
1899         case 1: return "TrustZone";
1900         case 2: return "Virtualization extension";
1901         case 3: return "TrustZone and virtualization extension";
1902         default:
1903                 snprintf(s_virtual, sizeof(s_virtual), "Unknown(%ju)",
1904                     (uintmax_t) vt);
1905                 return (s_virtual);
1906         }
1907 }
1908
1909 static struct {
1910         uint64_t tag;
1911         const char *s_tag;
1912         const char *(*get_desc)(uint64_t val);
1913 } aeabi_tags[] = {
1914         {4, "Tag_CPU_raw_name", NULL},
1915         {5, "Tag_CPU_name", NULL},
1916         {6, "Tag_CPU_arch", aeabi_cpu_arch},
1917         {7, "Tag_CPU_arch_profile", aeabi_cpu_arch_profile},
1918         {8, "Tag_ARM_ISA_use", aeabi_arm_isa},
1919         {9, "Tag_THUMB_ISA_use", aeabi_thumb_isa},
1920         {10, "Tag_FP_arch", aeabi_fp_arch},
1921         {11, "Tag_WMMX_arch", aeabi_wmmx_arch},
1922         {12, "Tag_Advanced_SIMD_arch", aeabi_adv_simd_arch},
1923         {13, "Tag_PCS_config", aeabi_pcs_config},
1924         {14, "Tag_ABI_PCS_R9_use", aeabi_pcs_r9},
1925         {15, "Tag_ABI_PCS_RW_data", aeabi_pcs_rw},
1926         {16, "Tag_ABI_PCS_RO_data", aeabi_pcs_ro},
1927         {17, "Tag_ABI_PCS_GOT_use", aeabi_pcs_got},
1928         {18, "Tag_ABI_PCS_wchar_t", aeabi_pcs_wchar_t},
1929         {19, "Tag_ABI_FP_rounding", aeabi_fp_rounding},
1930         {20, "Tag_ABI_FP_denormal", aeabi_fp_denormal},
1931         {21, "Tag_ABI_FP_exceptions", aeabi_fp_exceptions},
1932         {22, "Tag_ABI_FP_user_exceptions", aeabi_fp_user_exceptions},
1933         {23, "Tag_ABI_FP_number_model", aeabi_fp_number_model},
1934         {24, "Tag_ABI_align_needed", aeabi_align_needed},
1935         {25, "Tag_ABI_align_preserved", aeabi_align_preserved},
1936         {26, "Tag_ABI_enum_size", aeabi_enum_size},
1937         {27, "Tag_ABI_HardFP_use", aeabi_hardfp},
1938         {28, "Tag_ABI_VFP_args", aeabi_vfp_args},
1939         {29, "Tag_ABI_WMMX_args", aeabi_wmmx_args},
1940         {30, "Tag_ABI_optimization_goals", aeabi_optm_goal},
1941         {31, "Tag_ABI_FP_optimization_goals", aeabi_fp_optm_goal},
1942         {32, "Tag_compatibility", NULL},
1943         {34, "Tag_CPU_unaligned_access", aeabi_unaligned_access},
1944         {36, "Tag_FP_HP_extension", aeabi_fp_hpext},
1945         {38, "Tag_ABI_FP_16bit_format", aeabi_fp_16bit_format},
1946         {42, "Tag_MPextension_use", aeabi_mpext},
1947         {44, "Tag_DIV_use", aeabi_div},
1948         {64, "Tag_nodefaults", NULL},
1949         {65, "Tag_also_compatible_with", NULL},
1950         {66, "Tag_T2EE_use", aeabi_t2ee},
1951         {67, "Tag_conformance", NULL},
1952         {68, "Tag_Virtualization_use", aeabi_virtual},
1953         {70, "Tag_MPextension_use", aeabi_mpext},
1954 };
1955
1956 static const char *
1957 mips_abi_fp(uint64_t fp)
1958 {
1959         static char s_mips_abi_fp[64];
1960
1961         switch (fp) {
1962         case 0: return "N/A";
1963         case 1: return "Hard float (double precision)";
1964         case 2: return "Hard float (single precision)";
1965         case 3: return "Soft float";
1966         case 4: return "64-bit float (-mips32r2 -mfp64)";
1967         default:
1968                 snprintf(s_mips_abi_fp, sizeof(s_mips_abi_fp), "Unknown(%ju)",
1969                     (uintmax_t) fp);
1970                 return (s_mips_abi_fp);
1971         }
1972 }
1973
1974 static const char *
1975 ppc_abi_fp(uint64_t fp)
1976 {
1977         static char s_ppc_abi_fp[64];
1978
1979         switch (fp) {
1980         case 0: return "N/A";
1981         case 1: return "Hard float (double precision)";
1982         case 2: return "Soft float";
1983         case 3: return "Hard float (single precision)";
1984         default:
1985                 snprintf(s_ppc_abi_fp, sizeof(s_ppc_abi_fp), "Unknown(%ju)",
1986                     (uintmax_t) fp);
1987                 return (s_ppc_abi_fp);
1988         }
1989 }
1990
1991 static const char *
1992 ppc_abi_vector(uint64_t vec)
1993 {
1994         static char s_vec[64];
1995
1996         switch (vec) {
1997         case 0: return "N/A";
1998         case 1: return "Generic purpose registers";
1999         case 2: return "AltiVec registers";
2000         case 3: return "SPE registers";
2001         default:
2002                 snprintf(s_vec, sizeof(s_vec), "Unknown(%ju)", (uintmax_t) vec);
2003                 return (s_vec);
2004         }
2005 }
2006
2007 static const char *
2008 dwarf_reg(unsigned int mach, unsigned int reg)
2009 {
2010
2011         switch (mach) {
2012         case EM_386:
2013         case EM_IAMCU:
2014                 switch (reg) {
2015                 case 0: return "eax";
2016                 case 1: return "ecx";
2017                 case 2: return "edx";
2018                 case 3: return "ebx";
2019                 case 4: return "esp";
2020                 case 5: return "ebp";
2021                 case 6: return "esi";
2022                 case 7: return "edi";
2023                 case 8: return "eip";
2024                 case 9: return "eflags";
2025                 case 11: return "st0";
2026                 case 12: return "st1";
2027                 case 13: return "st2";
2028                 case 14: return "st3";
2029                 case 15: return "st4";
2030                 case 16: return "st5";
2031                 case 17: return "st6";
2032                 case 18: return "st7";
2033                 case 21: return "xmm0";
2034                 case 22: return "xmm1";
2035                 case 23: return "xmm2";
2036                 case 24: return "xmm3";
2037                 case 25: return "xmm4";
2038                 case 26: return "xmm5";
2039                 case 27: return "xmm6";
2040                 case 28: return "xmm7";
2041                 case 29: return "mm0";
2042                 case 30: return "mm1";
2043                 case 31: return "mm2";
2044                 case 32: return "mm3";
2045                 case 33: return "mm4";
2046                 case 34: return "mm5";
2047                 case 35: return "mm6";
2048                 case 36: return "mm7";
2049                 case 37: return "fcw";
2050                 case 38: return "fsw";
2051                 case 39: return "mxcsr";
2052                 case 40: return "es";
2053                 case 41: return "cs";
2054                 case 42: return "ss";
2055                 case 43: return "ds";
2056                 case 44: return "fs";
2057                 case 45: return "gs";
2058                 case 48: return "tr";
2059                 case 49: return "ldtr";
2060                 default: return (NULL);
2061                 }
2062         case EM_X86_64:
2063                 switch (reg) {
2064                 case 0: return "rax";
2065                 case 1: return "rdx";
2066                 case 2: return "rcx";
2067                 case 3: return "rbx";
2068                 case 4: return "rsi";
2069                 case 5: return "rdi";
2070                 case 6: return "rbp";
2071                 case 7: return "rsp";
2072                 case 16: return "rip";
2073                 case 17: return "xmm0";
2074                 case 18: return "xmm1";
2075                 case 19: return "xmm2";
2076                 case 20: return "xmm3";
2077                 case 21: return "xmm4";
2078                 case 22: return "xmm5";
2079                 case 23: return "xmm6";
2080                 case 24: return "xmm7";
2081                 case 25: return "xmm8";
2082                 case 26: return "xmm9";
2083                 case 27: return "xmm10";
2084                 case 28: return "xmm11";
2085                 case 29: return "xmm12";
2086                 case 30: return "xmm13";
2087                 case 31: return "xmm14";
2088                 case 32: return "xmm15";
2089                 case 33: return "st0";
2090                 case 34: return "st1";
2091                 case 35: return "st2";
2092                 case 36: return "st3";
2093                 case 37: return "st4";
2094                 case 38: return "st5";
2095                 case 39: return "st6";
2096                 case 40: return "st7";
2097                 case 41: return "mm0";
2098                 case 42: return "mm1";
2099                 case 43: return "mm2";
2100                 case 44: return "mm3";
2101                 case 45: return "mm4";
2102                 case 46: return "mm5";
2103                 case 47: return "mm6";
2104                 case 48: return "mm7";
2105                 case 49: return "rflags";
2106                 case 50: return "es";
2107                 case 51: return "cs";
2108                 case 52: return "ss";
2109                 case 53: return "ds";
2110                 case 54: return "fs";
2111                 case 55: return "gs";
2112                 case 58: return "fs.base";
2113                 case 59: return "gs.base";
2114                 case 62: return "tr";
2115                 case 63: return "ldtr";
2116                 case 64: return "mxcsr";
2117                 case 65: return "fcw";
2118                 case 66: return "fsw";
2119                 default: return (NULL);
2120                 }
2121         default:
2122                 return (NULL);
2123         }
2124 }
2125
2126 static void
2127 dump_ehdr(struct readelf *re)
2128 {
2129         size_t           phnum, shnum, shstrndx;
2130         int              i;
2131
2132         printf("ELF Header:\n");
2133
2134         /* e_ident[]. */
2135         printf("  Magic:   ");
2136         for (i = 0; i < EI_NIDENT; i++)
2137                 printf("%.2x ", re->ehdr.e_ident[i]);
2138         putchar('\n');
2139
2140         /* EI_CLASS. */
2141         printf("%-37s%s\n", "  Class:", elf_class(re->ehdr.e_ident[EI_CLASS]));
2142
2143         /* EI_DATA. */
2144         printf("%-37s%s\n", "  Data:", elf_endian(re->ehdr.e_ident[EI_DATA]));
2145
2146         /* EI_VERSION. */
2147         printf("%-37s%d %s\n", "  Version:", re->ehdr.e_ident[EI_VERSION],
2148             elf_ver(re->ehdr.e_ident[EI_VERSION]));
2149
2150         /* EI_OSABI. */
2151         printf("%-37s%s\n", "  OS/ABI:", elf_osabi(re->ehdr.e_ident[EI_OSABI]));
2152
2153         /* EI_ABIVERSION. */
2154         printf("%-37s%d\n", "  ABI Version:", re->ehdr.e_ident[EI_ABIVERSION]);
2155
2156         /* e_type. */
2157         printf("%-37s%s\n", "  Type:", elf_type(re->ehdr.e_type));
2158
2159         /* e_machine. */
2160         printf("%-37s%s\n", "  Machine:", elf_machine(re->ehdr.e_machine));
2161
2162         /* e_version. */
2163         printf("%-37s%#x\n", "  Version:", re->ehdr.e_version);
2164
2165         /* e_entry. */
2166         printf("%-37s%#jx\n", "  Entry point address:",
2167             (uintmax_t)re->ehdr.e_entry);
2168
2169         /* e_phoff. */
2170         printf("%-37s%ju (bytes into file)\n", "  Start of program headers:",
2171             (uintmax_t)re->ehdr.e_phoff);
2172
2173         /* e_shoff. */
2174         printf("%-37s%ju (bytes into file)\n", "  Start of section headers:",
2175             (uintmax_t)re->ehdr.e_shoff);
2176
2177         /* e_flags. */
2178         printf("%-37s%#x", "  Flags:", re->ehdr.e_flags);
2179         dump_eflags(re, re->ehdr.e_flags);
2180         putchar('\n');
2181
2182         /* e_ehsize. */
2183         printf("%-37s%u (bytes)\n", "  Size of this header:",
2184             re->ehdr.e_ehsize);
2185
2186         /* e_phentsize. */
2187         printf("%-37s%u (bytes)\n", "  Size of program headers:",
2188             re->ehdr.e_phentsize);
2189
2190         /* e_phnum. */
2191         printf("%-37s%u", "  Number of program headers:", re->ehdr.e_phnum);
2192         if (re->ehdr.e_phnum == PN_XNUM) {
2193                 /* Extended program header numbering is in use. */
2194                 if (elf_getphnum(re->elf, &phnum))
2195                         printf(" (%zu)", phnum);
2196         }
2197         putchar('\n');
2198
2199         /* e_shentsize. */
2200         printf("%-37s%u (bytes)\n", "  Size of section headers:",
2201             re->ehdr.e_shentsize);
2202
2203         /* e_shnum. */
2204         printf("%-37s%u", "  Number of section headers:", re->ehdr.e_shnum);
2205         if (re->ehdr.e_shnum == SHN_UNDEF) {
2206                 /* Extended section numbering is in use. */
2207                 if (elf_getshnum(re->elf, &shnum))
2208                         printf(" (%ju)", (uintmax_t)shnum);
2209         }
2210         putchar('\n');
2211
2212         /* e_shstrndx. */
2213         printf("%-37s%u", "  Section header string table index:",
2214             re->ehdr.e_shstrndx);
2215         if (re->ehdr.e_shstrndx == SHN_XINDEX) {
2216                 /* Extended section numbering is in use. */
2217                 if (elf_getshstrndx(re->elf, &shstrndx))
2218                         printf(" (%ju)", (uintmax_t)shstrndx);
2219         }
2220         putchar('\n');
2221 }
2222
2223 static void
2224 dump_eflags(struct readelf *re, uint64_t e_flags)
2225 {
2226         struct eflags_desc *edesc;
2227         int arm_eabi;
2228
2229         edesc = NULL;
2230         switch (re->ehdr.e_machine) {
2231         case EM_ARM:
2232                 arm_eabi = (e_flags & EF_ARM_EABIMASK) >> 24;
2233                 if (arm_eabi == 0)
2234                         printf(", GNU EABI");
2235                 else if (arm_eabi <= 5)
2236                         printf(", Version%d EABI", arm_eabi);
2237                 edesc = arm_eflags_desc;
2238                 break;
2239         case EM_MIPS:
2240         case EM_MIPS_RS3_LE:
2241                 switch ((e_flags & EF_MIPS_ARCH) >> 28) {
2242                 case 0: printf(", mips1"); break;
2243                 case 1: printf(", mips2"); break;
2244                 case 2: printf(", mips3"); break;
2245                 case 3: printf(", mips4"); break;
2246                 case 4: printf(", mips5"); break;
2247                 case 5: printf(", mips32"); break;
2248                 case 6: printf(", mips64"); break;
2249                 case 7: printf(", mips32r2"); break;
2250                 case 8: printf(", mips64r2"); break;
2251                 default: break;
2252                 }
2253                 switch ((e_flags & 0x00FF0000) >> 16) {
2254                 case 0x81: printf(", 3900"); break;
2255                 case 0x82: printf(", 4010"); break;
2256                 case 0x83: printf(", 4100"); break;
2257                 case 0x85: printf(", 4650"); break;
2258                 case 0x87: printf(", 4120"); break;
2259                 case 0x88: printf(", 4111"); break;
2260                 case 0x8a: printf(", sb1"); break;
2261                 case 0x8b: printf(", octeon"); break;
2262                 case 0x8c: printf(", xlr"); break;
2263                 case 0x91: printf(", 5400"); break;
2264                 case 0x98: printf(", 5500"); break;
2265                 case 0x99: printf(", 9000"); break;
2266                 case 0xa0: printf(", loongson-2e"); break;
2267                 case 0xa1: printf(", loongson-2f"); break;
2268                 default: break;
2269                 }
2270                 switch ((e_flags & 0x0000F000) >> 12) {
2271                 case 1: printf(", o32"); break;
2272                 case 2: printf(", o64"); break;
2273                 case 3: printf(", eabi32"); break;
2274                 case 4: printf(", eabi64"); break;
2275                 default: break;
2276                 }
2277                 edesc = mips_eflags_desc;
2278                 break;
2279         case EM_PPC:
2280         case EM_PPC64:
2281                 edesc = powerpc_eflags_desc;
2282                 break;
2283         case EM_SPARC:
2284         case EM_SPARC32PLUS:
2285         case EM_SPARCV9:
2286                 switch ((e_flags & EF_SPARCV9_MM)) {
2287                 case EF_SPARCV9_TSO: printf(", tso"); break;
2288                 case EF_SPARCV9_PSO: printf(", pso"); break;
2289                 case EF_SPARCV9_MM: printf(", rmo"); break;
2290                 default: break;
2291                 }
2292                 edesc = sparc_eflags_desc;
2293                 break;
2294         default:
2295                 break;
2296         }
2297
2298         if (edesc != NULL) {
2299                 while (edesc->desc != NULL) {
2300                         if (e_flags & edesc->flag)
2301                                 printf(", %s", edesc->desc);
2302                         edesc++;
2303                 }
2304         }
2305 }
2306
2307 static void
2308 dump_phdr(struct readelf *re)
2309 {
2310         const char      *rawfile;
2311         GElf_Phdr        phdr;
2312         size_t           phnum, size;
2313         int              i, j;
2314
2315 #define PH_HDR  "Type", "Offset", "VirtAddr", "PhysAddr", "FileSiz",    \
2316                 "MemSiz", "Flg", "Align"
2317 #define PH_CT   phdr_type(re->ehdr.e_machine, phdr.p_type),             \
2318                 (uintmax_t)phdr.p_offset, (uintmax_t)phdr.p_vaddr,      \
2319                 (uintmax_t)phdr.p_paddr, (uintmax_t)phdr.p_filesz,      \
2320                 (uintmax_t)phdr.p_memsz,                                \
2321                 phdr.p_flags & PF_R ? 'R' : ' ',                        \
2322                 phdr.p_flags & PF_W ? 'W' : ' ',                        \
2323                 phdr.p_flags & PF_X ? 'E' : ' ',                        \
2324                 (uintmax_t)phdr.p_align
2325
2326         if (elf_getphnum(re->elf, &phnum) == 0) {
2327                 warnx("elf_getphnum failed: %s", elf_errmsg(-1));
2328                 return;
2329         }
2330         if (phnum == 0) {
2331                 printf("\nThere are no program headers in this file.\n");
2332                 return;
2333         }
2334
2335         printf("\nElf file type is %s", elf_type(re->ehdr.e_type));
2336         printf("\nEntry point 0x%jx\n", (uintmax_t)re->ehdr.e_entry);
2337         printf("There are %ju program headers, starting at offset %ju\n",
2338             (uintmax_t)phnum, (uintmax_t)re->ehdr.e_phoff);
2339
2340         /* Dump program headers. */
2341         printf("\nProgram Headers:\n");
2342         if (re->ec == ELFCLASS32)
2343                 printf("  %-15s%-9s%-11s%-11s%-8s%-8s%-4s%s\n", PH_HDR);
2344         else if (re->options & RE_WW)
2345                 printf("  %-15s%-9s%-19s%-19s%-9s%-9s%-4s%s\n", PH_HDR);
2346         else
2347                 printf("  %-15s%-19s%-19s%s\n                 %-19s%-20s"
2348                     "%-7s%s\n", PH_HDR);
2349         for (i = 0; (size_t) i < phnum; i++) {
2350                 if (gelf_getphdr(re->elf, i, &phdr) != &phdr) {
2351                         warnx("gelf_getphdr failed: %s", elf_errmsg(-1));
2352                         continue;
2353                 }
2354                 /* TODO: Add arch-specific segment type dump. */
2355                 if (re->ec == ELFCLASS32)
2356                         printf("  %-14.14s 0x%6.6jx 0x%8.8jx 0x%8.8jx "
2357                             "0x%5.5jx 0x%5.5jx %c%c%c %#jx\n", PH_CT);
2358                 else if (re->options & RE_WW)
2359                         printf("  %-14.14s 0x%6.6jx 0x%16.16jx 0x%16.16jx "
2360                             "0x%6.6jx 0x%6.6jx %c%c%c %#jx\n", PH_CT);
2361                 else
2362                         printf("  %-14.14s 0x%16.16jx 0x%16.16jx 0x%16.16jx\n"
2363                             "                 0x%16.16jx 0x%16.16jx  %c%c%c"
2364                             "    %#jx\n", PH_CT);
2365                 if (phdr.p_type == PT_INTERP) {
2366                         if ((rawfile = elf_rawfile(re->elf, &size)) == NULL) {
2367                                 warnx("elf_rawfile failed: %s", elf_errmsg(-1));
2368                                 continue;
2369                         }
2370                         if (phdr.p_offset >= size) {
2371                                 warnx("invalid program header offset");
2372                                 continue;
2373                         }
2374                         printf("      [Requesting program interpreter: %s]\n",
2375                                 rawfile + phdr.p_offset);
2376                 }
2377         }
2378
2379         /* Dump section to segment mapping. */
2380         if (re->shnum == 0)
2381                 return;
2382         printf("\n Section to Segment mapping:\n");
2383         printf("  Segment Sections...\n");
2384         for (i = 0; (size_t)i < phnum; i++) {
2385                 if (gelf_getphdr(re->elf, i, &phdr) != &phdr) {
2386                         warnx("gelf_getphdr failed: %s", elf_errmsg(-1));
2387                         continue;
2388                 }
2389                 printf("   %2.2d     ", i);
2390                 /* skip NULL section. */
2391                 for (j = 1; (size_t)j < re->shnum; j++) {
2392                         if (re->sl[j].off < phdr.p_offset)
2393                                 continue;
2394                         if (re->sl[j].off + re->sl[j].sz >
2395                             phdr.p_offset + phdr.p_filesz &&
2396                             re->sl[j].type != SHT_NOBITS)
2397                                 continue;
2398                         if (re->sl[j].addr < phdr.p_vaddr ||
2399                             re->sl[j].addr + re->sl[j].sz >
2400                             phdr.p_vaddr + phdr.p_memsz)
2401                                 continue;
2402                         if (phdr.p_type == PT_TLS &&
2403                             (re->sl[j].flags & SHF_TLS) == 0)
2404                                 continue;
2405                         printf("%s ", re->sl[j].name);
2406                 }
2407                 printf("\n");
2408         }
2409 #undef  PH_HDR
2410 #undef  PH_CT
2411 }
2412
2413 static char *
2414 section_flags(struct readelf *re, struct section *s)
2415 {
2416 #define BUF_SZ 256
2417         static char     buf[BUF_SZ];
2418         int             i, p, nb;
2419
2420         p = 0;
2421         nb = re->ec == ELFCLASS32 ? 8 : 16;
2422         if (re->options & RE_T) {
2423                 snprintf(buf, BUF_SZ, "[%*.*jx]: ", nb, nb,
2424                     (uintmax_t)s->flags);
2425                 p += nb + 4;
2426         }
2427         for (i = 0; section_flag[i].ln != NULL; i++) {
2428                 if ((s->flags & section_flag[i].value) == 0)
2429                         continue;
2430                 if (re->options & RE_T) {
2431                         snprintf(&buf[p], BUF_SZ - p, "%s, ",
2432                             section_flag[i].ln);
2433                         p += strlen(section_flag[i].ln) + 2;
2434                 } else
2435                         buf[p++] = section_flag[i].sn;
2436         }
2437         if (re->options & RE_T && p > nb + 4)
2438                 p -= 2;
2439         buf[p] = '\0';
2440
2441         return (buf);
2442 }
2443
2444 static void
2445 dump_shdr(struct readelf *re)
2446 {
2447         struct section  *s;
2448         int              i;
2449
2450 #define S_HDR   "[Nr] Name", "Type", "Addr", "Off", "Size", "ES",       \
2451                 "Flg", "Lk", "Inf", "Al"
2452 #define S_HDRL  "[Nr] Name", "Type", "Address", "Offset", "Size",       \
2453                 "EntSize", "Flags", "Link", "Info", "Align"
2454 #define ST_HDR  "[Nr] Name", "Type", "Addr", "Off", "Size", "ES",       \
2455                 "Lk", "Inf", "Al", "Flags"
2456 #define ST_HDRL "[Nr] Name", "Type", "Address", "Offset", "Link",       \
2457                 "Size", "EntSize", "Info", "Align", "Flags"
2458 #define S_CT    i, s->name, section_type(re->ehdr.e_machine, s->type),  \
2459                 (uintmax_t)s->addr, (uintmax_t)s->off, (uintmax_t)s->sz,\
2460                 (uintmax_t)s->entsize, section_flags(re, s),            \
2461                 s->link, s->info, (uintmax_t)s->align
2462 #define ST_CT   i, s->name, section_type(re->ehdr.e_machine, s->type),  \
2463                 (uintmax_t)s->addr, (uintmax_t)s->off, (uintmax_t)s->sz,\
2464                 (uintmax_t)s->entsize, s->link, s->info,                \
2465                 (uintmax_t)s->align, section_flags(re, s)
2466 #define ST_CTL  i, s->name, section_type(re->ehdr.e_machine, s->type),  \
2467                 (uintmax_t)s->addr, (uintmax_t)s->off, s->link,         \
2468                 (uintmax_t)s->sz, (uintmax_t)s->entsize, s->info,       \
2469                 (uintmax_t)s->align, section_flags(re, s)
2470
2471         if (re->shnum == 0) {
2472                 printf("\nThere are no sections in this file.\n");
2473                 return;
2474         }
2475         printf("There are %ju section headers, starting at offset 0x%jx:\n",
2476             (uintmax_t)re->shnum, (uintmax_t)re->ehdr.e_shoff);
2477         printf("\nSection Headers:\n");
2478         if (re->ec == ELFCLASS32) {
2479                 if (re->options & RE_T)
2480                         printf("  %s\n       %-16s%-9s%-7s%-7s%-5s%-3s%-4s%s\n"
2481                             "%12s\n", ST_HDR);
2482                 else
2483                         printf("  %-23s%-16s%-9s%-7s%-7s%-3s%-4s%-3s%-4s%s\n",
2484                             S_HDR);
2485         } else if (re->options & RE_WW) {
2486                 if (re->options & RE_T)
2487                         printf("  %s\n       %-16s%-17s%-7s%-7s%-5s%-3s%-4s%s\n"
2488                             "%12s\n", ST_HDR);
2489                 else
2490                         printf("  %-23s%-16s%-17s%-7s%-7s%-3s%-4s%-3s%-4s%s\n",
2491                             S_HDR);
2492         } else {
2493                 if (re->options & RE_T)
2494                         printf("  %s\n       %-18s%-17s%-18s%s\n       %-18s"
2495                             "%-17s%-18s%s\n%12s\n", ST_HDRL);
2496                 else
2497                         printf("  %-23s%-17s%-18s%s\n       %-18s%-17s%-7s%"
2498                             "-6s%-6s%s\n", S_HDRL);
2499         }
2500         for (i = 0; (size_t)i < re->shnum; i++) {
2501                 s = &re->sl[i];
2502                 if (re->ec == ELFCLASS32) {
2503                         if (re->options & RE_T)
2504                                 printf("  [%2d] %s\n       %-15.15s %8.8jx"
2505                                     " %6.6jx %6.6jx %2.2jx  %2u %3u %2ju\n"
2506                                     "       %s\n", ST_CT);
2507                         else
2508                                 printf("  [%2d] %-17.17s %-15.15s %8.8jx"
2509                                     " %6.6jx %6.6jx %2.2jx %3s %2u %3u %2ju\n",
2510                                     S_CT);
2511                 } else if (re->options & RE_WW) {
2512                         if (re->options & RE_T)
2513                                 printf("  [%2d] %s\n       %-15.15s %16.16jx"
2514                                     " %6.6jx %6.6jx %2.2jx  %2u %3u %2ju\n"
2515                                     "       %s\n", ST_CT);
2516                         else
2517                                 printf("  [%2d] %-17.17s %-15.15s %16.16jx"
2518                                     " %6.6jx %6.6jx %2.2jx %3s %2u %3u %2ju\n",
2519                                     S_CT);
2520                 } else {
2521                         if (re->options & RE_T)
2522                                 printf("  [%2d] %s\n       %-15.15s  %16.16jx"
2523                                     "  %16.16jx  %u\n       %16.16jx %16.16jx"
2524                                     "  %-16u  %ju\n       %s\n", ST_CTL);
2525                         else
2526                                 printf("  [%2d] %-17.17s %-15.15s  %16.16jx"
2527                                     "  %8.8jx\n       %16.16jx  %16.16jx "
2528                                     "%3s      %2u   %3u     %ju\n", S_CT);
2529                 }
2530         }
2531         if ((re->options & RE_T) == 0)
2532                 printf("Key to Flags:\n  W (write), A (alloc),"
2533                     " X (execute), M (merge), S (strings)\n"
2534                     "  I (info), L (link order), G (group), x (unknown)\n"
2535                     "  O (extra OS processing required)"
2536                     " o (OS specific), p (processor specific)\n");
2537
2538 #undef  S_HDR
2539 #undef  S_HDRL
2540 #undef  ST_HDR
2541 #undef  ST_HDRL
2542 #undef  S_CT
2543 #undef  ST_CT
2544 #undef  ST_CTL
2545 }
2546
2547 /*
2548  * Return number of entries in the given section. We'd prefer ent_count be a
2549  * size_t *, but libelf APIs already use int for section indices.
2550  */
2551 static int
2552 get_ent_count(struct section *s, int *ent_count)
2553 {
2554         if (s->entsize == 0) {
2555                 warnx("section %s has entry size 0", s->name);
2556                 return (0);
2557         } else if (s->sz / s->entsize > INT_MAX) {
2558                 warnx("section %s has invalid section count", s->name);
2559                 return (0);
2560         }
2561         *ent_count = (int)(s->sz / s->entsize);
2562         return (1);
2563 }
2564
2565 static void
2566 dump_dynamic(struct readelf *re)
2567 {
2568         GElf_Dyn         dyn;
2569         Elf_Data        *d;
2570         struct section  *s;
2571         int              elferr, i, is_dynamic, j, jmax, nentries;
2572
2573         is_dynamic = 0;
2574
2575         for (i = 0; (size_t)i < re->shnum; i++) {
2576                 s = &re->sl[i];
2577                 if (s->type != SHT_DYNAMIC)
2578                         continue;
2579                 (void) elf_errno();
2580                 if ((d = elf_getdata(s->scn, NULL)) == NULL) {
2581                         elferr = elf_errno();
2582                         if (elferr != 0)
2583                                 warnx("elf_getdata failed: %s", elf_errmsg(-1));
2584                         continue;
2585                 }
2586                 if (d->d_size <= 0)
2587                         continue;
2588
2589                 is_dynamic = 1;
2590
2591                 /* Determine the actual number of table entries. */
2592                 nentries = 0;
2593                 if (!get_ent_count(s, &jmax))
2594                         continue;
2595                 for (j = 0; j < jmax; j++) {
2596                         if (gelf_getdyn(d, j, &dyn) != &dyn) {
2597                                 warnx("gelf_getdyn failed: %s",
2598                                     elf_errmsg(-1));
2599                                 continue;
2600                         }
2601                         nentries ++;
2602                         if (dyn.d_tag == DT_NULL)
2603                                 break;
2604                 }
2605
2606                 printf("\nDynamic section at offset 0x%jx", (uintmax_t)s->off);
2607                 printf(" contains %u entries:\n", nentries);
2608
2609                 if (re->ec == ELFCLASS32)
2610                         printf("%5s%12s%28s\n", "Tag", "Type", "Name/Value");
2611                 else
2612                         printf("%5s%20s%28s\n", "Tag", "Type", "Name/Value");
2613
2614                 for (j = 0; j < nentries; j++) {
2615                         if (gelf_getdyn(d, j, &dyn) != &dyn)
2616                                 continue;
2617                         /* Dump dynamic entry type. */
2618                         if (re->ec == ELFCLASS32)
2619                                 printf(" 0x%8.8jx", (uintmax_t)dyn.d_tag);
2620                         else
2621                                 printf(" 0x%16.16jx", (uintmax_t)dyn.d_tag);
2622                         printf(" %-20s", dt_type(re->ehdr.e_machine,
2623                             dyn.d_tag));
2624                         /* Dump dynamic entry value. */
2625                         dump_dyn_val(re, &dyn, s->link);
2626                 }
2627         }
2628
2629         if (!is_dynamic)
2630                 printf("\nThere is no dynamic section in this file.\n");
2631 }
2632
2633 static char *
2634 timestamp(time_t ti)
2635 {
2636         static char ts[32];
2637         struct tm *t;
2638
2639         t = gmtime(&ti);
2640         snprintf(ts, sizeof(ts), "%04d-%02d-%02dT%02d:%02d:%02d",
2641             t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour,
2642             t->tm_min, t->tm_sec);
2643
2644         return (ts);
2645 }
2646
2647 static const char *
2648 dyn_str(struct readelf *re, uint32_t stab, uint64_t d_val)
2649 {
2650         const char *name;
2651
2652         if (stab == SHN_UNDEF)
2653                 name = "ERROR";
2654         else if ((name = elf_strptr(re->elf, stab, d_val)) == NULL) {
2655                 (void) elf_errno(); /* clear error */
2656                 name = "ERROR";
2657         }
2658
2659         return (name);
2660 }
2661
2662 static void
2663 dump_arch_dyn_val(struct readelf *re, GElf_Dyn *dyn)
2664 {
2665         switch (re->ehdr.e_machine) {
2666         case EM_MIPS:
2667         case EM_MIPS_RS3_LE:
2668                 switch (dyn->d_tag) {
2669                 case DT_MIPS_RLD_VERSION:
2670                 case DT_MIPS_LOCAL_GOTNO:
2671                 case DT_MIPS_CONFLICTNO:
2672                 case DT_MIPS_LIBLISTNO:
2673                 case DT_MIPS_SYMTABNO:
2674                 case DT_MIPS_UNREFEXTNO:
2675                 case DT_MIPS_GOTSYM:
2676                 case DT_MIPS_HIPAGENO:
2677                 case DT_MIPS_DELTA_CLASS_NO:
2678                 case DT_MIPS_DELTA_INSTANCE_NO:
2679                 case DT_MIPS_DELTA_RELOC_NO:
2680                 case DT_MIPS_DELTA_SYM_NO:
2681                 case DT_MIPS_DELTA_CLASSSYM_NO:
2682                 case DT_MIPS_LOCALPAGE_GOTIDX:
2683                 case DT_MIPS_LOCAL_GOTIDX:
2684                 case DT_MIPS_HIDDEN_GOTIDX:
2685                 case DT_MIPS_PROTECTED_GOTIDX:
2686                         printf(" %ju\n", (uintmax_t) dyn->d_un.d_val);
2687                         break;
2688                 case DT_MIPS_ICHECKSUM:
2689                 case DT_MIPS_FLAGS:
2690                 case DT_MIPS_BASE_ADDRESS:
2691                 case DT_MIPS_CONFLICT:
2692                 case DT_MIPS_LIBLIST:
2693                 case DT_MIPS_RLD_MAP:
2694                 case DT_MIPS_DELTA_CLASS:
2695                 case DT_MIPS_DELTA_INSTANCE:
2696                 case DT_MIPS_DELTA_RELOC:
2697                 case DT_MIPS_DELTA_SYM:
2698                 case DT_MIPS_DELTA_CLASSSYM:
2699                 case DT_MIPS_CXX_FLAGS:
2700                 case DT_MIPS_PIXIE_INIT:
2701                 case DT_MIPS_SYMBOL_LIB:
2702                 case DT_MIPS_OPTIONS:
2703                 case DT_MIPS_INTERFACE:
2704                 case DT_MIPS_DYNSTR_ALIGN:
2705                 case DT_MIPS_INTERFACE_SIZE:
2706                 case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
2707                 case DT_MIPS_COMPACT_SIZE:
2708                 case DT_MIPS_GP_VALUE:
2709                 case DT_MIPS_AUX_DYNAMIC:
2710                 case DT_MIPS_PLTGOT:
2711                 case DT_MIPS_RLD_OBJ_UPDATE:
2712                 case DT_MIPS_RWPLT:
2713                         printf(" 0x%jx\n", (uintmax_t) dyn->d_un.d_val);
2714                         break;
2715                 case DT_MIPS_IVERSION:
2716                 case DT_MIPS_PERF_SUFFIX:
2717                 case DT_MIPS_TIME_STAMP:
2718                         printf(" %s\n", timestamp(dyn->d_un.d_val));
2719                         break;
2720                 default:
2721                         printf("\n");
2722                         break;
2723                 }
2724                 break;
2725         default:
2726                 printf("\n");
2727                 break;
2728         }
2729 }
2730
2731 static void
2732 dump_flags(struct flag_desc *desc, uint64_t val)
2733 {
2734         struct flag_desc *fd;
2735
2736         for (fd = desc; fd->flag != 0; fd++) {
2737                 if (val & fd->flag) {
2738                         val &= ~fd->flag;
2739                         printf(" %s", fd->desc);
2740                 }
2741         }
2742         if (val != 0)
2743                 printf(" unknown (0x%jx)", (uintmax_t)val);
2744         printf("\n");
2745 }
2746
2747 static struct flag_desc dt_flags[] = {
2748         { DF_ORIGIN,            "ORIGIN" },
2749         { DF_SYMBOLIC,          "SYMBOLIC" },
2750         { DF_TEXTREL,           "TEXTREL" },
2751         { DF_BIND_NOW,          "BIND_NOW" },
2752         { DF_STATIC_TLS,        "STATIC_TLS" },
2753         { 0, NULL }
2754 };
2755
2756 static struct flag_desc dt_flags_1[] = {
2757         { DF_1_BIND_NOW,        "NOW" },
2758         { DF_1_GLOBAL,          "GLOBAL" },
2759         { 0x4,                  "GROUP" },
2760         { DF_1_NODELETE,        "NODELETE" },
2761         { DF_1_LOADFLTR,        "LOADFLTR" },
2762         { 0x20,                 "INITFIRST" },
2763         { DF_1_NOOPEN,          "NOOPEN" },
2764         { DF_1_ORIGIN,          "ORIGIN" },
2765         { 0x100,                "DIRECT" },
2766         { DF_1_INTERPOSE,       "INTERPOSE" },
2767         { DF_1_NODEFLIB,        "NODEFLIB" },
2768         { 0x1000,               "NODUMP" },
2769         { 0x2000,               "CONFALT" },
2770         { 0x4000,               "ENDFILTEE" },
2771         { 0x8000,               "DISPRELDNE" },
2772         { 0x10000,              "DISPRELPND" },
2773         { 0x20000,              "NODIRECT" },
2774         { 0x40000,              "IGNMULDEF" },
2775         { 0x80000,              "NOKSYMS" },
2776         { 0x100000,             "NOHDR" },
2777         { 0x200000,             "EDITED" },
2778         { 0x400000,             "NORELOC" },
2779         { 0x800000,             "SYMINTPOSE" },
2780         { 0x1000000,            "GLOBAUDIT" },
2781         { 0, NULL }
2782 };
2783
2784 static void
2785 dump_dyn_val(struct readelf *re, GElf_Dyn *dyn, uint32_t stab)
2786 {
2787         const char *name;
2788
2789         if (dyn->d_tag >= DT_LOPROC && dyn->d_tag <= DT_HIPROC &&
2790             dyn->d_tag != DT_AUXILIARY && dyn->d_tag != DT_FILTER) {
2791                 dump_arch_dyn_val(re, dyn);
2792                 return;
2793         }
2794
2795         /* These entry values are index into the string table. */
2796         name = NULL;
2797         if (dyn->d_tag == DT_AUXILIARY || dyn->d_tag == DT_FILTER ||
2798             dyn->d_tag == DT_NEEDED || dyn->d_tag == DT_SONAME ||
2799             dyn->d_tag == DT_RPATH || dyn->d_tag == DT_RUNPATH)
2800                 name = dyn_str(re, stab, dyn->d_un.d_val);
2801
2802         switch(dyn->d_tag) {
2803         case DT_NULL:
2804         case DT_PLTGOT:
2805         case DT_HASH:
2806         case DT_STRTAB:
2807         case DT_SYMTAB:
2808         case DT_RELA:
2809         case DT_INIT:
2810         case DT_SYMBOLIC:
2811         case DT_REL:
2812         case DT_DEBUG:
2813         case DT_TEXTREL:
2814         case DT_JMPREL:
2815         case DT_FINI:
2816         case DT_VERDEF:
2817         case DT_VERNEED:
2818         case DT_VERSYM:
2819         case DT_GNU_HASH:
2820         case DT_GNU_LIBLIST:
2821         case DT_GNU_CONFLICT:
2822                 printf(" 0x%jx\n", (uintmax_t) dyn->d_un.d_val);
2823                 break;
2824         case DT_PLTRELSZ:
2825         case DT_RELASZ:
2826         case DT_RELAENT:
2827         case DT_STRSZ:
2828         case DT_SYMENT:
2829         case DT_RELSZ:
2830         case DT_RELENT:
2831         case DT_PREINIT_ARRAYSZ:
2832         case DT_INIT_ARRAYSZ:
2833         case DT_FINI_ARRAYSZ:
2834         case DT_GNU_CONFLICTSZ:
2835         case DT_GNU_LIBLISTSZ:
2836                 printf(" %ju (bytes)\n", (uintmax_t) dyn->d_un.d_val);
2837                 break;
2838         case DT_RELACOUNT:
2839         case DT_RELCOUNT:
2840         case DT_VERDEFNUM:
2841         case DT_VERNEEDNUM:
2842                 printf(" %ju\n", (uintmax_t) dyn->d_un.d_val);
2843                 break;
2844         case DT_AUXILIARY:
2845                 printf(" Auxiliary library: [%s]\n", name);
2846                 break;
2847         case DT_FILTER:
2848                 printf(" Filter library: [%s]\n", name);
2849                 break;
2850         case DT_NEEDED:
2851                 printf(" Shared library: [%s]\n", name);
2852                 break;
2853         case DT_SONAME:
2854                 printf(" Library soname: [%s]\n", name);
2855                 break;
2856         case DT_RPATH:
2857                 printf(" Library rpath: [%s]\n", name);
2858                 break;
2859         case DT_RUNPATH:
2860                 printf(" Library runpath: [%s]\n", name);
2861                 break;
2862         case DT_PLTREL:
2863                 printf(" %s\n", dt_type(re->ehdr.e_machine, dyn->d_un.d_val));
2864                 break;
2865         case DT_GNU_PRELINKED:
2866                 printf(" %s\n", timestamp(dyn->d_un.d_val));
2867                 break;
2868         case DT_FLAGS:
2869                 dump_flags(dt_flags, dyn->d_un.d_val);
2870                 break;
2871         case DT_FLAGS_1:
2872                 dump_flags(dt_flags_1, dyn->d_un.d_val);
2873                 break;
2874         default:
2875                 printf("\n");
2876         }
2877 }
2878
2879 static void
2880 dump_rel(struct readelf *re, struct section *s, Elf_Data *d)
2881 {
2882         GElf_Rel r;
2883         const char *symname;
2884         uint64_t symval;
2885         int i, len;
2886         uint32_t type;
2887         uint8_t type2, type3;
2888
2889         if (s->link >= re->shnum)
2890                 return;
2891
2892 #define REL_HDR "r_offset", "r_info", "r_type", "st_value", "st_name"
2893 #define REL_CT32 (uintmax_t)r.r_offset, (uintmax_t)r.r_info,        \
2894                 elftc_reloc_type_str(re->ehdr.e_machine,            \
2895                 ELF32_R_TYPE(r.r_info)), (uintmax_t)symval, symname
2896 #define REL_CT64 (uintmax_t)r.r_offset, (uintmax_t)r.r_info,        \
2897                 elftc_reloc_type_str(re->ehdr.e_machine, type),     \
2898                 (uintmax_t)symval, symname
2899
2900         printf("\nRelocation section (%s):\n", s->name);
2901         if (re->ec == ELFCLASS32)
2902                 printf("%-8s %-8s %-19s %-8s %s\n", REL_HDR);
2903         else {
2904                 if (re->options & RE_WW)
2905                         printf("%-16s %-16s %-24s %-16s %s\n", REL_HDR);
2906                 else
2907                         printf("%-12s %-12s %-19s %-16s %s\n", REL_HDR);
2908         }
2909         assert(d->d_size == s->sz);
2910         if (!get_ent_count(s, &len))
2911                 return;
2912         for (i = 0; i < len; i++) {
2913                 if (gelf_getrel(d, i, &r) != &r) {
2914                         warnx("gelf_getrel failed: %s", elf_errmsg(-1));
2915                         continue;
2916                 }
2917                 symname = get_symbol_name(re, s->link, GELF_R_SYM(r.r_info));
2918                 symval = get_symbol_value(re, s->link, GELF_R_SYM(r.r_info));
2919                 if (re->ec == ELFCLASS32) {
2920                         r.r_info = ELF32_R_INFO(ELF64_R_SYM(r.r_info),
2921                             ELF64_R_TYPE(r.r_info));
2922                         printf("%8.8jx %8.8jx %-19.19s %8.8jx %s\n", REL_CT32);
2923                 } else {
2924                         type = ELF64_R_TYPE(r.r_info);
2925                         if (re->ehdr.e_machine == EM_MIPS) {
2926                                 type2 = (type >> 8) & 0xFF;
2927                                 type3 = (type >> 16) & 0xFF;
2928                                 type = type & 0xFF;
2929                         } else {
2930                                 type2 = type3 = 0;
2931                         }
2932                         if (re->options & RE_WW)
2933                                 printf("%16.16jx %16.16jx %-24.24s"
2934                                     " %16.16jx %s\n", REL_CT64);
2935                         else
2936                                 printf("%12.12jx %12.12jx %-19.19s"
2937                                     " %16.16jx %s\n", REL_CT64);
2938                         if (re->ehdr.e_machine == EM_MIPS) {
2939                                 if (re->options & RE_WW) {
2940                                         printf("%32s: %s\n", "Type2",
2941                                             elftc_reloc_type_str(EM_MIPS,
2942                                             type2));
2943                                         printf("%32s: %s\n", "Type3",
2944                                             elftc_reloc_type_str(EM_MIPS,
2945                                             type3));
2946                                 } else {
2947                                         printf("%24s: %s\n", "Type2",
2948                                             elftc_reloc_type_str(EM_MIPS,
2949                                             type2));
2950                                         printf("%24s: %s\n", "Type3",
2951                                             elftc_reloc_type_str(EM_MIPS,
2952                                             type3));
2953                                 }
2954                         }
2955                 }
2956         }
2957
2958 #undef  REL_HDR
2959 #undef  REL_CT
2960 }
2961
2962 static void
2963 dump_rela(struct readelf *re, struct section *s, Elf_Data *d)
2964 {
2965         GElf_Rela r;
2966         const char *symname;
2967         uint64_t symval;
2968         int i, len;
2969         uint32_t type;
2970         uint8_t type2, type3;
2971
2972         if (s->link >= re->shnum)
2973                 return;
2974
2975 #define RELA_HDR "r_offset", "r_info", "r_type", "st_value", \
2976                 "st_name + r_addend"
2977 #define RELA_CT32 (uintmax_t)r.r_offset, (uintmax_t)r.r_info,       \
2978                 elftc_reloc_type_str(re->ehdr.e_machine,            \
2979                 ELF32_R_TYPE(r.r_info)), (uintmax_t)symval, symname
2980 #define RELA_CT64 (uintmax_t)r.r_offset, (uintmax_t)r.r_info,       \
2981                 elftc_reloc_type_str(re->ehdr.e_machine, type),     \
2982                 (uintmax_t)symval, symname
2983
2984         printf("\nRelocation section with addend (%s):\n", s->name);
2985         if (re->ec == ELFCLASS32)
2986                 printf("%-8s %-8s %-19s %-8s %s\n", RELA_HDR);
2987         else {
2988                 if (re->options & RE_WW)
2989                         printf("%-16s %-16s %-24s %-16s %s\n", RELA_HDR);
2990                 else
2991                         printf("%-12s %-12s %-19s %-16s %s\n", RELA_HDR);
2992         }
2993         assert(d->d_size == s->sz);
2994         if (!get_ent_count(s, &len))
2995                 return;
2996         for (i = 0; i < len; i++) {
2997                 if (gelf_getrela(d, i, &r) != &r) {
2998                         warnx("gelf_getrel failed: %s", elf_errmsg(-1));
2999                         continue;
3000                 }
3001                 symname = get_symbol_name(re, s->link, GELF_R_SYM(r.r_info));
3002                 symval = get_symbol_value(re, s->link, GELF_R_SYM(r.r_info));
3003                 if (re->ec == ELFCLASS32) {
3004                         r.r_info = ELF32_R_INFO(ELF64_R_SYM(r.r_info),
3005                             ELF64_R_TYPE(r.r_info));
3006                         printf("%8.8jx %8.8jx %-19.19s %8.8jx %s", RELA_CT32);
3007                         printf(" + %x\n", (uint32_t) r.r_addend);
3008                 } else {
3009                         type = ELF64_R_TYPE(r.r_info);
3010                         if (re->ehdr.e_machine == EM_MIPS) {
3011                                 type2 = (type >> 8) & 0xFF;
3012                                 type3 = (type >> 16) & 0xFF;
3013                                 type = type & 0xFF;
3014                         } else {
3015                                 type2 = type3 = 0;
3016                         }
3017                         if (re->options & RE_WW)
3018                                 printf("%16.16jx %16.16jx %-24.24s"
3019                                     " %16.16jx %s", RELA_CT64);
3020                         else
3021                                 printf("%12.12jx %12.12jx %-19.19s"
3022                                     " %16.16jx %s", RELA_CT64);
3023                         printf(" + %jx\n", (uintmax_t) r.r_addend);
3024                         if (re->ehdr.e_machine == EM_MIPS) {
3025                                 if (re->options & RE_WW) {
3026                                         printf("%32s: %s\n", "Type2",
3027                                             elftc_reloc_type_str(EM_MIPS,
3028                                             type2));
3029                                         printf("%32s: %s\n", "Type3",
3030                                             elftc_reloc_type_str(EM_MIPS,
3031                                             type3));
3032                                 } else {
3033                                         printf("%24s: %s\n", "Type2",
3034                                             elftc_reloc_type_str(EM_MIPS,
3035                                             type2));
3036                                         printf("%24s: %s\n", "Type3",
3037                                             elftc_reloc_type_str(EM_MIPS,
3038                                             type3));
3039                                 }
3040                         }
3041                 }
3042         }
3043
3044 #undef  RELA_HDR
3045 #undef  RELA_CT
3046 }
3047
3048 static void
3049 dump_reloc(struct readelf *re)
3050 {
3051         struct section *s;
3052         Elf_Data *d;
3053         int i, elferr;
3054
3055         for (i = 0; (size_t)i < re->shnum; i++) {
3056                 s = &re->sl[i];
3057                 if (s->type == SHT_REL || s->type == SHT_RELA) {
3058                         (void) elf_errno();
3059                         if ((d = elf_getdata(s->scn, NULL)) == NULL) {
3060                                 elferr = elf_errno();
3061                                 if (elferr != 0)
3062                                         warnx("elf_getdata failed: %s",
3063                                             elf_errmsg(elferr));
3064                                 continue;
3065                         }
3066                         if (s->type == SHT_REL)
3067                                 dump_rel(re, s, d);
3068                         else
3069                                 dump_rela(re, s, d);
3070                 }
3071         }
3072 }
3073
3074 static void
3075 dump_symtab(struct readelf *re, int i)
3076 {
3077         struct section *s;
3078         Elf_Data *d;
3079         GElf_Sym sym;
3080         const char *name;
3081         uint32_t stab;
3082         int elferr, j, len;
3083         uint16_t vs;
3084
3085         s = &re->sl[i];
3086         if (s->link >= re->shnum)
3087                 return;
3088         stab = s->link;
3089         (void) elf_errno();
3090         if ((d = elf_getdata(s->scn, NULL)) == NULL) {
3091                 elferr = elf_errno();
3092                 if (elferr != 0)
3093                         warnx("elf_getdata failed: %s", elf_errmsg(elferr));
3094                 return;
3095         }
3096         if (d->d_size <= 0)
3097                 return;
3098         if (!get_ent_count(s, &len))
3099                 return;
3100         printf("Symbol table (%s)", s->name);
3101         printf(" contains %d entries:\n", len);
3102         printf("%7s%9s%14s%5s%8s%6s%9s%5s\n", "Num:", "Value", "Size", "Type",
3103             "Bind", "Vis", "Ndx", "Name");
3104
3105         for (j = 0; j < len; j++) {
3106                 if (gelf_getsym(d, j, &sym) != &sym) {
3107                         warnx("gelf_getsym failed: %s", elf_errmsg(-1));
3108                         continue;
3109                 }
3110                 printf("%6d:", j);
3111                 printf(" %16.16jx", (uintmax_t) sym.st_value);
3112                 printf(" %5ju", (uintmax_t) sym.st_size);
3113                 printf(" %-7s", st_type(re->ehdr.e_machine,
3114                     re->ehdr.e_ident[EI_OSABI], GELF_ST_TYPE(sym.st_info)));
3115                 printf(" %-6s", st_bind(GELF_ST_BIND(sym.st_info)));
3116                 printf(" %-8s", st_vis(GELF_ST_VISIBILITY(sym.st_other)));
3117                 printf(" %3s", st_shndx(sym.st_shndx));
3118                 if ((name = elf_strptr(re->elf, stab, sym.st_name)) != NULL)
3119                         printf(" %s", name);
3120                 /* Append symbol version string for SHT_DYNSYM symbol table. */
3121                 if (s->type == SHT_DYNSYM && re->ver != NULL &&
3122                     re->vs != NULL && re->vs[j] > 1) {
3123                         vs = re->vs[j] & VERSYM_VERSION;
3124                         if (vs >= re->ver_sz || re->ver[vs].name == NULL) {
3125                                 warnx("invalid versym version index %u", vs);
3126                                 break;
3127                         }
3128                         if (re->vs[j] & VERSYM_HIDDEN || re->ver[vs].type == 0)
3129                                 printf("@%s (%d)", re->ver[vs].name, vs);
3130                         else
3131                                 printf("@@%s (%d)", re->ver[vs].name, vs);
3132                 }
3133                 putchar('\n');
3134         }
3135
3136 }
3137
3138 static void
3139 dump_symtabs(struct readelf *re)
3140 {
3141         GElf_Dyn dyn;
3142         Elf_Data *d;
3143         struct section *s;
3144         uint64_t dyn_off;
3145         int elferr, i, len;
3146
3147         /*
3148          * If -D is specified, only dump the symbol table specified by
3149          * the DT_SYMTAB entry in the .dynamic section.
3150          */
3151         dyn_off = 0;
3152         if (re->options & RE_DD) {
3153                 s = NULL;
3154                 for (i = 0; (size_t)i < re->shnum; i++)
3155                         if (re->sl[i].type == SHT_DYNAMIC) {
3156                                 s = &re->sl[i];
3157                                 break;
3158                         }
3159                 if (s == NULL)
3160                         return;
3161                 (void) elf_errno();
3162                 if ((d = elf_getdata(s->scn, NULL)) == NULL) {
3163                         elferr = elf_errno();
3164                         if (elferr != 0)
3165                                 warnx("elf_getdata failed: %s", elf_errmsg(-1));
3166                         return;
3167                 }
3168                 if (d->d_size <= 0)
3169                         return;
3170                 if (!get_ent_count(s, &len))
3171                         return;
3172
3173                 for (i = 0; i < len; i++) {
3174                         if (gelf_getdyn(d, i, &dyn) != &dyn) {
3175                                 warnx("gelf_getdyn failed: %s", elf_errmsg(-1));
3176                                 continue;
3177                         }
3178                         if (dyn.d_tag == DT_SYMTAB) {
3179                                 dyn_off = dyn.d_un.d_val;
3180                                 break;
3181                         }
3182                 }
3183         }
3184
3185         /* Find and dump symbol tables. */
3186         for (i = 0; (size_t)i < re->shnum; i++) {
3187                 s = &re->sl[i];
3188                 if (s->type == SHT_SYMTAB || s->type == SHT_DYNSYM) {
3189                         if (re->options & RE_DD) {
3190                                 if (dyn_off == s->addr) {
3191                                         dump_symtab(re, i);
3192                                         break;
3193                                 }
3194                         } else
3195                                 dump_symtab(re, i);
3196                 }
3197         }
3198 }
3199
3200 static void
3201 dump_svr4_hash(struct section *s)
3202 {
3203         Elf_Data        *d;
3204         uint32_t        *buf;
3205         uint32_t         nbucket, nchain;
3206         uint32_t        *bucket, *chain;
3207         uint32_t        *bl, *c, maxl, total;
3208         int              elferr, i, j;
3209
3210         /* Read and parse the content of .hash section. */
3211         (void) elf_errno();
3212         if ((d = elf_getdata(s->scn, NULL)) == NULL) {
3213                 elferr = elf_errno();
3214                 if (elferr != 0)
3215                         warnx("elf_getdata failed: %s", elf_errmsg(elferr));
3216                 return;
3217         }
3218         if (d->d_size < 2 * sizeof(uint32_t)) {
3219                 warnx(".hash section too small");
3220                 return;
3221         }
3222         buf = d->d_buf;
3223         nbucket = buf[0];
3224         nchain = buf[1];
3225         if (nbucket <= 0 || nchain <= 0) {
3226                 warnx("Malformed .hash section");
3227                 return;
3228         }
3229         if (d->d_size != (nbucket + nchain + 2) * sizeof(uint32_t)) {
3230                 warnx("Malformed .hash section");
3231                 return;
3232         }
3233         bucket = &buf[2];
3234         chain = &buf[2 + nbucket];
3235
3236         maxl = 0;
3237         if ((bl = calloc(nbucket, sizeof(*bl))) == NULL)
3238                 errx(EXIT_FAILURE, "calloc failed");
3239         for (i = 0; (uint32_t)i < nbucket; i++)
3240                 for (j = bucket[i]; j > 0 && (uint32_t)j < nchain; j = chain[j])
3241                         if (++bl[i] > maxl)
3242                                 maxl = bl[i];
3243         if ((c = calloc(maxl + 1, sizeof(*c))) == NULL)
3244                 errx(EXIT_FAILURE, "calloc failed");
3245         for (i = 0; (uint32_t)i < nbucket; i++)
3246                 c[bl[i]]++;
3247         printf("\nHistogram for bucket list length (total of %u buckets):\n",
3248             nbucket);
3249         printf(" Length\tNumber\t\t%% of total\tCoverage\n");
3250         total = 0;
3251         for (i = 0; (uint32_t)i <= maxl; i++) {
3252                 total += c[i] * i;
3253                 printf("%7u\t%-10u\t(%5.1f%%)\t%5.1f%%\n", i, c[i],
3254                     c[i] * 100.0 / nbucket, total * 100.0 / (nchain - 1));
3255         }
3256         free(c);
3257         free(bl);
3258 }
3259
3260 static void
3261 dump_svr4_hash64(struct readelf *re, struct section *s)
3262 {
3263         Elf_Data        *d, dst;
3264         uint64_t        *buf;
3265         uint64_t         nbucket, nchain;
3266         uint64_t        *bucket, *chain;
3267         uint64_t        *bl, *c, maxl, total;
3268         int              elferr, i, j;
3269
3270         /*
3271          * ALPHA uses 64-bit hash entries. Since libelf assumes that
3272          * .hash section contains only 32-bit entry, an explicit
3273          * gelf_xlatetom is needed here.
3274          */
3275         (void) elf_errno();
3276         if ((d = elf_rawdata(s->scn, NULL)) == NULL) {
3277                 elferr = elf_errno();
3278                 if (elferr != 0)
3279                         warnx("elf_rawdata failed: %s",
3280                             elf_errmsg(elferr));
3281                 return;
3282         }
3283         d->d_type = ELF_T_XWORD;
3284         memcpy(&dst, d, sizeof(Elf_Data));
3285         if (gelf_xlatetom(re->elf, &dst, d,
3286                 re->ehdr.e_ident[EI_DATA]) != &dst) {
3287                 warnx("gelf_xlatetom failed: %s", elf_errmsg(-1));
3288                 return;
3289         }
3290         if (dst.d_size < 2 * sizeof(uint64_t)) {
3291                 warnx(".hash section too small");
3292                 return;
3293         }
3294         buf = dst.d_buf;
3295         nbucket = buf[0];
3296         nchain = buf[1];
3297         if (nbucket <= 0 || nchain <= 0) {
3298                 warnx("Malformed .hash section");
3299                 return;
3300         }
3301         if (d->d_size != (nbucket + nchain + 2) * sizeof(uint32_t)) {
3302                 warnx("Malformed .hash section");
3303                 return;
3304         }
3305         bucket = &buf[2];
3306         chain = &buf[2 + nbucket];
3307
3308         maxl = 0;
3309         if ((bl = calloc(nbucket, sizeof(*bl))) == NULL)
3310                 errx(EXIT_FAILURE, "calloc failed");
3311         for (i = 0; (uint32_t)i < nbucket; i++)
3312                 for (j = bucket[i]; j > 0 && (uint32_t)j < nchain; j = chain[j])
3313                         if (++bl[i] > maxl)
3314                                 maxl = bl[i];
3315         if ((c = calloc(maxl + 1, sizeof(*c))) == NULL)
3316                 errx(EXIT_FAILURE, "calloc failed");
3317         for (i = 0; (uint64_t)i < nbucket; i++)
3318                 c[bl[i]]++;
3319         printf("Histogram for bucket list length (total of %ju buckets):\n",
3320             (uintmax_t)nbucket);
3321         printf(" Length\tNumber\t\t%% of total\tCoverage\n");
3322         total = 0;
3323         for (i = 0; (uint64_t)i <= maxl; i++) {
3324                 total += c[i] * i;
3325                 printf("%7u\t%-10ju\t(%5.1f%%)\t%5.1f%%\n", i, (uintmax_t)c[i],
3326                     c[i] * 100.0 / nbucket, total * 100.0 / (nchain - 1));
3327         }
3328         free(c);
3329         free(bl);
3330 }
3331
3332 static void
3333 dump_gnu_hash(struct readelf *re, struct section *s)
3334 {
3335         struct section  *ds;
3336         Elf_Data        *d;
3337         uint32_t        *buf;
3338         uint32_t        *bucket, *chain;
3339         uint32_t         nbucket, nchain, symndx, maskwords;
3340         uint32_t        *bl, *c, maxl, total;
3341         int              elferr, dynsymcount, i, j;
3342
3343         (void) elf_errno();
3344         if ((d = elf_getdata(s->scn, NULL)) == NULL) {
3345                 elferr = elf_errno();
3346                 if (elferr != 0)
3347                         warnx("elf_getdata failed: %s",
3348                             elf_errmsg(elferr));
3349                 return;
3350         }
3351         if (d->d_size < 4 * sizeof(uint32_t)) {
3352                 warnx(".gnu.hash section too small");
3353                 return;
3354         }
3355         buf = d->d_buf;
3356         nbucket = buf[0];
3357         symndx = buf[1];
3358         maskwords = buf[2];
3359         buf += 4;
3360         if (s->link >= re->shnum)
3361                 return;
3362         ds = &re->sl[s->link];
3363         if (!get_ent_count(ds, &dynsymcount))
3364                 return;
3365         if (symndx >= (uint32_t)dynsymcount) {
3366                 warnx("Malformed .gnu.hash section (symndx out of range)");
3367                 return;
3368         }
3369         nchain = dynsymcount - symndx;
3370         if (d->d_size != 4 * sizeof(uint32_t) + maskwords *
3371             (re->ec == ELFCLASS32 ? sizeof(uint32_t) : sizeof(uint64_t)) +
3372             (nbucket + nchain) * sizeof(uint32_t)) {
3373                 warnx("Malformed .gnu.hash section");
3374                 return;
3375         }
3376         bucket = buf + (re->ec == ELFCLASS32 ? maskwords : maskwords * 2);
3377         chain = bucket + nbucket;
3378
3379         maxl = 0;
3380         if ((bl = calloc(nbucket, sizeof(*bl))) == NULL)
3381                 errx(EXIT_FAILURE, "calloc failed");
3382         for (i = 0; (uint32_t)i < nbucket; i++)
3383                 for (j = bucket[i]; j > 0 && (uint32_t)j - symndx < nchain;
3384                      j++) {
3385                         if (++bl[i] > maxl)
3386                                 maxl = bl[i];
3387                         if (chain[j - symndx] & 1)
3388                                 break;
3389                 }
3390         if ((c = calloc(maxl + 1, sizeof(*c))) == NULL)
3391                 errx(EXIT_FAILURE, "calloc failed");
3392         for (i = 0; (uint32_t)i < nbucket; i++)
3393                 c[bl[i]]++;
3394         printf("Histogram for bucket list length (total of %u buckets):\n",
3395             nbucket);
3396         printf(" Length\tNumber\t\t%% of total\tCoverage\n");
3397         total = 0;
3398         for (i = 0; (uint32_t)i <= maxl; i++) {
3399                 total += c[i] * i;
3400                 printf("%7u\t%-10u\t(%5.1f%%)\t%5.1f%%\n", i, c[i],
3401                     c[i] * 100.0 / nbucket, total * 100.0 / (nchain - 1));
3402         }
3403         free(c);
3404         free(bl);
3405 }
3406
3407 static void
3408 dump_hash(struct readelf *re)
3409 {
3410         struct section  *s;
3411         int              i;
3412
3413         for (i = 0; (size_t) i < re->shnum; i++) {
3414                 s = &re->sl[i];
3415                 if (s->type == SHT_HASH || s->type == SHT_GNU_HASH) {
3416                         if (s->type == SHT_GNU_HASH)
3417                                 dump_gnu_hash(re, s);
3418                         else if (re->ehdr.e_machine == EM_ALPHA &&
3419                             s->entsize == 8)
3420                                 dump_svr4_hash64(re, s);
3421                         else
3422                                 dump_svr4_hash(s);
3423                 }
3424         }
3425 }
3426
3427 static void
3428 dump_notes(struct readelf *re)
3429 {
3430         struct section *s;
3431         const char *rawfile;
3432         GElf_Phdr phdr;
3433         Elf_Data *d;
3434         size_t filesize, phnum;
3435         int i, elferr;
3436
3437         if (re->ehdr.e_type == ET_CORE) {
3438                 /*
3439                  * Search program headers in the core file for
3440                  * PT_NOTE entry.
3441                  */
3442                 if (elf_getphnum(re->elf, &phnum) == 0) {
3443                         warnx("elf_getphnum failed: %s", elf_errmsg(-1));
3444                         return;
3445                 }
3446                 if (phnum == 0)
3447                         return;
3448                 if ((rawfile = elf_rawfile(re->elf, &filesize)) == NULL) {
3449                         warnx("elf_rawfile failed: %s", elf_errmsg(-1));
3450                         return;
3451                 }
3452                 for (i = 0; (size_t) i < phnum; i++) {
3453                         if (gelf_getphdr(re->elf, i, &phdr) != &phdr) {
3454                                 warnx("gelf_getphdr failed: %s",
3455                                     elf_errmsg(-1));
3456                                 continue;
3457                         }
3458                         if (phdr.p_type == PT_NOTE) {
3459                                 if (phdr.p_offset >= filesize ||
3460                                     phdr.p_filesz > filesize - phdr.p_offset) {
3461                                         warnx("invalid PHDR offset");
3462                                         continue;
3463                                 }
3464                                 dump_notes_content(re, rawfile + phdr.p_offset,
3465                                     phdr.p_filesz, phdr.p_offset);
3466                         }
3467                 }
3468
3469         } else {
3470                 /*
3471                  * For objects other than core files, Search for
3472                  * SHT_NOTE sections.
3473                  */
3474                 for (i = 0; (size_t) i < re->shnum; i++) {
3475                         s = &re->sl[i];
3476                         if (s->type == SHT_NOTE) {
3477                                 (void) elf_errno();
3478                                 if ((d = elf_getdata(s->scn, NULL)) == NULL) {
3479                                         elferr = elf_errno();
3480                                         if (elferr != 0)
3481                                                 warnx("elf_getdata failed: %s",
3482                                                     elf_errmsg(elferr));
3483                                         continue;
3484                                 }
3485                                 dump_notes_content(re, d->d_buf, d->d_size,
3486                                     s->off);
3487                         }
3488                 }
3489         }
3490 }
3491
3492 static struct flag_desc note_feature_ctl_flags[] = {
3493         { NT_FREEBSD_FCTL_ASLR_DISABLE,         "ASLR_DISABLE" },
3494         { 0, NULL }
3495 };
3496
3497 static void
3498 dump_notes_data(const char *name, uint32_t type, const char *buf, size_t sz)
3499 {
3500         size_t i;
3501         const uint32_t *ubuf;
3502
3503         /* Note data is at least 4-byte aligned. */
3504         if (((uintptr_t)buf & 3) != 0) {
3505                 warnx("bad note data alignment");
3506                 goto unknown;
3507         }
3508         ubuf = (const uint32_t *)(const void *)buf;
3509
3510         if (strcmp(name, "FreeBSD") == 0) {
3511                 switch (type) {
3512                 case NT_FREEBSD_ABI_TAG:
3513                         if (sz != 4)
3514                                 goto unknown;
3515                         printf("   ABI tag: %u\n", ubuf[0]);
3516                         return;
3517                 /* NT_FREEBSD_NOINIT_TAG carries no data, treat as unknown. */
3518                 case NT_FREEBSD_ARCH_TAG:
3519                         if (sz != 4)
3520                                 goto unknown;
3521                         printf("   Arch tag: %x\n", ubuf[0]);
3522                         return;
3523                 case NT_FREEBSD_FEATURE_CTL:
3524                         if (sz != 4)
3525                                 goto unknown;
3526                         printf("   Features:");
3527                         dump_flags(note_feature_ctl_flags, ubuf[0]);
3528                         return;
3529                 }
3530         }
3531 unknown:
3532         printf("   description data:");
3533         for (i = 0; i < sz; i++)
3534                 printf(" %02x", (unsigned char)buf[i]);
3535         printf("\n");
3536 }
3537
3538 static void
3539 dump_notes_content(struct readelf *re, const char *buf, size_t sz, off_t off)
3540 {
3541         Elf_Note *note;
3542         const char *end, *name;
3543
3544         printf("\nNotes at offset %#010jx with length %#010jx:\n",
3545             (uintmax_t) off, (uintmax_t) sz);
3546         printf("  %-13s %-15s %s\n", "Owner", "Data size", "Description");
3547         end = buf + sz;
3548         while (buf < end) {
3549                 if (buf + sizeof(*note) > end) {
3550                         warnx("invalid note header");
3551                         return;
3552                 }
3553                 note = (Elf_Note *)(uintptr_t) buf;
3554                 buf += sizeof(Elf_Note);
3555                 name = buf;
3556                 buf += roundup2(note->n_namesz, 4);
3557                 /*
3558                  * The name field is required to be nul-terminated, and
3559                  * n_namesz includes the terminating nul in observed
3560                  * implementations (contrary to the ELF-64 spec). A special
3561                  * case is needed for cores generated by some older Linux
3562                  * versions, which write a note named "CORE" without a nul
3563                  * terminator and n_namesz = 4.
3564                  */
3565                 if (note->n_namesz == 0)
3566                         name = "";
3567                 else if (note->n_namesz == 4 && strncmp(name, "CORE", 4) == 0)
3568                         name = "CORE";
3569                 else if (strnlen(name, note->n_namesz) >= note->n_namesz)
3570                         name = "<invalid>";
3571                 printf("  %-13s %#010jx", name, (uintmax_t) note->n_descsz);
3572                 printf("      %s\n", note_type(name, re->ehdr.e_type,
3573                     note->n_type));
3574                 dump_notes_data(name, note->n_type, buf, note->n_descsz);
3575                 buf += roundup2(note->n_descsz, 4);
3576         }
3577 }
3578
3579 /*
3580  * Symbol versioning sections are the same for 32bit and 64bit
3581  * ELF objects.
3582  */
3583 #define Elf_Verdef      Elf32_Verdef
3584 #define Elf_Verdaux     Elf32_Verdaux
3585 #define Elf_Verneed     Elf32_Verneed
3586 #define Elf_Vernaux     Elf32_Vernaux
3587
3588 #define SAVE_VERSION_NAME(x, n, t)                                      \
3589         do {                                                            \
3590                 while (x >= re->ver_sz) {                               \
3591                         nv = realloc(re->ver,                           \
3592                             sizeof(*re->ver) * re->ver_sz * 2);         \
3593                         if (nv == NULL) {                               \
3594                                 warn("realloc failed");                 \
3595                                 free(re->ver);                          \
3596                                 return;                                 \
3597                         }                                               \
3598                         re->ver = nv;                                   \
3599                         for (i = re->ver_sz; i < re->ver_sz * 2; i++) { \
3600                                 re->ver[i].name = NULL;                 \
3601                                 re->ver[i].type = 0;                    \
3602                         }                                               \
3603                         re->ver_sz *= 2;                                \
3604                 }                                                       \
3605                 if (x > 1) {                                            \
3606                         re->ver[x].name = n;                            \
3607                         re->ver[x].type = t;                            \
3608                 }                                                       \
3609         } while (0)
3610
3611
3612 static void
3613 dump_verdef(struct readelf *re, int dump)
3614 {
3615         struct section *s;
3616         struct symver *nv;
3617         Elf_Data *d;
3618         Elf_Verdef *vd;
3619         Elf_Verdaux *vda;
3620         uint8_t *buf, *end, *buf2;
3621         const char *name;
3622         int elferr, i, j;
3623
3624         if ((s = re->vd_s) == NULL)
3625                 return;
3626         if (s->link >= re->shnum)
3627                 return;
3628
3629         if (re->ver == NULL) {
3630                 re->ver_sz = 16;
3631                 if ((re->ver = calloc(re->ver_sz, sizeof(*re->ver))) ==
3632                     NULL) {
3633                         warn("calloc failed");
3634                         return;
3635                 }
3636                 re->ver[0].name = "*local*";
3637                 re->ver[1].name = "*global*";
3638         }
3639
3640         if (dump)
3641                 printf("\nVersion definition section (%s):\n", s->name);
3642         (void) elf_errno();
3643         if ((d = elf_getdata(s->scn, NULL)) == NULL) {
3644                 elferr = elf_errno();
3645                 if (elferr != 0)
3646                         warnx("elf_getdata failed: %s", elf_errmsg(elferr));
3647                 return;
3648         }
3649         if (d->d_size == 0)
3650                 return;
3651
3652         buf = d->d_buf;
3653         end = buf + d->d_size;
3654         while (buf + sizeof(Elf_Verdef) <= end) {
3655                 vd = (Elf_Verdef *) (uintptr_t) buf;
3656                 if (dump) {
3657                         printf("  0x%4.4lx", (unsigned long)
3658                             (buf - (uint8_t *)d->d_buf));
3659                         printf(" vd_version: %u vd_flags: %d"
3660                             " vd_ndx: %u vd_cnt: %u", vd->vd_version,
3661                             vd->vd_flags, vd->vd_ndx, vd->vd_cnt);
3662                 }
3663                 buf2 = buf + vd->vd_aux;
3664                 j = 0;
3665                 while (buf2 + sizeof(Elf_Verdaux) <= end && j < vd->vd_cnt) {
3666                         vda = (Elf_Verdaux *) (uintptr_t) buf2;
3667                         name = get_string(re, s->link, vda->vda_name);
3668                         if (j == 0) {
3669                                 if (dump)
3670                                         printf(" vda_name: %s\n", name);
3671                                 SAVE_VERSION_NAME((int)vd->vd_ndx, name, 1);
3672                         } else if (dump)
3673                                 printf("  0x%4.4lx parent: %s\n",
3674                                     (unsigned long) (buf2 -
3675                                     (uint8_t *)d->d_buf), name);
3676                         if (vda->vda_next == 0)
3677                                 break;
3678                         buf2 += vda->vda_next;
3679                         j++;
3680                 }
3681                 if (vd->vd_next == 0)
3682                         break;
3683                 buf += vd->vd_next;
3684         }
3685 }
3686
3687 static void
3688 dump_verneed(struct readelf *re, int dump)
3689 {
3690         struct section *s;
3691         struct symver *nv;
3692         Elf_Data *d;
3693         Elf_Verneed *vn;
3694         Elf_Vernaux *vna;
3695         uint8_t *buf, *end, *buf2;
3696         const char *name;
3697         int elferr, i, j;
3698
3699         if ((s = re->vn_s) == NULL)
3700                 return;
3701         if (s->link >= re->shnum)
3702                 return;
3703
3704         if (re->ver == NULL) {
3705                 re->ver_sz = 16;
3706                 if ((re->ver = calloc(re->ver_sz, sizeof(*re->ver))) ==
3707                     NULL) {
3708                         warn("calloc failed");
3709                         return;
3710                 }
3711                 re->ver[0].name = "*local*";
3712                 re->ver[1].name = "*global*";
3713         }
3714
3715         if (dump)
3716                 printf("\nVersion needed section (%s):\n", s->name);
3717         (void) elf_errno();
3718         if ((d = elf_getdata(s->scn, NULL)) == NULL) {
3719                 elferr = elf_errno();
3720                 if (elferr != 0)
3721                         warnx("elf_getdata failed: %s", elf_errmsg(elferr));
3722                 return;
3723         }
3724         if (d->d_size == 0)
3725                 return;
3726
3727         buf = d->d_buf;
3728         end = buf + d->d_size;
3729         while (buf + sizeof(Elf_Verneed) <= end) {
3730                 vn = (Elf_Verneed *) (uintptr_t) buf;
3731                 if (dump) {
3732                         printf("  0x%4.4lx", (unsigned long)
3733                             (buf - (uint8_t *)d->d_buf));
3734                         printf(" vn_version: %u vn_file: %s vn_cnt: %u\n",
3735                             vn->vn_version,
3736                             get_string(re, s->link, vn->vn_file),
3737                             vn->vn_cnt);
3738                 }
3739                 buf2 = buf + vn->vn_aux;
3740                 j = 0;
3741                 while (buf2 + sizeof(Elf_Vernaux) <= end && j < vn->vn_cnt) {
3742                         vna = (Elf32_Vernaux *) (uintptr_t) buf2;
3743                         if (dump)
3744                                 printf("  0x%4.4lx", (unsigned long)
3745                                     (buf2 - (uint8_t *)d->d_buf));
3746                         name = get_string(re, s->link, vna->vna_name);
3747                         if (dump)
3748                                 printf("   vna_name: %s vna_flags: %u"
3749                                     " vna_other: %u\n", name,
3750                                     vna->vna_flags, vna->vna_other);
3751                         SAVE_VERSION_NAME((int)vna->vna_other, name, 0);
3752                         if (vna->vna_next == 0)
3753                                 break;
3754                         buf2 += vna->vna_next;
3755                         j++;
3756                 }
3757                 if (vn->vn_next == 0)
3758                         break;
3759                 buf += vn->vn_next;
3760         }
3761 }
3762
3763 static void
3764 dump_versym(struct readelf *re)
3765 {
3766         int i;
3767         uint16_t vs;
3768
3769         if (re->vs_s == NULL || re->ver == NULL || re->vs == NULL)
3770                 return;
3771         printf("\nVersion symbol section (%s):\n", re->vs_s->name);
3772         for (i = 0; i < re->vs_sz; i++) {
3773                 if ((i & 3) == 0) {
3774                         if (i > 0)
3775                                 putchar('\n');
3776                         printf("  %03x:", i);
3777                 }
3778                 vs = re->vs[i] & VERSYM_VERSION;
3779                 if (vs >= re->ver_sz || re->ver[vs].name == NULL) {
3780                         warnx("invalid versym version index %u", re->vs[i]);
3781                         break;
3782                 }
3783                 if (re->vs[i] & VERSYM_HIDDEN)
3784                         printf(" %3xh %-12s ", vs,
3785                             re->ver[re->vs[i] & VERSYM_VERSION].name);
3786                 else
3787                         printf(" %3x %-12s ", vs, re->ver[re->vs[i]].name);
3788         }
3789         putchar('\n');
3790 }
3791
3792 static void
3793 dump_ver(struct readelf *re)
3794 {
3795
3796         if (re->vs_s && re->ver && re->vs)
3797                 dump_versym(re);
3798         if (re->vd_s)
3799                 dump_verdef(re, 1);
3800         if (re->vn_s)
3801                 dump_verneed(re, 1);
3802 }
3803
3804 static void
3805 search_ver(struct readelf *re)
3806 {
3807         struct section *s;
3808         Elf_Data *d;
3809         int elferr, i;
3810
3811         for (i = 0; (size_t) i < re->shnum; i++) {
3812                 s = &re->sl[i];
3813                 if (s->type == SHT_SUNW_versym)
3814                         re->vs_s = s;
3815                 if (s->type == SHT_SUNW_verneed)
3816                         re->vn_s = s;
3817                 if (s->type == SHT_SUNW_verdef)
3818                         re->vd_s = s;
3819         }
3820         if (re->vd_s)
3821                 dump_verdef(re, 0);
3822         if (re->vn_s)
3823                 dump_verneed(re, 0);
3824         if (re->vs_s && re->ver != NULL) {
3825                 (void) elf_errno();
3826                 if ((d = elf_getdata(re->vs_s->scn, NULL)) == NULL) {
3827                         elferr = elf_errno();
3828                         if (elferr != 0)
3829                                 warnx("elf_getdata failed: %s",
3830                                     elf_errmsg(elferr));
3831                         return;
3832                 }
3833                 if (d->d_size == 0)
3834                         return;
3835                 re->vs = d->d_buf;
3836                 re->vs_sz = d->d_size / sizeof(Elf32_Half);
3837         }
3838 }
3839
3840 #undef  Elf_Verdef
3841 #undef  Elf_Verdaux
3842 #undef  Elf_Verneed
3843 #undef  Elf_Vernaux
3844 #undef  SAVE_VERSION_NAME
3845
3846 /*
3847  * Elf32_Lib and Elf64_Lib are identical.
3848  */
3849 #define Elf_Lib         Elf32_Lib
3850
3851 static void
3852 dump_liblist(struct readelf *re)
3853 {
3854         struct section *s;
3855         struct tm *t;
3856         time_t ti;
3857         char tbuf[20];
3858         Elf_Data *d;
3859         Elf_Lib *lib;
3860         int i, j, k, elferr, first, len;
3861
3862         for (i = 0; (size_t) i < re->shnum; i++) {
3863                 s = &re->sl[i];
3864                 if (s->type != SHT_GNU_LIBLIST)
3865                         continue;
3866                 if (s->link >= re->shnum)
3867                         continue;
3868                 (void) elf_errno();
3869                 if ((d = elf_getdata(s->scn, NULL)) == NULL) {
3870                         elferr = elf_errno();
3871                         if (elferr != 0)
3872                                 warnx("elf_getdata failed: %s",
3873                                     elf_errmsg(elferr));
3874                         continue;
3875                 }
3876                 if (d->d_size <= 0)
3877                         continue;
3878                 lib = d->d_buf;
3879                 if (!get_ent_count(s, &len))
3880                         continue;
3881                 printf("\nLibrary list section '%s' ", s->name);
3882                 printf("contains %d entries:\n", len);
3883                 printf("%12s%24s%18s%10s%6s\n", "Library", "Time Stamp",
3884                     "Checksum", "Version", "Flags");
3885                 for (j = 0; (uint64_t) j < s->sz / s->entsize; j++) {
3886                         printf("%3d: ", j);
3887                         printf("%-20.20s ",
3888                             get_string(re, s->link, lib->l_name));
3889                         ti = lib->l_time_stamp;
3890                         t = gmtime(&ti);
3891                         snprintf(tbuf, sizeof(tbuf), "%04d-%02d-%02dT%02d:%02d"
3892                             ":%2d", t->tm_year + 1900, t->tm_mon + 1,
3893                             t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
3894                         printf("%-19.19s ", tbuf);
3895                         printf("0x%08x ", lib->l_checksum);
3896                         printf("%-7d %#x", lib->l_version, lib->l_flags);
3897                         if (lib->l_flags != 0) {
3898                                 first = 1;
3899                                 putchar('(');
3900                                 for (k = 0; l_flag[k].name != NULL; k++) {
3901                                         if ((l_flag[k].value & lib->l_flags) ==
3902                                             0)
3903                                                 continue;
3904                                         if (!first)
3905                                                 putchar(',');
3906                                         else
3907                                                 first = 0;
3908                                         printf("%s", l_flag[k].name);
3909                                 }
3910                                 putchar(')');
3911                         }
3912                         putchar('\n');
3913                         lib++;
3914                 }
3915         }
3916 }
3917
3918 #undef Elf_Lib
3919
3920 static void
3921 dump_section_groups(struct readelf *re)
3922 {
3923         struct section *s;
3924         const char *symname;
3925         Elf_Data *d;
3926         uint32_t *w;
3927         int i, j, elferr;
3928         size_t n;
3929
3930         for (i = 0; (size_t) i < re->shnum; i++) {
3931                 s = &re->sl[i];
3932                 if (s->type != SHT_GROUP)
3933                         continue;
3934                 if (s->link >= re->shnum)
3935                         continue;
3936                 (void) elf_errno();
3937                 if ((d = elf_getdata(s->scn, NULL)) == NULL) {
3938                         elferr = elf_errno();
3939                         if (elferr != 0)
3940                                 warnx("elf_getdata failed: %s",
3941                                     elf_errmsg(elferr));
3942                         continue;
3943                 }
3944                 if (d->d_size <= 0)
3945                         continue;
3946
3947                 w = d->d_buf;
3948
3949                 /* We only support COMDAT section. */
3950 #ifndef GRP_COMDAT
3951 #define GRP_COMDAT 0x1
3952 #endif
3953                 if ((*w++ & GRP_COMDAT) == 0)
3954                         return;
3955
3956                 if (s->entsize == 0)
3957                         s->entsize = 4;
3958
3959                 symname = get_symbol_name(re, s->link, s->info);
3960                 n = s->sz / s->entsize;
3961                 if (n-- < 1)
3962                         return;
3963
3964                 printf("\nCOMDAT group section [%5d] `%s' [%s] contains %ju"
3965                     " sections:\n", i, s->name, symname, (uintmax_t)n);
3966                 printf("   %-10.10s %s\n", "[Index]", "Name");
3967                 for (j = 0; (size_t) j < n; j++, w++) {
3968                         if (*w >= re->shnum) {
3969                                 warnx("invalid section index: %u", *w);
3970                                 continue;
3971                         }
3972                         printf("   [%5u]   %s\n", *w, re->sl[*w].name);
3973                 }
3974         }
3975 }
3976
3977 static uint8_t *
3978 dump_unknown_tag(uint64_t tag, uint8_t *p, uint8_t *pe)
3979 {
3980         uint64_t val;
3981
3982         /*
3983          * According to ARM EABI: For tags > 32, even numbered tags have
3984          * a ULEB128 param and odd numbered ones have NUL-terminated
3985          * string param. This rule probably also applies for tags <= 32
3986          * if the object arch is not ARM.
3987          */
3988
3989         printf("  Tag_unknown_%ju: ", (uintmax_t) tag);
3990
3991         if (tag & 1) {
3992                 printf("%s\n", (char *) p);
3993                 p += strlen((char *) p) + 1;
3994         } else {
3995                 val = _decode_uleb128(&p, pe);
3996                 printf("%ju\n", (uintmax_t) val);
3997         }
3998
3999         return (p);
4000 }
4001
4002 static uint8_t *
4003 dump_compatibility_tag(uint8_t *p, uint8_t *pe)
4004 {
4005         uint64_t val;
4006
4007         val = _decode_uleb128(&p, pe);
4008         printf("flag = %ju, vendor = %s\n", (uintmax_t) val, p);
4009         p += strlen((char *) p) + 1;
4010
4011         return (p);
4012 }
4013
4014 static void
4015 dump_arm_attributes(struct readelf *re, uint8_t *p, uint8_t *pe)
4016 {
4017         uint64_t tag, val;
4018         size_t i;
4019         int found, desc;
4020
4021         (void) re;
4022
4023         while (p < pe) {
4024                 tag = _decode_uleb128(&p, pe);
4025                 found = desc = 0;
4026                 for (i = 0; i < sizeof(aeabi_tags) / sizeof(aeabi_tags[0]);
4027                      i++) {
4028                         if (tag == aeabi_tags[i].tag) {
4029                                 found = 1;
4030                                 printf("  %s: ", aeabi_tags[i].s_tag);
4031                                 if (aeabi_tags[i].get_desc) {
4032                                         desc = 1;
4033                                         val = _decode_uleb128(&p, pe);
4034                                         printf("%s\n",
4035                                             aeabi_tags[i].get_desc(val));
4036                                 }
4037                                 break;
4038                         }
4039                         if (tag < aeabi_tags[i].tag)
4040                                 break;
4041                 }
4042                 if (!found) {
4043                         p = dump_unknown_tag(tag, p, pe);
4044                         continue;
4045                 }
4046                 if (desc)
4047                         continue;
4048
4049                 switch (tag) {
4050                 case 4:         /* Tag_CPU_raw_name */
4051                 case 5:         /* Tag_CPU_name */
4052                 case 67:        /* Tag_conformance */
4053                         printf("%s\n", (char *) p);
4054                         p += strlen((char *) p) + 1;
4055                         break;
4056                 case 32:        /* Tag_compatibility */
4057                         p = dump_compatibility_tag(p, pe);
4058                         break;
4059                 case 64:        /* Tag_nodefaults */
4060                         /* ignored, written as 0. */
4061                         (void) _decode_uleb128(&p, pe);
4062                         printf("True\n");
4063                         break;
4064                 case 65:        /* Tag_also_compatible_with */
4065                         val = _decode_uleb128(&p, pe);
4066                         /* Must be Tag_CPU_arch */
4067                         if (val != 6) {
4068                                 printf("unknown\n");
4069                                 break;
4070                         }
4071                         val = _decode_uleb128(&p, pe);
4072                         printf("%s\n", aeabi_cpu_arch(val));
4073                         /* Skip NUL terminator. */
4074                         p++;
4075                         break;
4076                 default:
4077                         putchar('\n');
4078                         break;
4079                 }
4080         }
4081 }
4082
4083 #ifndef Tag_GNU_MIPS_ABI_FP
4084 #define Tag_GNU_MIPS_ABI_FP     4
4085 #endif
4086
4087 static void
4088 dump_mips_attributes(struct readelf *re, uint8_t *p, uint8_t *pe)
4089 {
4090         uint64_t tag, val;
4091
4092         (void) re;
4093
4094         while (p < pe) {
4095                 tag = _decode_uleb128(&p, pe);
4096                 switch (tag) {
4097                 case Tag_GNU_MIPS_ABI_FP:
4098                         val = _decode_uleb128(&p, pe);
4099                         printf("  Tag_GNU_MIPS_ABI_FP: %s\n", mips_abi_fp(val));
4100                         break;
4101                 case 32:        /* Tag_compatibility */
4102                         p = dump_compatibility_tag(p, pe);
4103                         break;
4104                 default:
4105                         p = dump_unknown_tag(tag, p, pe);
4106                         break;
4107                 }
4108         }
4109 }
4110
4111 #ifndef Tag_GNU_Power_ABI_FP
4112 #define Tag_GNU_Power_ABI_FP    4
4113 #endif
4114
4115 #ifndef Tag_GNU_Power_ABI_Vector
4116 #define Tag_GNU_Power_ABI_Vector        8
4117 #endif
4118
4119 static void
4120 dump_ppc_attributes(uint8_t *p, uint8_t *pe)
4121 {
4122         uint64_t tag, val;
4123
4124         while (p < pe) {
4125                 tag = _decode_uleb128(&p, pe);
4126                 switch (tag) {
4127                 case Tag_GNU_Power_ABI_FP:
4128                         val = _decode_uleb128(&p, pe);
4129                         printf("  Tag_GNU_Power_ABI_FP: %s\n", ppc_abi_fp(val));
4130                         break;
4131                 case Tag_GNU_Power_ABI_Vector:
4132                         val = _decode_uleb128(&p, pe);
4133                         printf("  Tag_GNU_Power_ABI_Vector: %s\n",
4134                             ppc_abi_vector(val));
4135                         break;
4136                 case 32:        /* Tag_compatibility */
4137                         p = dump_compatibility_tag(p, pe);
4138                         break;
4139                 default:
4140                         p = dump_unknown_tag(tag, p, pe);
4141                         break;
4142                 }
4143         }
4144 }
4145
4146 static void
4147 dump_attributes(struct readelf *re)
4148 {
4149         struct section *s;
4150         Elf_Data *d;
4151         uint8_t *p, *pe, *sp;
4152         size_t len, seclen, nlen, sublen;
4153         uint64_t val;
4154         int tag, i, elferr;
4155
4156         for (i = 0; (size_t) i < re->shnum; i++) {
4157                 s = &re->sl[i];
4158                 if (s->type != SHT_GNU_ATTRIBUTES &&
4159                     (re->ehdr.e_machine != EM_ARM || s->type != SHT_LOPROC + 3))
4160                         continue;
4161                 (void) elf_errno();
4162                 if ((d = elf_rawdata(s->scn, NULL)) == NULL) {
4163                         elferr = elf_errno();
4164                         if (elferr != 0)
4165                                 warnx("elf_rawdata failed: %s",
4166                                     elf_errmsg(elferr));
4167                         continue;
4168                 }
4169                 if (d->d_size <= 0)
4170                         continue;
4171                 p = d->d_buf;
4172                 pe = p + d->d_size;
4173                 if (*p != 'A') {
4174                         printf("Unknown Attribute Section Format: %c\n",
4175                             (char) *p);
4176                         continue;
4177                 }
4178                 len = d->d_size - 1;
4179                 p++;
4180                 while (len > 0) {
4181                         if (len < 4) {
4182                                 warnx("truncated attribute section length");
4183                                 return;
4184                         }
4185                         seclen = re->dw_decode(&p, 4);
4186                         if (seclen > len) {
4187                                 warnx("invalid attribute section length");
4188                                 return;
4189                         }
4190                         len -= seclen;
4191                         nlen = strlen((char *) p) + 1;
4192                         if (nlen + 4 > seclen) {
4193                                 warnx("invalid attribute section name");
4194                                 return;
4195                         }
4196                         printf("Attribute Section: %s\n", (char *) p);
4197                         p += nlen;
4198                         seclen -= nlen + 4;
4199                         while (seclen > 0) {
4200                                 sp = p;
4201                                 tag = *p++;
4202                                 sublen = re->dw_decode(&p, 4);
4203                                 if (sublen > seclen) {
4204                                         warnx("invalid attribute sub-section"
4205                                             " length");
4206                                         return;
4207                                 }
4208                                 seclen -= sublen;
4209                                 printf("%s", top_tag(tag));
4210                                 if (tag == 2 || tag == 3) {
4211                                         putchar(':');
4212                                         for (;;) {
4213                                                 val = _decode_uleb128(&p, pe);
4214                                                 if (val == 0)
4215                                                         break;
4216                                                 printf(" %ju", (uintmax_t) val);
4217                                         }
4218                                 }
4219                                 putchar('\n');
4220                                 if (re->ehdr.e_machine == EM_ARM &&
4221                                     s->type == SHT_LOPROC + 3)
4222                                         dump_arm_attributes(re, p, sp + sublen);
4223                                 else if (re->ehdr.e_machine == EM_MIPS ||
4224                                     re->ehdr.e_machine == EM_MIPS_RS3_LE)
4225                                         dump_mips_attributes(re, p,
4226                                             sp + sublen);
4227                                 else if (re->ehdr.e_machine == EM_PPC)
4228                                         dump_ppc_attributes(p, sp + sublen);
4229                                 p = sp + sublen;
4230                         }
4231                 }
4232         }
4233 }
4234
4235 static void
4236 dump_mips_specific_info(struct readelf *re)
4237 {
4238         struct section *s;
4239         int i;
4240
4241         s = NULL;
4242         for (i = 0; (size_t) i < re->shnum; i++) {
4243                 s = &re->sl[i];
4244                 if (s->name != NULL && (!strcmp(s->name, ".MIPS.options") ||
4245                     (s->type == SHT_MIPS_OPTIONS))) {
4246                         dump_mips_options(re, s);
4247                 }
4248         }
4249
4250         if (s->name != NULL && (!strcmp(s->name, ".MIPS.abiflags") ||
4251             (s->type == SHT_MIPS_ABIFLAGS)))
4252                 dump_mips_abiflags(re, s);
4253
4254         /*
4255          * Dump .reginfo if present (although it will be ignored by an OS if a
4256          * .MIPS.options section is present, according to SGI mips64 spec).
4257          */
4258         for (i = 0; (size_t) i < re->shnum; i++) {
4259                 s = &re->sl[i];
4260                 if (s->name != NULL && (!strcmp(s->name, ".reginfo") ||
4261                     (s->type == SHT_MIPS_REGINFO)))
4262                         dump_mips_reginfo(re, s);
4263         }
4264 }
4265
4266 static void
4267 dump_mips_abiflags(struct readelf *re, struct section *s)
4268 {
4269         Elf_Data *d;
4270         uint8_t *p;
4271         int elferr;
4272         uint32_t isa_ext, ases, flags1, flags2;
4273         uint16_t version;
4274         uint8_t isa_level, isa_rev, gpr_size, cpr1_size, cpr2_size, fp_abi;
4275
4276         if ((d = elf_rawdata(s->scn, NULL)) == NULL) {
4277                 elferr = elf_errno();
4278                 if (elferr != 0)
4279                         warnx("elf_rawdata failed: %s",
4280                             elf_errmsg(elferr));
4281                 return;
4282         }
4283         if (d->d_size != 24) {
4284                 warnx("invalid MIPS abiflags section size");
4285                 return;
4286         }
4287
4288         p = d->d_buf;
4289         version = re->dw_decode(&p, 2);
4290         printf("MIPS ABI Flags Version: %u", version);
4291         if (version != 0) {
4292                 printf(" (unknown)\n\n");
4293                 return;
4294         }
4295         printf("\n\n");
4296
4297         isa_level = re->dw_decode(&p, 1);
4298         isa_rev = re->dw_decode(&p, 1);
4299         gpr_size = re->dw_decode(&p, 1);
4300         cpr1_size = re->dw_decode(&p, 1);
4301         cpr2_size = re->dw_decode(&p, 1);
4302         fp_abi = re->dw_decode(&p, 1);
4303         isa_ext = re->dw_decode(&p, 4);
4304         ases = re->dw_decode(&p, 4);
4305         flags1 = re->dw_decode(&p, 4);
4306         flags2 = re->dw_decode(&p, 4);
4307
4308         printf("ISA: ");
4309         if (isa_rev <= 1)
4310                 printf("MIPS%u\n", isa_level);
4311         else
4312                 printf("MIPS%ur%u\n", isa_level, isa_rev);
4313         printf("GPR size: %d\n", get_mips_register_size(gpr_size));
4314         printf("CPR1 size: %d\n", get_mips_register_size(cpr1_size));
4315         printf("CPR2 size: %d\n", get_mips_register_size(cpr2_size));
4316         printf("FP ABI: ");
4317         switch (fp_abi) {
4318         case 3:
4319                 printf("Soft float");
4320                 break;
4321         default:
4322                 printf("%u", fp_abi);
4323                 break;
4324         }
4325         printf("\nISA Extension: %u\n", isa_ext);
4326         printf("ASEs: %u\n", ases);
4327         printf("FLAGS 1: %08x\n", flags1);
4328         printf("FLAGS 2: %08x\n", flags2);
4329 }
4330
4331 static int
4332 get_mips_register_size(uint8_t flag)
4333 {
4334         switch (flag) {
4335         case 0: return 0;
4336         case 1: return 32;
4337         case 2: return 64;
4338         case 3: return 128;
4339         default: return -1;
4340         }
4341 }
4342 static void
4343 dump_mips_reginfo(struct readelf *re, struct section *s)
4344 {
4345         Elf_Data *d;
4346         int elferr, len;
4347
4348         (void) elf_errno();
4349         if ((d = elf_rawdata(s->scn, NULL)) == NULL) {
4350                 elferr = elf_errno();
4351                 if (elferr != 0)
4352                         warnx("elf_rawdata failed: %s",
4353                             elf_errmsg(elferr));
4354                 return;
4355         }
4356         if (d->d_size <= 0)
4357                 return;
4358         if (!get_ent_count(s, &len))
4359                 return;
4360
4361         printf("\nSection '%s' contains %d entries:\n", s->name, len);
4362         dump_mips_odk_reginfo(re, d->d_buf, d->d_size);
4363 }
4364
4365 static void
4366 dump_mips_options(struct readelf *re, struct section *s)
4367 {
4368         Elf_Data *d;
4369         uint32_t info;
4370         uint16_t sndx;
4371         uint8_t *p, *pe;
4372         uint8_t kind, size;
4373         int elferr;
4374
4375         (void) elf_errno();
4376         if ((d = elf_rawdata(s->scn, NULL)) == NULL) {
4377                 elferr = elf_errno();
4378                 if (elferr != 0)
4379                         warnx("elf_rawdata failed: %s",
4380                             elf_errmsg(elferr));
4381                 return;
4382         }
4383         if (d->d_size == 0)
4384                 return;
4385
4386         printf("\nSection %s contains:\n", s->name);
4387         p = d->d_buf;
4388         pe = p + d->d_size;
4389         while (p < pe) {
4390                 if (pe - p < 8) {
4391                         warnx("Truncated MIPS option header");
4392                         return;
4393                 }
4394                 kind = re->dw_decode(&p, 1);
4395                 size = re->dw_decode(&p, 1);
4396                 sndx = re->dw_decode(&p, 2);
4397                 info = re->dw_decode(&p, 4);
4398                 if (size < 8 || size - 8 > pe - p) {
4399                         warnx("Malformed MIPS option header");
4400                         return;
4401                 }
4402                 size -= 8;
4403                 switch (kind) {
4404                 case ODK_REGINFO:
4405                         dump_mips_odk_reginfo(re, p, size);
4406                         break;
4407                 case ODK_EXCEPTIONS:
4408                         printf(" EXCEPTIONS FPU_MIN: %#x\n",
4409                             info & OEX_FPU_MIN);
4410                         printf("%11.11s FPU_MAX: %#x\n", "",
4411                             info & OEX_FPU_MAX);
4412                         dump_mips_option_flags("", mips_exceptions_option,
4413                             info);
4414                         break;
4415                 case ODK_PAD:
4416                         printf(" %-10.10s section: %ju\n", "OPAD",
4417                             (uintmax_t) sndx);
4418                         dump_mips_option_flags("", mips_pad_option, info);
4419                         break;
4420                 case ODK_HWPATCH:
4421                         dump_mips_option_flags("HWPATCH", mips_hwpatch_option,
4422                             info);
4423                         break;
4424                 case ODK_HWAND:
4425                         dump_mips_option_flags("HWAND", mips_hwa_option, info);
4426                         break;
4427                 case ODK_HWOR:
4428                         dump_mips_option_flags("HWOR", mips_hwo_option, info);
4429                         break;
4430                 case ODK_FILL:
4431                         printf(" %-10.10s %#jx\n", "FILL", (uintmax_t) info);
4432                         break;
4433                 case ODK_TAGS:
4434                         printf(" %-10.10s\n", "TAGS");
4435                         break;
4436                 case ODK_GP_GROUP:
4437                         printf(" %-10.10s GP group number: %#x\n", "GP_GROUP",
4438                             info & 0xFFFF);
4439                         if (info & 0x10000)
4440                                 printf(" %-10.10s GP group is "
4441                                     "self-contained\n", "");
4442                         break;
4443                 case ODK_IDENT:
4444                         printf(" %-10.10s default GP group number: %#x\n",
4445                             "IDENT", info & 0xFFFF);
4446                         if (info & 0x10000)
4447                                 printf(" %-10.10s default GP group is "
4448                                     "self-contained\n", "");
4449                         break;
4450                 case ODK_PAGESIZE:
4451                         printf(" %-10.10s\n", "PAGESIZE");
4452                         break;
4453                 default:
4454                         break;
4455                 }
4456                 p += size;
4457         }
4458 }
4459
4460 static void
4461 dump_mips_option_flags(const char *name, struct mips_option *opt, uint64_t info)
4462 {
4463         int first;
4464
4465         first = 1;
4466         for (; opt->desc != NULL; opt++) {
4467                 if (info & opt->flag) {
4468                         printf(" %-10.10s %s\n", first ? name : "",
4469                             opt->desc);
4470                         first = 0;
4471                 }
4472         }
4473 }
4474
4475 static void
4476 dump_mips_odk_reginfo(struct readelf *re, uint8_t *p, size_t sz)
4477 {
4478         uint32_t ri_gprmask;
4479         uint32_t ri_cprmask[4];
4480         uint64_t ri_gp_value;
4481         uint8_t *pe;
4482         int i;
4483
4484         pe = p + sz;
4485         while (p < pe) {
4486                 ri_gprmask = re->dw_decode(&p, 4);
4487                 /* Skip ri_pad padding field for mips64. */
4488                 if (re->ec == ELFCLASS64)
4489                         re->dw_decode(&p, 4);
4490                 for (i = 0; i < 4; i++)
4491                         ri_cprmask[i] = re->dw_decode(&p, 4);
4492                 if (re->ec == ELFCLASS32)
4493                         ri_gp_value = re->dw_decode(&p, 4);
4494                 else
4495                         ri_gp_value = re->dw_decode(&p, 8);
4496                 printf(" %s    ", option_kind(ODK_REGINFO));
4497                 printf("ri_gprmask:    0x%08jx\n", (uintmax_t) ri_gprmask);
4498                 for (i = 0; i < 4; i++)
4499                         printf("%11.11s ri_cprmask[%d]: 0x%08jx\n", "", i,
4500                             (uintmax_t) ri_cprmask[i]);
4501                 printf("%12.12s", "");
4502                 printf("ri_gp_value:   %#jx\n", (uintmax_t) ri_gp_value);
4503         }
4504 }
4505
4506 static void
4507 dump_arch_specific_info(struct readelf *re)
4508 {
4509
4510         dump_liblist(re);
4511         dump_attributes(re);
4512
4513         switch (re->ehdr.e_machine) {
4514         case EM_MIPS:
4515         case EM_MIPS_RS3_LE:
4516                 dump_mips_specific_info(re);
4517         default:
4518                 break;
4519         }
4520 }
4521
4522 static const char *
4523 dwarf_regname(struct readelf *re, unsigned int num)
4524 {
4525         static char rx[32];
4526         const char *rn;
4527
4528         if ((rn = dwarf_reg(re->ehdr.e_machine, num)) != NULL)
4529                 return (rn);
4530
4531         snprintf(rx, sizeof(rx), "r%u", num);
4532
4533         return (rx);
4534 }
4535
4536 static void
4537 dump_dwarf_line(struct readelf *re)
4538 {
4539         struct section *s;
4540         Dwarf_Die die;
4541         Dwarf_Error de;
4542         Dwarf_Half tag, version, pointer_size;
4543         Dwarf_Unsigned offset, endoff, length, hdrlen, dirndx, mtime, fsize;
4544         Dwarf_Small minlen, defstmt, lrange, opbase, oplen;
4545         Elf_Data *d;
4546         char *pn;
4547         uint64_t address, file, line, column, isa, opsize, udelta;
4548         int64_t sdelta;
4549         uint8_t *p, *pe;
4550         int8_t lbase;
4551         int i, is_stmt, dwarf_size, elferr, ret;
4552
4553         printf("\nDump of debug contents of section .debug_line:\n");
4554
4555         s = NULL;
4556         for (i = 0; (size_t) i < re->shnum; i++) {
4557                 s = &re->sl[i];
4558                 if (s->name != NULL && !strcmp(s->name, ".debug_line"))
4559                         break;
4560         }
4561         if ((size_t) i >= re->shnum)
4562                 return;
4563
4564         (void) elf_errno();
4565         if ((d = elf_getdata(s->scn, NULL)) == NULL) {
4566                 elferr = elf_errno();
4567                 if (elferr != 0)
4568                         warnx("elf_getdata failed: %s", elf_errmsg(-1));
4569                 return;
4570         }
4571         if (d->d_size <= 0)
4572                 return;
4573
4574         while ((ret = dwarf_next_cu_header(re->dbg, NULL, NULL, NULL, NULL,
4575             NULL, &de)) ==  DW_DLV_OK) {
4576                 die = NULL;
4577                 while (dwarf_siblingof(re->dbg, die, &die, &de) == DW_DLV_OK) {
4578                         if (dwarf_tag(die, &tag, &de) != DW_DLV_OK) {
4579                                 warnx("dwarf_tag failed: %s",
4580                                     dwarf_errmsg(de));
4581                                 return;
4582                         }
4583                         /* XXX: What about DW_TAG_partial_unit? */
4584                         if (tag == DW_TAG_compile_unit)
4585                                 break;
4586                 }
4587                 if (die == NULL) {
4588                         warnx("could not find DW_TAG_compile_unit die");
4589                         return;
4590                 }
4591                 if (dwarf_attrval_unsigned(die, DW_AT_stmt_list, &offset,
4592                     &de) != DW_DLV_OK)
4593                         continue;
4594
4595                 length = re->dw_read(d, &offset, 4);
4596                 if (length == 0xffffffff) {
4597                         dwarf_size = 8;
4598                         length = re->dw_read(d, &offset, 8);
4599                 } else
4600                         dwarf_size = 4;
4601
4602                 if (length > d->d_size - offset) {
4603                         warnx("invalid .dwarf_line section");
4604                         continue;
4605                 }
4606
4607                 endoff = offset + length;
4608                 pe = (uint8_t *) d->d_buf + endoff;
4609                 version = re->dw_read(d, &offset, 2);
4610                 hdrlen = re->dw_read(d, &offset, dwarf_size);
4611                 minlen = re->dw_read(d, &offset, 1);
4612                 defstmt = re->dw_read(d, &offset, 1);
4613                 lbase = re->dw_read(d, &offset, 1);
4614                 lrange = re->dw_read(d, &offset, 1);
4615                 opbase = re->dw_read(d, &offset, 1);
4616
4617                 printf("\n");
4618                 printf("  Length:\t\t\t%ju\n", (uintmax_t) length);
4619                 printf("  DWARF version:\t\t%u\n", version);
4620                 printf("  Prologue Length:\t\t%ju\n", (uintmax_t) hdrlen);
4621                 printf("  Minimum Instruction Length:\t%u\n", minlen);
4622                 printf("  Initial value of 'is_stmt':\t%u\n", defstmt);
4623                 printf("  Line Base:\t\t\t%d\n", lbase);
4624                 printf("  Line Range:\t\t\t%u\n", lrange);
4625                 printf("  Opcode Base:\t\t\t%u\n", opbase);
4626                 (void) dwarf_get_address_size(re->dbg, &pointer_size, &de);
4627                 printf("  (Pointer size:\t\t%u)\n", pointer_size);
4628
4629                 printf("\n");
4630                 printf(" Opcodes:\n");
4631                 for (i = 1; i < opbase; i++) {
4632                         oplen = re->dw_read(d, &offset, 1);
4633                         printf("  Opcode %d has %u args\n", i, oplen);
4634                 }
4635
4636                 printf("\n");
4637                 printf(" The Directory Table:\n");
4638                 p = (uint8_t *) d->d_buf + offset;
4639                 while (*p != '\0') {
4640                         printf("  %s\n", (char *) p);
4641                         p += strlen((char *) p) + 1;
4642                 }
4643
4644                 p++;
4645                 printf("\n");
4646                 printf(" The File Name Table:\n");
4647                 printf("  Entry\tDir\tTime\tSize\tName\n");
4648                 i = 0;
4649                 while (*p != '\0') {
4650                         i++;
4651                         pn = (char *) p;
4652                         p += strlen(pn) + 1;
4653                         dirndx = _decode_uleb128(&p, pe);
4654                         mtime = _decode_uleb128(&p, pe);
4655                         fsize = _decode_uleb128(&p, pe);
4656                         printf("  %d\t%ju\t%ju\t%ju\t%s\n", i,
4657                             (uintmax_t) dirndx, (uintmax_t) mtime,
4658                             (uintmax_t) fsize, pn);
4659                 }
4660
4661 #define RESET_REGISTERS                                         \
4662         do {                                                    \
4663                 address        = 0;                             \
4664                 file           = 1;                             \
4665                 line           = 1;                             \
4666                 column         = 0;                             \
4667                 is_stmt        = defstmt;                       \
4668         } while(0)
4669
4670 #define LINE(x) (lbase + (((x) - opbase) % lrange))
4671 #define ADDRESS(x) ((((x) - opbase) / lrange) * minlen)
4672
4673                 p++;
4674                 printf("\n");
4675                 printf(" Line Number Statements:\n");
4676
4677                 RESET_REGISTERS;
4678
4679                 while (p < pe) {
4680
4681                         if (*p == 0) {
4682                                 /*
4683                                  * Extended Opcodes.
4684                                  */
4685                                 p++;
4686                                 opsize = _decode_uleb128(&p, pe);
4687                                 printf("  Extended opcode %u: ", *p);
4688                                 switch (*p) {
4689                                 case DW_LNE_end_sequence:
4690                                         p++;
4691                                         RESET_REGISTERS;
4692                                         printf("End of Sequence\n");
4693                                         break;
4694                                 case DW_LNE_set_address:
4695                                         p++;
4696                                         address = re->dw_decode(&p,
4697                                             pointer_size);
4698                                         printf("set Address to %#jx\n",
4699                                             (uintmax_t) address);
4700                                         break;
4701                                 case DW_LNE_define_file:
4702                                         p++;
4703                                         pn = (char *) p;
4704                                         p += strlen(pn) + 1;
4705                                         dirndx = _decode_uleb128(&p, pe);
4706                                         mtime = _decode_uleb128(&p, pe);
4707                                         fsize = _decode_uleb128(&p, pe);
4708                                         printf("define new file: %s\n", pn);
4709                                         break;
4710                                 default:
4711                                         /* Unrecognized extened opcodes. */
4712                                         p += opsize;
4713                                         printf("unknown opcode\n");
4714                                 }
4715                         } else if (*p > 0 && *p < opbase) {
4716                                 /*
4717                                  * Standard Opcodes.
4718                                  */
4719                                 switch(*p++) {
4720                                 case DW_LNS_copy:
4721                                         printf("  Copy\n");
4722                                         break;
4723                                 case DW_LNS_advance_pc:
4724                                         udelta = _decode_uleb128(&p, pe) *
4725                                             minlen;
4726                                         address += udelta;
4727                                         printf("  Advance PC by %ju to %#jx\n",
4728                                             (uintmax_t) udelta,
4729                                             (uintmax_t) address);
4730                                         break;
4731                                 case DW_LNS_advance_line:
4732                                         sdelta = _decode_sleb128(&p, pe);
4733                                         line += sdelta;
4734                                         printf("  Advance Line by %jd to %ju\n",
4735                                             (intmax_t) sdelta,
4736                                             (uintmax_t) line);
4737                                         break;
4738                                 case DW_LNS_set_file:
4739                                         file = _decode_uleb128(&p, pe);
4740                                         printf("  Set File to %ju\n",
4741                                             (uintmax_t) file);
4742                                         break;
4743                                 case DW_LNS_set_column:
4744                                         column = _decode_uleb128(&p, pe);
4745                                         printf("  Set Column to %ju\n",
4746                                             (uintmax_t) column);
4747                                         break;
4748                                 case DW_LNS_negate_stmt:
4749                                         is_stmt = !is_stmt;
4750                                         printf("  Set is_stmt to %d\n", is_stmt);
4751                                         break;
4752                                 case DW_LNS_set_basic_block:
4753                                         printf("  Set basic block flag\n");
4754                                         break;
4755                                 case DW_LNS_const_add_pc:
4756                                         address += ADDRESS(255);
4757                                         printf("  Advance PC by constant %ju"
4758                                             " to %#jx\n",
4759                                             (uintmax_t) ADDRESS(255),
4760                                             (uintmax_t) address);
4761                                         break;
4762                                 case DW_LNS_fixed_advance_pc:
4763                                         udelta = re->dw_decode(&p, 2);
4764                                         address += udelta;
4765                                         printf("  Advance PC by fixed value "
4766                                             "%ju to %#jx\n",
4767                                             (uintmax_t) udelta,
4768                                             (uintmax_t) address);
4769                                         break;
4770                                 case DW_LNS_set_prologue_end:
4771                                         printf("  Set prologue end flag\n");
4772                                         break;
4773                                 case DW_LNS_set_epilogue_begin:
4774                                         printf("  Set epilogue begin flag\n");
4775                                         break;
4776                                 case DW_LNS_set_isa:
4777                                         isa = _decode_uleb128(&p, pe);
4778                                         printf("  Set isa to %ju\n",
4779                                             (uintmax_t) isa);
4780                                         break;
4781                                 default:
4782                                         /* Unrecognized extended opcodes. */
4783                                         printf("  Unknown extended opcode %u\n",
4784                                             *(p - 1));
4785                                         break;
4786                                 }
4787
4788                         } else {
4789                                 /*
4790                                  * Special Opcodes.
4791                                  */
4792                                 line += LINE(*p);
4793                                 address += ADDRESS(*p);
4794                                 printf("  Special opcode %u: advance Address "
4795                                     "by %ju to %#jx and Line by %jd to %ju\n",
4796                                     *p - opbase, (uintmax_t) ADDRESS(*p),
4797                                     (uintmax_t) address, (intmax_t) LINE(*p),
4798                                     (uintmax_t) line);
4799                                 p++;
4800                         }
4801
4802
4803                 }
4804         }
4805         if (ret == DW_DLV_ERROR)
4806                 warnx("dwarf_next_cu_header: %s", dwarf_errmsg(de));
4807
4808 #undef  RESET_REGISTERS
4809 #undef  LINE
4810 #undef  ADDRESS
4811 }
4812
4813 static void
4814 dump_dwarf_line_decoded(struct readelf *re)
4815 {
4816         Dwarf_Die die;
4817         Dwarf_Line *linebuf, ln;
4818         Dwarf_Addr lineaddr;
4819         Dwarf_Signed linecount, srccount;
4820         Dwarf_Unsigned lineno, fn;
4821         Dwarf_Error de;
4822         const char *dir, *file;
4823         char **srcfiles;
4824         int i, ret;
4825
4826         printf("Decoded dump of debug contents of section .debug_line:\n\n");
4827         while ((ret = dwarf_next_cu_header(re->dbg, NULL, NULL, NULL, NULL,
4828             NULL, &de)) == DW_DLV_OK) {
4829                 if (dwarf_siblingof(re->dbg, NULL, &die, &de) != DW_DLV_OK)
4830                         continue;
4831                 if (dwarf_attrval_string(die, DW_AT_name, &file, &de) !=
4832                     DW_DLV_OK)
4833                         file = NULL;
4834                 if (dwarf_attrval_string(die, DW_AT_comp_dir, &dir, &de) !=
4835                     DW_DLV_OK)
4836                         dir = NULL;
4837                 printf("CU: ");
4838                 if (dir && file && file[0] != '/')
4839                         printf("%s/", dir);
4840                 if (file)
4841                         printf("%s", file);
4842                 putchar('\n');
4843                 printf("%-37s %11s   %s\n", "Filename", "Line Number",
4844                     "Starting Address");
4845                 if (dwarf_srclines(die, &linebuf, &linecount, &de) != DW_DLV_OK)
4846                         continue;
4847                 if (dwarf_srcfiles(die, &srcfiles, &srccount, &de) != DW_DLV_OK)
4848                         continue;
4849                 for (i = 0; i < linecount; i++) {
4850                         ln = linebuf[i];
4851                         if (dwarf_line_srcfileno(ln, &fn, &de) != DW_DLV_OK)
4852                                 continue;
4853                         if (dwarf_lineno(ln, &lineno, &de) != DW_DLV_OK)
4854                                 continue;
4855                         if (dwarf_lineaddr(ln, &lineaddr, &de) != DW_DLV_OK)
4856                                 continue;
4857                         printf("%-37s %11ju %#18jx\n",
4858                             basename(srcfiles[fn - 1]), (uintmax_t) lineno,
4859                             (uintmax_t) lineaddr);
4860                 }
4861                 putchar('\n');
4862         }
4863 }
4864
4865 static void
4866 dump_dwarf_die(struct readelf *re, Dwarf_Die die, int level)
4867 {
4868         Dwarf_Attribute *attr_list;
4869         Dwarf_Die ret_die;
4870         Dwarf_Off dieoff, cuoff, culen, attroff;
4871         Dwarf_Unsigned ate, lang, v_udata, v_sig;
4872         Dwarf_Signed attr_count, v_sdata;
4873         Dwarf_Off v_off;
4874         Dwarf_Addr v_addr;
4875         Dwarf_Half tag, attr, form;
4876         Dwarf_Block *v_block;
4877         Dwarf_Bool v_bool, is_info;
4878         Dwarf_Sig8 v_sig8;
4879         Dwarf_Error de;
4880         Dwarf_Ptr v_expr;
4881         const char *tag_str, *attr_str, *ate_str, *lang_str;
4882         char unk_tag[32], unk_attr[32];
4883         char *v_str;
4884         uint8_t *b, *p;
4885         int i, j, abc, ret;
4886
4887         if (dwarf_dieoffset(die, &dieoff, &de) != DW_DLV_OK) {
4888                 warnx("dwarf_dieoffset failed: %s", dwarf_errmsg(de));
4889                 goto cont_search;
4890         }
4891
4892         printf(" <%d><%jx>: ", level, (uintmax_t) dieoff);
4893
4894         if (dwarf_die_CU_offset_range(die, &cuoff, &culen, &de) != DW_DLV_OK) {
4895                 warnx("dwarf_die_CU_offset_range failed: %s",
4896                       dwarf_errmsg(de));
4897                 cuoff = 0;
4898         }
4899
4900         abc = dwarf_die_abbrev_code(die);
4901         if (dwarf_tag(die, &tag, &de) != DW_DLV_OK) {
4902                 warnx("dwarf_tag failed: %s", dwarf_errmsg(de));
4903                 goto cont_search;
4904         }
4905         if (dwarf_get_TAG_name(tag, &tag_str) != DW_DLV_OK) {
4906                 snprintf(unk_tag, sizeof(unk_tag), "[Unknown Tag: %#x]", tag);
4907                 tag_str = unk_tag;
4908         }
4909
4910         printf("Abbrev Number: %d (%s)\n", abc, tag_str);
4911
4912         if ((ret = dwarf_attrlist(die, &attr_list, &attr_count, &de)) !=
4913             DW_DLV_OK) {
4914                 if (ret == DW_DLV_ERROR)
4915                         warnx("dwarf_attrlist failed: %s", dwarf_errmsg(de));
4916                 goto cont_search;
4917         }
4918
4919         for (i = 0; i < attr_count; i++) {
4920                 if (dwarf_whatform(attr_list[i], &form, &de) != DW_DLV_OK) {
4921                         warnx("dwarf_whatform failed: %s", dwarf_errmsg(de));
4922                         continue;
4923                 }
4924                 if (dwarf_whatattr(attr_list[i], &attr, &de) != DW_DLV_OK) {
4925                         warnx("dwarf_whatattr failed: %s", dwarf_errmsg(de));
4926                         continue;
4927                 }
4928                 if (dwarf_get_AT_name(attr, &attr_str) != DW_DLV_OK) {
4929                         snprintf(unk_attr, sizeof(unk_attr),
4930                             "[Unknown AT: %#x]", attr);
4931                         attr_str = unk_attr;
4932                 }
4933                 if (dwarf_attroffset(attr_list[i], &attroff, &de) !=
4934                     DW_DLV_OK) {
4935                         warnx("dwarf_attroffset failed: %s", dwarf_errmsg(de));
4936                         attroff = 0;
4937                 }
4938                 printf("    <%jx>   %-18s: ", (uintmax_t) attroff, attr_str);
4939                 switch (form) {
4940                 case DW_FORM_ref_addr:
4941                 case DW_FORM_sec_offset:
4942                         if (dwarf_global_formref(attr_list[i], &v_off, &de) !=
4943                             DW_DLV_OK) {
4944                                 warnx("dwarf_global_formref failed: %s",
4945                                     dwarf_errmsg(de));
4946                                 continue;
4947                         }
4948                         if (form == DW_FORM_ref_addr)
4949                                 printf("<0x%jx>", (uintmax_t) v_off);
4950                         else
4951                                 printf("0x%jx", (uintmax_t) v_off);
4952                         break;
4953
4954                 case DW_FORM_ref1:
4955                 case DW_FORM_ref2:
4956                 case DW_FORM_ref4:
4957                 case DW_FORM_ref8:
4958                 case DW_FORM_ref_udata:
4959                         if (dwarf_formref(attr_list[i], &v_off, &de) !=
4960                             DW_DLV_OK) {
4961                                 warnx("dwarf_formref failed: %s",
4962                                     dwarf_errmsg(de));
4963                                 continue;
4964                         }
4965                         v_off += cuoff;
4966                         printf("<0x%jx>", (uintmax_t) v_off);
4967                         break;
4968
4969                 case DW_FORM_addr:
4970                         if (dwarf_formaddr(attr_list[i], &v_addr, &de) !=
4971                             DW_DLV_OK) {
4972                                 warnx("dwarf_formaddr failed: %s",
4973                                     dwarf_errmsg(de));
4974                                 continue;
4975                         }
4976                         printf("%#jx", (uintmax_t) v_addr);
4977                         break;
4978
4979                 case DW_FORM_data1:
4980                 case DW_FORM_data2:
4981                 case DW_FORM_data4:
4982                 case DW_FORM_data8:
4983                 case DW_FORM_udata:
4984                         if (dwarf_formudata(attr_list[i], &v_udata, &de) !=
4985                             DW_DLV_OK) {
4986                                 warnx("dwarf_formudata failed: %s",
4987                                     dwarf_errmsg(de));
4988                                 continue;
4989                         }
4990                         if (attr == DW_AT_high_pc)
4991                                 printf("0x%jx", (uintmax_t) v_udata);
4992                         else
4993                                 printf("%ju", (uintmax_t) v_udata);
4994                         break;
4995
4996                 case DW_FORM_sdata:
4997                         if (dwarf_formsdata(attr_list[i], &v_sdata, &de) !=
4998                             DW_DLV_OK) {
4999                                 warnx("dwarf_formudata failed: %s",
5000                                     dwarf_errmsg(de));
5001                                 continue;
5002                         }
5003                         printf("%jd", (intmax_t) v_sdata);
5004                         break;
5005
5006                 case DW_FORM_flag:
5007                         if (dwarf_formflag(attr_list[i], &v_bool, &de) !=
5008                             DW_DLV_OK) {
5009                                 warnx("dwarf_formflag failed: %s",
5010                                     dwarf_errmsg(de));
5011                                 continue;
5012                         }
5013                         printf("%jd", (intmax_t) v_bool);
5014                         break;
5015
5016                 case DW_FORM_flag_present:
5017                         putchar('1');
5018                         break;
5019
5020                 case DW_FORM_string:
5021                 case DW_FORM_strp:
5022                         if (dwarf_formstring(attr_list[i], &v_str, &de) !=
5023                             DW_DLV_OK) {
5024                                 warnx("dwarf_formstring failed: %s",
5025                                     dwarf_errmsg(de));
5026                                 continue;
5027                         }
5028                         if (form == DW_FORM_string)
5029                                 printf("%s", v_str);
5030                         else
5031                                 printf("(indirect string) %s", v_str);
5032                         break;
5033
5034                 case DW_FORM_block:
5035                 case DW_FORM_block1:
5036                 case DW_FORM_block2:
5037                 case DW_FORM_block4:
5038                         if (dwarf_formblock(attr_list[i], &v_block, &de) !=
5039                             DW_DLV_OK) {
5040                                 warnx("dwarf_formblock failed: %s",
5041                                     dwarf_errmsg(de));
5042                                 continue;
5043                         }
5044                         printf("%ju byte block:", (uintmax_t) v_block->bl_len);
5045                         b = v_block->bl_data;
5046                         for (j = 0; (Dwarf_Unsigned) j < v_block->bl_len; j++)
5047                                 printf(" %x", b[j]);
5048                         printf("\t(");
5049                         dump_dwarf_block(re, v_block->bl_data, v_block->bl_len);
5050                         putchar(')');
5051                         break;
5052
5053                 case DW_FORM_exprloc:
5054                         if (dwarf_formexprloc(attr_list[i], &v_udata, &v_expr,
5055                             &de) != DW_DLV_OK) {
5056                                 warnx("dwarf_formexprloc failed: %s",
5057                                     dwarf_errmsg(de));
5058                                 continue;
5059                         }
5060                         printf("%ju byte block:", (uintmax_t) v_udata);
5061                         b = v_expr;
5062                         for (j = 0; (Dwarf_Unsigned) j < v_udata; j++)
5063                                 printf(" %x", b[j]);
5064                         printf("\t(");
5065                         dump_dwarf_block(re, v_expr, v_udata);
5066                         putchar(')');
5067                         break;
5068
5069                 case DW_FORM_ref_sig8:
5070                         if (dwarf_formsig8(attr_list[i], &v_sig8, &de) !=
5071                             DW_DLV_OK) {
5072                                 warnx("dwarf_formsig8 failed: %s",
5073                                     dwarf_errmsg(de));
5074                                 continue;
5075                         }
5076                         p = (uint8_t *)(uintptr_t) &v_sig8.signature[0];
5077                         v_sig = re->dw_decode(&p, 8);
5078                         printf("signature: 0x%jx", (uintmax_t) v_sig);
5079                 }
5080                 switch (attr) {
5081                 case DW_AT_encoding:
5082                         if (dwarf_attrval_unsigned(die, attr, &ate, &de) !=
5083                             DW_DLV_OK)
5084                                 break;
5085                         if (dwarf_get_ATE_name(ate, &ate_str) != DW_DLV_OK)
5086                                 ate_str = "DW_ATE_UNKNOWN";
5087                         printf("\t(%s)", &ate_str[strlen("DW_ATE_")]);
5088                         break;
5089
5090                 case DW_AT_language:
5091                         if (dwarf_attrval_unsigned(die, attr, &lang, &de) !=
5092                             DW_DLV_OK)
5093                                 break;
5094                         if (dwarf_get_LANG_name(lang, &lang_str) != DW_DLV_OK)
5095                                 break;
5096                         printf("\t(%s)", &lang_str[strlen("DW_LANG_")]);
5097                         break;
5098
5099                 case DW_AT_location:
5100                 case DW_AT_string_length:
5101                 case DW_AT_return_addr:
5102                 case DW_AT_data_member_location:
5103                 case DW_AT_frame_base:
5104                 case DW_AT_segment:
5105                 case DW_AT_static_link:
5106                 case DW_AT_use_location:
5107                 case DW_AT_vtable_elem_location:
5108                         switch (form) {
5109                         case DW_FORM_data4:
5110                         case DW_FORM_data8:
5111                         case DW_FORM_sec_offset:
5112                                 printf("\t(location list)");
5113                                 break;
5114                         default:
5115                                 break;
5116                         }
5117
5118                 default:
5119                         break;
5120                 }
5121                 putchar('\n');
5122         }
5123
5124
5125 cont_search:
5126         /* Search children. */
5127         ret = dwarf_child(die, &ret_die, &de);
5128         if (ret == DW_DLV_ERROR)
5129                 warnx("dwarf_child: %s", dwarf_errmsg(de));
5130         else if (ret == DW_DLV_OK)
5131                 dump_dwarf_die(re, ret_die, level + 1);
5132
5133         /* Search sibling. */
5134         is_info = dwarf_get_die_infotypes_flag(die);
5135         ret = dwarf_siblingof_b(re->dbg, die, &ret_die, is_info, &de);
5136         if (ret == DW_DLV_ERROR)
5137                 warnx("dwarf_siblingof: %s", dwarf_errmsg(de));
5138         else if (ret == DW_DLV_OK)
5139                 dump_dwarf_die(re, ret_die, level);
5140
5141         dwarf_dealloc(re->dbg, die, DW_DLA_DIE);
5142 }
5143
5144 static void
5145 set_cu_context(struct readelf *re, Dwarf_Half psize, Dwarf_Half osize,
5146     Dwarf_Half ver)
5147 {
5148
5149         re->cu_psize = psize;
5150         re->cu_osize = osize;
5151         re->cu_ver = ver;
5152 }
5153
5154 static void
5155 dump_dwarf_info(struct readelf *re, Dwarf_Bool is_info)
5156 {
5157         struct section *s;
5158         Dwarf_Die die;
5159         Dwarf_Error de;
5160         Dwarf_Half tag, version, pointer_size, off_size;
5161         Dwarf_Off cu_offset, cu_length;
5162         Dwarf_Off aboff;
5163         Dwarf_Unsigned typeoff;
5164         Dwarf_Sig8 sig8;
5165         Dwarf_Unsigned sig;
5166         uint8_t *p;
5167         const char *sn;
5168         int i, ret;
5169
5170         sn = is_info ? ".debug_info" : ".debug_types";
5171
5172         s = NULL;
5173         for (i = 0; (size_t) i < re->shnum; i++) {
5174                 s = &re->sl[i];
5175                 if (s->name != NULL && !strcmp(s->name, sn))
5176                         break;
5177         }
5178         if ((size_t) i >= re->shnum)
5179                 return;
5180
5181         do {
5182                 printf("\nDump of debug contents of section %s:\n", sn);
5183
5184                 while ((ret = dwarf_next_cu_header_c(re->dbg, is_info, NULL,
5185                     &version, &aboff, &pointer_size, &off_size, NULL, &sig8,
5186                     &typeoff, NULL, &de)) == DW_DLV_OK) {
5187                         set_cu_context(re, pointer_size, off_size, version);
5188                         die = NULL;
5189                         while (dwarf_siblingof_b(re->dbg, die, &die, is_info,
5190                             &de) == DW_DLV_OK) {
5191                                 if (dwarf_tag(die, &tag, &de) != DW_DLV_OK) {
5192                                         warnx("dwarf_tag failed: %s",
5193                                             dwarf_errmsg(de));
5194                                         continue;
5195                                 }
5196                                 /* XXX: What about DW_TAG_partial_unit? */
5197                                 if ((is_info && tag == DW_TAG_compile_unit) ||
5198                                     (!is_info && tag == DW_TAG_type_unit))
5199                                         break;
5200                         }
5201                         if (die == NULL && is_info) {
5202                                 warnx("could not find DW_TAG_compile_unit "
5203                                     "die");
5204                                 continue;
5205                         } else if (die == NULL && !is_info) {
5206                                 warnx("could not find DW_TAG_type_unit die");
5207                                 continue;
5208                         }
5209
5210                         if (dwarf_die_CU_offset_range(die, &cu_offset,
5211                             &cu_length, &de) != DW_DLV_OK) {
5212                                 warnx("dwarf_die_CU_offset failed: %s",
5213                                     dwarf_errmsg(de));
5214                                 continue;
5215                         }
5216
5217                         cu_length -= off_size == 4 ? 4 : 12;
5218
5219                         sig = 0;
5220                         if (!is_info) {
5221                                 p = (uint8_t *)(uintptr_t) &sig8.signature[0];
5222                                 sig = re->dw_decode(&p, 8);
5223                         }
5224
5225                         printf("\n  Type Unit @ offset 0x%jx:\n",
5226                             (uintmax_t) cu_offset);
5227                         printf("    Length:\t\t%#jx (%d-bit)\n",
5228                             (uintmax_t) cu_length, off_size == 4 ? 32 : 64);
5229                         printf("    Version:\t\t%u\n", version);
5230                         printf("    Abbrev Offset:\t0x%jx\n",
5231                             (uintmax_t) aboff);
5232                         printf("    Pointer Size:\t%u\n", pointer_size);
5233                         if (!is_info) {
5234                                 printf("    Signature:\t\t0x%016jx\n",
5235                                     (uintmax_t) sig);
5236                                 printf("    Type Offset:\t0x%jx\n",
5237                                     (uintmax_t) typeoff);
5238                         }
5239
5240                         dump_dwarf_die(re, die, 0);
5241                 }
5242                 if (ret == DW_DLV_ERROR)
5243                         warnx("dwarf_next_cu_header: %s", dwarf_errmsg(de));
5244                 if (is_info)
5245                         break;
5246         } while (dwarf_next_types_section(re->dbg, &de) == DW_DLV_OK);
5247 }
5248
5249 static void
5250 dump_dwarf_abbrev(struct readelf *re)
5251 {
5252         Dwarf_Abbrev ab;
5253         Dwarf_Off aboff, atoff;
5254         Dwarf_Unsigned length, attr_count;
5255         Dwarf_Signed flag, form;
5256         Dwarf_Half tag, attr;
5257         Dwarf_Error de;
5258         const char *tag_str, *attr_str, *form_str;
5259         char unk_tag[32], unk_attr[32], unk_form[32];
5260         int i, j, ret;
5261
5262         printf("\nContents of section .debug_abbrev:\n\n");
5263
5264         while ((ret = dwarf_next_cu_header(re->dbg, NULL, NULL, &aboff,
5265             NULL, NULL, &de)) ==  DW_DLV_OK) {
5266                 printf("  Number TAG\n");
5267                 i = 0;
5268                 while ((ret = dwarf_get_abbrev(re->dbg, aboff, &ab, &length,
5269                     &attr_count, &de)) == DW_DLV_OK) {
5270                         if (length == 1) {
5271                                 dwarf_dealloc(re->dbg, ab, DW_DLA_ABBREV);
5272                                 break;
5273                         }
5274                         aboff += length;
5275                         printf("%4d", ++i);
5276                         if (dwarf_get_abbrev_tag(ab, &tag, &de) != DW_DLV_OK) {
5277                                 warnx("dwarf_get_abbrev_tag failed: %s",
5278                                     dwarf_errmsg(de));
5279                                 goto next_abbrev;
5280                         }
5281                         if (dwarf_get_TAG_name(tag, &tag_str) != DW_DLV_OK) {
5282                                 snprintf(unk_tag, sizeof(unk_tag),
5283                                     "[Unknown Tag: %#x]", tag);
5284                                 tag_str = unk_tag;
5285                         }
5286                         if (dwarf_get_abbrev_children_flag(ab, &flag, &de) !=
5287                             DW_DLV_OK) {
5288                                 warnx("dwarf_get_abbrev_children_flag failed:"
5289                                     " %s", dwarf_errmsg(de));
5290                                 goto next_abbrev;
5291                         }
5292                         printf("      %s    %s\n", tag_str,
5293                             flag ? "[has children]" : "[no children]");
5294                         for (j = 0; (Dwarf_Unsigned) j < attr_count; j++) {
5295                                 if (dwarf_get_abbrev_entry(ab, (Dwarf_Signed) j,
5296                                     &attr, &form, &atoff, &de) != DW_DLV_OK) {
5297                                         warnx("dwarf_get_abbrev_entry failed:"
5298                                             " %s", dwarf_errmsg(de));
5299                                         continue;
5300                                 }
5301                                 if (dwarf_get_AT_name(attr, &attr_str) !=
5302                                     DW_DLV_OK) {
5303                                         snprintf(unk_attr, sizeof(unk_attr),
5304                                             "[Unknown AT: %#x]", attr);
5305                                         attr_str = unk_attr;
5306                                 }
5307                                 if (dwarf_get_FORM_name(form, &form_str) !=
5308                                     DW_DLV_OK) {
5309                                         snprintf(unk_form, sizeof(unk_form),
5310                                             "[Unknown Form: %#x]",
5311                                             (Dwarf_Half) form);
5312                                         form_str = unk_form;
5313                                 }
5314                                 printf("    %-18s %s\n", attr_str, form_str);
5315                         }
5316                 next_abbrev:
5317                         dwarf_dealloc(re->dbg, ab, DW_DLA_ABBREV);
5318                 }
5319                 if (ret != DW_DLV_OK)
5320                         warnx("dwarf_get_abbrev: %s", dwarf_errmsg(de));
5321         }
5322         if (ret == DW_DLV_ERROR)
5323                 warnx("dwarf_next_cu_header: %s", dwarf_errmsg(de));
5324 }
5325
5326 static void
5327 dump_dwarf_pubnames(struct readelf *re)
5328 {
5329         struct section *s;
5330         Dwarf_Off die_off;
5331         Dwarf_Unsigned offset, length, nt_cu_offset, nt_cu_length;
5332         Dwarf_Signed cnt;
5333         Dwarf_Global *globs;
5334         Dwarf_Half nt_version;
5335         Dwarf_Error de;
5336         Elf_Data *d;
5337         char *glob_name;
5338         int i, dwarf_size, elferr;
5339
5340         printf("\nContents of the .debug_pubnames section:\n");
5341
5342         s = NULL;
5343         for (i = 0; (size_t) i < re->shnum; i++) {
5344                 s = &re->sl[i];
5345                 if (s->name != NULL && !strcmp(s->name, ".debug_pubnames"))
5346                         break;
5347         }
5348         if ((size_t) i >= re->shnum)
5349                 return;
5350
5351         (void) elf_errno();
5352         if ((d = elf_getdata(s->scn, NULL)) == NULL) {
5353                 elferr = elf_errno();
5354                 if (elferr != 0)
5355                         warnx("elf_getdata failed: %s", elf_errmsg(-1));
5356                 return;
5357         }
5358         if (d->d_size <= 0)
5359                 return;
5360
5361         /* Read in .debug_pubnames section table header. */
5362         offset = 0;
5363         length = re->dw_read(d, &offset, 4);
5364         if (length == 0xffffffff) {
5365                 dwarf_size = 8;
5366                 length = re->dw_read(d, &offset, 8);
5367         } else
5368                 dwarf_size = 4;
5369
5370         if (length > d->d_size - offset) {
5371                 warnx("invalid .dwarf_pubnames section");
5372                 return;
5373         }
5374
5375         nt_version = re->dw_read(d, &offset, 2);
5376         nt_cu_offset = re->dw_read(d, &offset, dwarf_size);
5377         nt_cu_length = re->dw_read(d, &offset, dwarf_size);
5378         printf("  Length:\t\t\t\t%ju\n", (uintmax_t) length);
5379         printf("  Version:\t\t\t\t%u\n", nt_version);
5380         printf("  Offset into .debug_info section:\t%ju\n",
5381             (uintmax_t) nt_cu_offset);
5382         printf("  Size of area in .debug_info section:\t%ju\n",
5383             (uintmax_t) nt_cu_length);
5384
5385         if (dwarf_get_globals(re->dbg, &globs, &cnt, &de) != DW_DLV_OK) {
5386                 warnx("dwarf_get_globals failed: %s", dwarf_errmsg(de));
5387                 return;
5388         }
5389
5390         printf("\n    Offset      Name\n");
5391         for (i = 0; i < cnt; i++) {
5392                 if (dwarf_globname(globs[i], &glob_name, &de) != DW_DLV_OK) {
5393                         warnx("dwarf_globname failed: %s", dwarf_errmsg(de));
5394                         continue;
5395                 }
5396                 if (dwarf_global_die_offset(globs[i], &die_off, &de) !=
5397                     DW_DLV_OK) {
5398                         warnx("dwarf_global_die_offset failed: %s",
5399                             dwarf_errmsg(de));
5400                         continue;
5401                 }
5402                 printf("    %-11ju %s\n", (uintmax_t) die_off, glob_name);
5403         }
5404 }
5405
5406 static void
5407 dump_dwarf_aranges(struct readelf *re)
5408 {
5409         struct section *s;
5410         Dwarf_Arange *aranges;
5411         Dwarf_Addr start;
5412         Dwarf_Unsigned offset, length, as_cu_offset;
5413         Dwarf_Off die_off;
5414         Dwarf_Signed cnt;
5415         Dwarf_Half as_version, as_addrsz, as_segsz;
5416         Dwarf_Error de;
5417         Elf_Data *d;
5418         int i, dwarf_size, elferr;
5419
5420         printf("\nContents of section .debug_aranges:\n");
5421
5422         s = NULL;
5423         for (i = 0; (size_t) i < re->shnum; i++) {
5424                 s = &re->sl[i];
5425                 if (s->name != NULL && !strcmp(s->name, ".debug_aranges"))
5426                         break;
5427         }
5428         if ((size_t) i >= re->shnum)
5429                 return;
5430
5431         (void) elf_errno();
5432         if ((d = elf_getdata(s->scn, NULL)) == NULL) {
5433                 elferr = elf_errno();
5434                 if (elferr != 0)
5435                         warnx("elf_getdata failed: %s", elf_errmsg(-1));
5436                 return;
5437         }
5438         if (d->d_size <= 0)
5439                 return;
5440
5441         /* Read in the .debug_aranges section table header. */
5442         offset = 0;
5443         length = re->dw_read(d, &offset, 4);
5444         if (length == 0xffffffff) {
5445                 dwarf_size = 8;
5446                 length = re->dw_read(d, &offset, 8);
5447         } else
5448                 dwarf_size = 4;
5449
5450         if (length > d->d_size - offset) {
5451                 warnx("invalid .dwarf_aranges section");
5452                 return;
5453         }
5454
5455         as_version = re->dw_read(d, &offset, 2);
5456         as_cu_offset = re->dw_read(d, &offset, dwarf_size);
5457         as_addrsz = re->dw_read(d, &offset, 1);
5458         as_segsz = re->dw_read(d, &offset, 1);
5459
5460         printf("  Length:\t\t\t%ju\n", (uintmax_t) length);
5461         printf("  Version:\t\t\t%u\n", as_version);
5462         printf("  Offset into .debug_info:\t%ju\n", (uintmax_t) as_cu_offset);
5463         printf("  Pointer Size:\t\t\t%u\n", as_addrsz);
5464         printf("  Segment Size:\t\t\t%u\n", as_segsz);
5465
5466         if (dwarf_get_aranges(re->dbg, &aranges, &cnt, &de) != DW_DLV_OK) {
5467                 warnx("dwarf_get_aranges failed: %s", dwarf_errmsg(de));
5468                 return;
5469         }
5470
5471         printf("\n    Address  Length\n");
5472         for (i = 0; i < cnt; i++) {
5473                 if (dwarf_get_arange_info(aranges[i], &start, &length,
5474                     &die_off, &de) != DW_DLV_OK) {
5475                         warnx("dwarf_get_arange_info failed: %s",
5476                             dwarf_errmsg(de));
5477                         continue;
5478                 }
5479                 printf("    %08jx %ju\n", (uintmax_t) start,
5480                     (uintmax_t) length);
5481         }
5482 }
5483
5484 static void
5485 dump_dwarf_ranges_foreach(struct readelf *re, Dwarf_Die die, Dwarf_Addr base)
5486 {
5487         Dwarf_Attribute *attr_list;
5488         Dwarf_Ranges *ranges;
5489         Dwarf_Die ret_die;
5490         Dwarf_Error de;
5491         Dwarf_Addr base0;
5492         Dwarf_Half attr;
5493         Dwarf_Signed attr_count, cnt;
5494         Dwarf_Unsigned off, bytecnt;
5495         int i, j, ret;
5496
5497         if ((ret = dwarf_attrlist(die, &attr_list, &attr_count, &de)) !=
5498             DW_DLV_OK) {
5499                 if (ret == DW_DLV_ERROR)
5500                         warnx("dwarf_attrlist failed: %s", dwarf_errmsg(de));
5501                 goto cont_search;
5502         }
5503
5504         for (i = 0; i < attr_count; i++) {
5505                 if (dwarf_whatattr(attr_list[i], &attr, &de) != DW_DLV_OK) {
5506                         warnx("dwarf_whatattr failed: %s", dwarf_errmsg(de));
5507                         continue;
5508                 }
5509                 if (attr != DW_AT_ranges)
5510                         continue;
5511                 if (dwarf_formudata(attr_list[i], &off, &de) != DW_DLV_OK) {
5512                         warnx("dwarf_formudata failed: %s", dwarf_errmsg(de));
5513                         continue;
5514                 }
5515                 if (dwarf_get_ranges(re->dbg, (Dwarf_Off) off, &ranges, &cnt,
5516                     &bytecnt, &de) != DW_DLV_OK)
5517                         continue;
5518                 base0 = base;
5519                 for (j = 0; j < cnt; j++) {
5520                         printf("    %08jx ", (uintmax_t) off);
5521                         if (ranges[j].dwr_type == DW_RANGES_END) {
5522                                 printf("%s\n", "<End of list>");
5523                                 continue;
5524                         } else if (ranges[j].dwr_type ==
5525                             DW_RANGES_ADDRESS_SELECTION) {
5526                                 base0 = ranges[j].dwr_addr2;
5527                                 continue;
5528                         }
5529                         if (re->ec == ELFCLASS32)
5530                                 printf("%08jx %08jx\n",
5531                                     (uintmax_t) (ranges[j].dwr_addr1 + base0),
5532                                     (uintmax_t) (ranges[j].dwr_addr2 + base0));
5533                         else
5534                                 printf("%016jx %016jx\n",
5535                                     (uintmax_t) (ranges[j].dwr_addr1 + base0),
5536                                     (uintmax_t) (ranges[j].dwr_addr2 + base0));
5537                 }
5538         }
5539
5540 cont_search:
5541         /* Search children. */
5542         ret = dwarf_child(die, &ret_die, &de);
5543         if (ret == DW_DLV_ERROR)
5544                 warnx("dwarf_child: %s", dwarf_errmsg(de));
5545         else if (ret == DW_DLV_OK)
5546                 dump_dwarf_ranges_foreach(re, ret_die, base);
5547
5548         /* Search sibling. */
5549         ret = dwarf_siblingof(re->dbg, die, &ret_die, &de);
5550         if (ret == DW_DLV_ERROR)
5551                 warnx("dwarf_siblingof: %s", dwarf_errmsg(de));
5552         else if (ret == DW_DLV_OK)
5553                 dump_dwarf_ranges_foreach(re, ret_die, base);
5554 }
5555
5556 static void
5557 dump_dwarf_ranges(struct readelf *re)
5558 {
5559         Dwarf_Ranges *ranges;
5560         Dwarf_Die die;
5561         Dwarf_Signed cnt;
5562         Dwarf_Unsigned bytecnt;
5563         Dwarf_Half tag;
5564         Dwarf_Error de;
5565         Dwarf_Unsigned lowpc;
5566         int ret;
5567
5568         if (dwarf_get_ranges(re->dbg, 0, &ranges, &cnt, &bytecnt, &de) !=
5569             DW_DLV_OK)
5570                 return;
5571
5572         printf("Contents of the .debug_ranges section:\n\n");
5573         if (re->ec == ELFCLASS32)
5574                 printf("    %-8s %-8s %s\n", "Offset", "Begin", "End");
5575         else
5576                 printf("    %-8s %-16s %s\n", "Offset", "Begin", "End");
5577
5578         while ((ret = dwarf_next_cu_header(re->dbg, NULL, NULL, NULL, NULL,
5579             NULL, &de)) == DW_DLV_OK) {
5580                 die = NULL;
5581                 if (dwarf_siblingof(re->dbg, die, &die, &de) != DW_DLV_OK)
5582                         continue;
5583                 if (dwarf_tag(die, &tag, &de) != DW_DLV_OK) {
5584                         warnx("dwarf_tag failed: %s", dwarf_errmsg(de));
5585                         continue;
5586                 }
5587                 /* XXX: What about DW_TAG_partial_unit? */
5588                 lowpc = 0;
5589                 if (tag == DW_TAG_compile_unit) {
5590                         if (dwarf_attrval_unsigned(die, DW_AT_low_pc, &lowpc,
5591                             &de) != DW_DLV_OK)
5592                                 lowpc = 0;
5593                 }
5594
5595                 dump_dwarf_ranges_foreach(re, die, (Dwarf_Addr) lowpc);
5596         }
5597         putchar('\n');
5598 }
5599
5600 static void
5601 dump_dwarf_macinfo(struct readelf *re)
5602 {
5603         Dwarf_Unsigned offset;
5604         Dwarf_Signed cnt;
5605         Dwarf_Macro_Details *md;
5606         Dwarf_Error de;
5607         const char *mi_str;
5608         char unk_mi[32];
5609         int i;
5610
5611 #define _MAX_MACINFO_ENTRY      65535
5612
5613         printf("\nContents of section .debug_macinfo:\n\n");
5614
5615         offset = 0;
5616         while (dwarf_get_macro_details(re->dbg, offset, _MAX_MACINFO_ENTRY,
5617             &cnt, &md, &de) == DW_DLV_OK) {
5618                 for (i = 0; i < cnt; i++) {
5619                         offset = md[i].dmd_offset + 1;
5620                         if (md[i].dmd_type == 0)
5621                                 break;
5622                         if (dwarf_get_MACINFO_name(md[i].dmd_type, &mi_str) !=
5623                             DW_DLV_OK) {
5624                                 snprintf(unk_mi, sizeof(unk_mi),
5625                                     "[Unknown MACINFO: %#x]", md[i].dmd_type);
5626                                 mi_str = unk_mi;
5627                         }
5628                         printf(" %s", mi_str);
5629                         switch (md[i].dmd_type) {
5630                         case DW_MACINFO_define:
5631                         case DW_MACINFO_undef:
5632                                 printf(" - lineno : %jd macro : %s\n",
5633                                     (intmax_t) md[i].dmd_lineno,
5634                                     md[i].dmd_macro);
5635                                 break;
5636                         case DW_MACINFO_start_file:
5637                                 printf(" - lineno : %jd filenum : %jd\n",
5638                                     (intmax_t) md[i].dmd_lineno,
5639                                     (intmax_t) md[i].dmd_fileindex);
5640                                 break;
5641                         default:
5642                                 putchar('\n');
5643                                 break;
5644                         }
5645                 }
5646         }
5647
5648 #undef  _MAX_MACINFO_ENTRY
5649 }
5650
5651 static void
5652 dump_dwarf_frame_inst(struct readelf *re, Dwarf_Cie cie, uint8_t *insts,
5653     Dwarf_Unsigned len, Dwarf_Unsigned caf, Dwarf_Signed daf, Dwarf_Addr pc,
5654     Dwarf_Debug dbg)
5655 {
5656         Dwarf_Frame_Op *oplist;
5657         Dwarf_Signed opcnt, delta;
5658         Dwarf_Small op;
5659         Dwarf_Error de;
5660         const char *op_str;
5661         char unk_op[32];
5662         int i;
5663
5664         if (dwarf_expand_frame_instructions(cie, insts, len, &oplist,
5665             &opcnt, &de) != DW_DLV_OK) {
5666                 warnx("dwarf_expand_frame_instructions failed: %s",
5667                     dwarf_errmsg(de));
5668                 return;
5669         }
5670
5671         for (i = 0; i < opcnt; i++) {
5672                 if (oplist[i].fp_base_op != 0)
5673                         op = oplist[i].fp_base_op << 6;
5674                 else
5675                         op = oplist[i].fp_extended_op;
5676                 if (dwarf_get_CFA_name(op, &op_str) != DW_DLV_OK) {
5677                         snprintf(unk_op, sizeof(unk_op), "[Unknown CFA: %#x]",
5678                             op);
5679                         op_str = unk_op;
5680                 }
5681                 printf("  %s", op_str);
5682                 switch (op) {
5683                 case DW_CFA_advance_loc:
5684                         delta = oplist[i].fp_offset * caf;
5685                         pc += delta;
5686                         printf(": %ju to %08jx", (uintmax_t) delta,
5687                             (uintmax_t) pc);
5688                         break;
5689                 case DW_CFA_offset:
5690                 case DW_CFA_offset_extended:
5691                 case DW_CFA_offset_extended_sf:
5692                         delta = oplist[i].fp_offset * daf;
5693                         printf(": r%u (%s) at cfa%+jd", oplist[i].fp_register,
5694                             dwarf_regname(re, oplist[i].fp_register),
5695                             (intmax_t) delta);
5696                         break;
5697                 case DW_CFA_restore:
5698                         printf(": r%u (%s)", oplist[i].fp_register,
5699                             dwarf_regname(re, oplist[i].fp_register));
5700                         break;
5701                 case DW_CFA_set_loc:
5702                         pc = oplist[i].fp_offset;
5703                         printf(": to %08jx", (uintmax_t) pc);
5704                         break;
5705                 case DW_CFA_advance_loc1:
5706                 case DW_CFA_advance_loc2:
5707                 case DW_CFA_advance_loc4:
5708                         pc += oplist[i].fp_offset;
5709                         printf(": %jd to %08jx", (intmax_t) oplist[i].fp_offset,
5710                             (uintmax_t) pc);
5711                         break;
5712                 case DW_CFA_def_cfa:
5713                         printf(": r%u (%s) ofs %ju", oplist[i].fp_register,
5714                             dwarf_regname(re, oplist[i].fp_register),
5715                             (uintmax_t) oplist[i].fp_offset);
5716                         break;
5717                 case DW_CFA_def_cfa_sf:
5718                         printf(": r%u (%s) ofs %jd", oplist[i].fp_register,
5719                             dwarf_regname(re, oplist[i].fp_register),
5720                             (intmax_t) (oplist[i].fp_offset * daf));
5721                         break;
5722                 case DW_CFA_def_cfa_register:
5723                         printf(": r%u (%s)", oplist[i].fp_register,
5724                             dwarf_regname(re, oplist[i].fp_register));
5725                         break;
5726                 case DW_CFA_def_cfa_offset:
5727                         printf(": %ju", (uintmax_t) oplist[i].fp_offset);
5728                         break;
5729                 case DW_CFA_def_cfa_offset_sf:
5730                         printf(": %jd", (intmax_t) (oplist[i].fp_offset * daf));
5731                         break;
5732                 default:
5733                         break;
5734                 }
5735                 putchar('\n');
5736         }
5737
5738         dwarf_dealloc(dbg, oplist, DW_DLA_FRAME_BLOCK);
5739 }
5740
5741 static char *
5742 get_regoff_str(struct readelf *re, Dwarf_Half reg, Dwarf_Addr off)
5743 {
5744         static char rs[16];
5745
5746         if (reg == DW_FRAME_UNDEFINED_VAL || reg == DW_FRAME_REG_INITIAL_VALUE)
5747                 snprintf(rs, sizeof(rs), "%c", 'u');
5748         else if (reg == DW_FRAME_CFA_COL)
5749                 snprintf(rs, sizeof(rs), "c%+jd", (intmax_t) off);
5750         else
5751                 snprintf(rs, sizeof(rs), "%s%+jd", dwarf_regname(re, reg),
5752                     (intmax_t) off);
5753
5754         return (rs);
5755 }
5756
5757 static int
5758 dump_dwarf_frame_regtable(struct readelf *re, Dwarf_Fde fde, Dwarf_Addr pc,
5759     Dwarf_Unsigned func_len, Dwarf_Half cie_ra)
5760 {
5761         Dwarf_Regtable rt;
5762         Dwarf_Addr row_pc, end_pc, pre_pc, cur_pc;
5763         Dwarf_Error de;
5764         char *vec;
5765         int i;
5766
5767 #define BIT_SET(v, n) (v[(n)>>3] |= 1U << ((n) & 7))
5768 #define BIT_CLR(v, n) (v[(n)>>3] &= ~(1U << ((n) & 7)))
5769 #define BIT_ISSET(v, n) (v[(n)>>3] & (1U << ((n) & 7)))
5770 #define RT(x) rt.rules[(x)]
5771
5772         vec = calloc((DW_REG_TABLE_SIZE + 7) / 8, 1);
5773         if (vec == NULL)
5774                 err(EXIT_FAILURE, "calloc failed");
5775
5776         pre_pc = ~((Dwarf_Addr) 0);
5777         cur_pc = pc;
5778         end_pc = pc + func_len;
5779         for (; cur_pc < end_pc; cur_pc++) {
5780                 if (dwarf_get_fde_info_for_all_regs(fde, cur_pc, &rt, &row_pc,
5781                     &de) != DW_DLV_OK) {
5782                         warnx("dwarf_get_fde_info_for_all_regs failed: %s\n",
5783                             dwarf_errmsg(de));
5784                         return (-1);
5785                 }
5786                 if (row_pc == pre_pc)
5787                         continue;
5788                 pre_pc = row_pc;
5789                 for (i = 1; i < DW_REG_TABLE_SIZE; i++) {
5790                         if (rt.rules[i].dw_regnum != DW_FRAME_REG_INITIAL_VALUE)
5791                                 BIT_SET(vec, i);
5792                 }
5793         }
5794
5795         printf("   LOC   CFA      ");
5796         for (i = 1; i < DW_REG_TABLE_SIZE; i++) {
5797                 if (BIT_ISSET(vec, i)) {
5798                         if ((Dwarf_Half) i == cie_ra)
5799                                 printf("ra   ");
5800                         else
5801                                 printf("%-5s",
5802                                     dwarf_regname(re, (unsigned int) i));
5803                 }
5804         }
5805         putchar('\n');
5806
5807         pre_pc = ~((Dwarf_Addr) 0);
5808         cur_pc = pc;
5809         end_pc = pc + func_len;
5810         for (; cur_pc < end_pc; cur_pc++) {
5811                 if (dwarf_get_fde_info_for_all_regs(fde, cur_pc, &rt, &row_pc,
5812                     &de) != DW_DLV_OK) {
5813                         warnx("dwarf_get_fde_info_for_all_regs failed: %s\n",
5814                             dwarf_errmsg(de));
5815                         return (-1);
5816                 }
5817                 if (row_pc == pre_pc)
5818                         continue;
5819                 pre_pc = row_pc;
5820                 printf("%08jx ", (uintmax_t) row_pc);
5821                 printf("%-8s ", get_regoff_str(re, RT(0).dw_regnum,
5822                     RT(0).dw_offset));
5823                 for (i = 1; i < DW_REG_TABLE_SIZE; i++) {
5824                         if (BIT_ISSET(vec, i)) {
5825                                 printf("%-5s", get_regoff_str(re,
5826                                     RT(i).dw_regnum, RT(i).dw_offset));
5827                         }
5828                 }
5829                 putchar('\n');
5830         }
5831
5832         free(vec);
5833
5834         return (0);
5835
5836 #undef  BIT_SET
5837 #undef  BIT_CLR
5838 #undef  BIT_ISSET
5839 #undef  RT
5840 }
5841
5842 static void
5843 dump_dwarf_frame_section(struct readelf *re, struct section *s, int alt)
5844 {
5845         Dwarf_Cie *cie_list, cie, pre_cie;
5846         Dwarf_Fde *fde_list, fde;
5847         Dwarf_Off cie_offset, fde_offset;
5848         Dwarf_Unsigned cie_length, fde_instlen;
5849         Dwarf_Unsigned cie_caf, cie_daf, cie_instlen, func_len, fde_length;
5850         Dwarf_Signed cie_count, fde_count, cie_index;
5851         Dwarf_Addr low_pc;
5852         Dwarf_Half cie_ra;
5853         Dwarf_Small cie_version;
5854         Dwarf_Ptr fde_addr, fde_inst, cie_inst;
5855         char *cie_aug, c;
5856         int i, eh_frame;
5857         Dwarf_Error de;
5858
5859         printf("\nThe section %s contains:\n\n", s->name);
5860
5861         if (!strcmp(s->name, ".debug_frame")) {
5862                 eh_frame = 0;
5863                 if (dwarf_get_fde_list(re->dbg, &cie_list, &cie_count,
5864                     &fde_list, &fde_count, &de) != DW_DLV_OK) {
5865                         warnx("dwarf_get_fde_list failed: %s",
5866                             dwarf_errmsg(de));
5867                         return;
5868                 }
5869         } else if (!strcmp(s->name, ".eh_frame")) {
5870                 eh_frame = 1;
5871                 if (dwarf_get_fde_list_eh(re->dbg, &cie_list, &cie_count,
5872                     &fde_list, &fde_count, &de) != DW_DLV_OK) {
5873                         warnx("dwarf_get_fde_list_eh failed: %s",
5874                             dwarf_errmsg(de));
5875                         return;
5876                 }
5877         } else
5878                 return;
5879
5880         pre_cie = NULL;
5881         for (i = 0; i < fde_count; i++) {
5882                 if (dwarf_get_fde_n(fde_list, i, &fde, &de) != DW_DLV_OK) {
5883                         warnx("dwarf_get_fde_n failed: %s", dwarf_errmsg(de));
5884                         continue;
5885                 }
5886                 if (dwarf_get_cie_of_fde(fde, &cie, &de) != DW_DLV_OK) {
5887                         warnx("dwarf_get_fde_n failed: %s", dwarf_errmsg(de));
5888                         continue;
5889                 }
5890                 if (dwarf_get_fde_range(fde, &low_pc, &func_len, &fde_addr,
5891                     &fde_length, &cie_offset, &cie_index, &fde_offset,
5892                     &de) != DW_DLV_OK) {
5893                         warnx("dwarf_get_fde_range failed: %s",
5894                             dwarf_errmsg(de));
5895                         continue;
5896                 }
5897                 if (dwarf_get_fde_instr_bytes(fde, &fde_inst, &fde_instlen,
5898                     &de) != DW_DLV_OK) {
5899                         warnx("dwarf_get_fde_instr_bytes failed: %s",
5900                             dwarf_errmsg(de));
5901                         continue;
5902                 }
5903                 if (pre_cie == NULL || cie != pre_cie) {
5904                         pre_cie = cie;
5905                         if (dwarf_get_cie_info(cie, &cie_length, &cie_version,
5906                             &cie_aug, &cie_caf, &cie_daf, &cie_ra,
5907                             &cie_inst, &cie_instlen, &de) != DW_DLV_OK) {
5908                                 warnx("dwarf_get_cie_info failed: %s",
5909                                     dwarf_errmsg(de));
5910                                 continue;
5911                         }
5912                         printf("%08jx %08jx %8.8jx CIE",
5913                             (uintmax_t) cie_offset,
5914                             (uintmax_t) cie_length,
5915                             (uintmax_t) (eh_frame ? 0 : ~0U));
5916                         if (!alt) {
5917                                 putchar('\n');
5918                                 printf("  Version:\t\t\t%u\n", cie_version);
5919                                 printf("  Augmentation:\t\t\t\"");
5920                                 while ((c = *cie_aug++) != '\0')
5921                                         putchar(c);
5922                                 printf("\"\n");
5923                                 printf("  Code alignment factor:\t%ju\n",
5924                                     (uintmax_t) cie_caf);
5925                                 printf("  Data alignment factor:\t%jd\n",
5926                                     (intmax_t) cie_daf);
5927                                 printf("  Return address column:\t%ju\n",
5928                                     (uintmax_t) cie_ra);
5929                                 putchar('\n');
5930                                 dump_dwarf_frame_inst(re, cie, cie_inst,
5931                                     cie_instlen, cie_caf, cie_daf, 0,
5932                                     re->dbg);
5933                                 putchar('\n');
5934                         } else {
5935                                 printf(" \"");
5936                                 while ((c = *cie_aug++) != '\0')
5937                                         putchar(c);
5938                                 putchar('"');
5939                                 printf(" cf=%ju df=%jd ra=%ju\n",
5940                                     (uintmax_t) cie_caf,
5941                                     (uintmax_t) cie_daf,
5942                                     (uintmax_t) cie_ra);
5943                                 dump_dwarf_frame_regtable(re, fde, low_pc, 1,
5944                                     cie_ra);
5945                                 putchar('\n');
5946                         }
5947                 }
5948                 printf("%08jx %08jx %08jx FDE cie=%08jx pc=%08jx..%08jx\n",
5949                     (uintmax_t) fde_offset, (uintmax_t) fde_length,
5950                     (uintmax_t) cie_offset,
5951                     (uintmax_t) (eh_frame ? fde_offset + 4 - cie_offset :
5952                         cie_offset),
5953                     (uintmax_t) low_pc, (uintmax_t) (low_pc + func_len));
5954                 if (!alt)
5955                         dump_dwarf_frame_inst(re, cie, fde_inst, fde_instlen,
5956                             cie_caf, cie_daf, low_pc, re->dbg);
5957                 else
5958                         dump_dwarf_frame_regtable(re, fde, low_pc, func_len,
5959                             cie_ra);
5960                 putchar('\n');
5961         }
5962 }
5963
5964 static void
5965 dump_dwarf_frame(struct readelf *re, int alt)
5966 {
5967         struct section *s;
5968         int i;
5969
5970         (void) dwarf_set_frame_cfa_value(re->dbg, DW_FRAME_CFA_COL);
5971
5972         for (i = 0; (size_t) i < re->shnum; i++) {
5973                 s = &re->sl[i];
5974                 if (s->name != NULL && (!strcmp(s->name, ".debug_frame") ||
5975                     !strcmp(s->name, ".eh_frame")))
5976                         dump_dwarf_frame_section(re, s, alt);
5977         }
5978 }
5979
5980 static void
5981 dump_dwarf_str(struct readelf *re)
5982 {
5983         struct section *s;
5984         Elf_Data *d;
5985         unsigned char *p;
5986         int elferr, end, i, j;
5987
5988         printf("\nContents of section .debug_str:\n");
5989
5990         s = NULL;
5991         for (i = 0; (size_t) i < re->shnum; i++) {
5992                 s = &re->sl[i];
5993                 if (s->name != NULL && !strcmp(s->name, ".debug_str"))
5994                         break;
5995         }
5996         if ((size_t) i >= re->shnum)
5997                 return;
5998
5999         (void) elf_errno();
6000         if ((d = elf_getdata(s->scn, NULL)) == NULL) {
6001                 elferr = elf_errno();
6002                 if (elferr != 0)
6003                         warnx("elf_getdata failed: %s", elf_errmsg(-1));
6004                 return;
6005         }
6006         if (d->d_size <= 0)
6007                 return;
6008
6009         for (i = 0, p = d->d_buf; (size_t) i < d->d_size; i += 16) {
6010                 printf("  0x%08x", (unsigned int) i);
6011                 if ((size_t) i + 16 > d->d_size)
6012                         end = d->d_size;
6013                 else
6014                         end = i + 16;
6015                 for (j = i; j < i + 16; j++) {
6016                         if ((j - i) % 4 == 0)
6017                                 putchar(' ');
6018                         if (j >= end) {
6019                                 printf("  ");
6020                                 continue;
6021                         }
6022                         printf("%02x", (uint8_t) p[j]);
6023                 }
6024                 putchar(' ');
6025                 for (j = i; j < end; j++) {
6026                         if (isprint(p[j]))
6027                                 putchar(p[j]);
6028                         else if (p[j] == 0)
6029                                 putchar('.');
6030                         else
6031                                 putchar(' ');
6032                 }
6033                 putchar('\n');
6034         }
6035 }
6036
6037 struct loc_at {
6038         Dwarf_Attribute la_at;
6039         Dwarf_Unsigned la_off;
6040         Dwarf_Unsigned la_lowpc;
6041         Dwarf_Half la_cu_psize;
6042         Dwarf_Half la_cu_osize;
6043         Dwarf_Half la_cu_ver;
6044         TAILQ_ENTRY(loc_at) la_next;
6045 };
6046
6047 static TAILQ_HEAD(, loc_at) lalist = TAILQ_HEAD_INITIALIZER(lalist);
6048
6049 static void
6050 search_loclist_at(struct readelf *re, Dwarf_Die die, Dwarf_Unsigned lowpc)
6051 {
6052         Dwarf_Attribute *attr_list;
6053         Dwarf_Die ret_die;
6054         Dwarf_Unsigned off;
6055         Dwarf_Off ref;
6056         Dwarf_Signed attr_count;
6057         Dwarf_Half attr, form;
6058         Dwarf_Bool is_info;
6059         Dwarf_Error de;
6060         struct loc_at *la, *nla;
6061         int i, ret;
6062
6063         is_info = dwarf_get_die_infotypes_flag(die);
6064
6065         if ((ret = dwarf_attrlist(die, &attr_list, &attr_count, &de)) !=
6066             DW_DLV_OK) {
6067                 if (ret == DW_DLV_ERROR)
6068                         warnx("dwarf_attrlist failed: %s", dwarf_errmsg(de));
6069                 goto cont_search;
6070         }
6071         for (i = 0; i < attr_count; i++) {
6072                 if (dwarf_whatattr(attr_list[i], &attr, &de) != DW_DLV_OK) {
6073                         warnx("dwarf_whatattr failed: %s", dwarf_errmsg(de));
6074                         continue;
6075                 }
6076                 if (attr != DW_AT_location &&
6077                     attr != DW_AT_string_length &&
6078                     attr != DW_AT_return_addr &&
6079                     attr != DW_AT_data_member_location &&
6080                     attr != DW_AT_frame_base &&
6081                     attr != DW_AT_segment &&
6082                     attr != DW_AT_static_link &&
6083                     attr != DW_AT_use_location &&
6084                     attr != DW_AT_vtable_elem_location)
6085                         continue;
6086                 if (dwarf_whatform(attr_list[i], &form, &de) != DW_DLV_OK) {
6087                         warnx("dwarf_whatform failed: %s", dwarf_errmsg(de));
6088                         continue;
6089                 }
6090                 if (form == DW_FORM_data4 || form == DW_FORM_data8) {
6091                         if (dwarf_formudata(attr_list[i], &off, &de) !=
6092                             DW_DLV_OK) {
6093                                 warnx("dwarf_formudata failed: %s",
6094                                     dwarf_errmsg(de));
6095                                 continue;
6096                         }
6097                 } else if (form == DW_FORM_sec_offset) {
6098                         if (dwarf_global_formref(attr_list[i], &ref, &de) !=
6099                             DW_DLV_OK) {
6100                                 warnx("dwarf_global_formref failed: %s",
6101                                     dwarf_errmsg(de));
6102                                 continue;
6103                         }
6104                         off = ref;
6105                 } else
6106                         continue;
6107
6108                 TAILQ_FOREACH(la, &lalist, la_next) {
6109                         if (off == la->la_off)
6110                                 break;
6111                         if (off < la->la_off) {
6112                                 if ((nla = malloc(sizeof(*nla))) == NULL)
6113                                         err(EXIT_FAILURE, "malloc failed");
6114                                 nla->la_at = attr_list[i];
6115                                 nla->la_off = off;
6116                                 nla->la_lowpc = lowpc;
6117                                 nla->la_cu_psize = re->cu_psize;
6118                                 nla->la_cu_osize = re->cu_osize;
6119                                 nla->la_cu_ver = re->cu_ver;
6120                                 TAILQ_INSERT_BEFORE(la, nla, la_next);
6121                                 break;
6122                         }
6123                 }
6124                 if (la == NULL) {
6125                         if ((nla = malloc(sizeof(*nla))) == NULL)
6126                                 err(EXIT_FAILURE, "malloc failed");
6127                         nla->la_at = attr_list[i];
6128                         nla->la_off = off;
6129                         nla->la_lowpc = lowpc;
6130                         nla->la_cu_psize = re->cu_psize;
6131                         nla->la_cu_osize = re->cu_osize;
6132                         nla->la_cu_ver = re->cu_ver;
6133                         TAILQ_INSERT_TAIL(&lalist, nla, la_next);
6134                 }
6135         }
6136
6137 cont_search:
6138         /* Search children. */
6139         ret = dwarf_child(die, &ret_die, &de);
6140         if (ret == DW_DLV_ERROR)
6141                 warnx("dwarf_child: %s", dwarf_errmsg(de));
6142         else if (ret == DW_DLV_OK)
6143                 search_loclist_at(re, ret_die, lowpc);
6144
6145         /* Search sibling. */
6146         ret = dwarf_siblingof_b(re->dbg, die, &ret_die, is_info, &de);
6147         if (ret == DW_DLV_ERROR)
6148                 warnx("dwarf_siblingof: %s", dwarf_errmsg(de));
6149         else if (ret == DW_DLV_OK)
6150                 search_loclist_at(re, ret_die, lowpc);
6151 }
6152
6153 static void
6154 dump_dwarf_loc(struct readelf *re, Dwarf_Loc *lr)
6155 {
6156         const char *op_str;
6157         char unk_op[32];
6158         uint8_t *b, n;
6159         int i;
6160
6161         if (dwarf_get_OP_name(lr->lr_atom, &op_str) !=
6162             DW_DLV_OK) {
6163                 snprintf(unk_op, sizeof(unk_op),
6164                     "[Unknown OP: %#x]", lr->lr_atom);
6165                 op_str = unk_op;
6166         }
6167
6168         printf("%s", op_str);
6169
6170         switch (lr->lr_atom) {
6171         case DW_OP_reg0:
6172         case DW_OP_reg1:
6173         case DW_OP_reg2:
6174         case DW_OP_reg3:
6175         case DW_OP_reg4:
6176         case DW_OP_reg5:
6177         case DW_OP_reg6:
6178         case DW_OP_reg7:
6179         case DW_OP_reg8:
6180         case DW_OP_reg9:
6181         case DW_OP_reg10:
6182         case DW_OP_reg11:
6183         case DW_OP_reg12:
6184         case DW_OP_reg13:
6185         case DW_OP_reg14:
6186         case DW_OP_reg15:
6187         case DW_OP_reg16:
6188         case DW_OP_reg17:
6189         case DW_OP_reg18:
6190         case DW_OP_reg19:
6191         case DW_OP_reg20:
6192         case DW_OP_reg21:
6193         case DW_OP_reg22:
6194         case DW_OP_reg23:
6195         case DW_OP_reg24:
6196         case DW_OP_reg25:
6197         case DW_OP_reg26:
6198         case DW_OP_reg27:
6199         case DW_OP_reg28:
6200         case DW_OP_reg29:
6201         case DW_OP_reg30:
6202         case DW_OP_reg31:
6203                 printf(" (%s)", dwarf_regname(re, lr->lr_atom - DW_OP_reg0));
6204                 break;
6205
6206         case DW_OP_deref:
6207         case DW_OP_lit0:
6208         case DW_OP_lit1:
6209         case DW_OP_lit2:
6210         case DW_OP_lit3:
6211         case DW_OP_lit4:
6212         case DW_OP_lit5:
6213         case DW_OP_lit6:
6214         case DW_OP_lit7:
6215         case DW_OP_lit8:
6216         case DW_OP_lit9:
6217         case DW_OP_lit10:
6218         case DW_OP_lit11:
6219         case DW_OP_lit12:
6220         case DW_OP_lit13:
6221         case DW_OP_lit14:
6222         case DW_OP_lit15:
6223         case DW_OP_lit16:
6224         case DW_OP_lit17:
6225         case DW_OP_lit18:
6226         case DW_OP_lit19:
6227         case DW_OP_lit20:
6228         case DW_OP_lit21:
6229         case DW_OP_lit22:
6230         case DW_OP_lit23:
6231         case DW_OP_lit24:
6232         case DW_OP_lit25:
6233         case DW_OP_lit26:
6234         case DW_OP_lit27:
6235         case DW_OP_lit28:
6236         case DW_OP_lit29:
6237         case DW_OP_lit30:
6238         case DW_OP_lit31:
6239         case DW_OP_dup:
6240         case DW_OP_drop:
6241         case DW_OP_over:
6242         case DW_OP_swap:
6243         case DW_OP_rot:
6244         case DW_OP_xderef:
6245         case DW_OP_abs:
6246         case DW_OP_and:
6247         case DW_OP_div:
6248         case DW_OP_minus:
6249         case DW_OP_mod:
6250         case DW_OP_mul:
6251         case DW_OP_neg:
6252         case DW_OP_not:
6253         case DW_OP_or:
6254         case DW_OP_plus:
6255         case DW_OP_shl:
6256         case DW_OP_shr:
6257         case DW_OP_shra:
6258         case DW_OP_xor:
6259         case DW_OP_eq:
6260         case DW_OP_ge:
6261         case DW_OP_gt:
6262         case DW_OP_le:
6263         case DW_OP_lt:
6264         case DW_OP_ne:
6265         case DW_OP_nop:
6266         case DW_OP_push_object_address:
6267         case DW_OP_form_tls_address:
6268         case DW_OP_call_frame_cfa:
6269         case DW_OP_stack_value:
6270         case DW_OP_GNU_push_tls_address:
6271         case DW_OP_GNU_uninit:
6272                 break;
6273
6274         case DW_OP_const1u:
6275         case DW_OP_pick:
6276         case DW_OP_deref_size:
6277         case DW_OP_xderef_size:
6278         case DW_OP_const2u:
6279         case DW_OP_bra:
6280         case DW_OP_skip:
6281         case DW_OP_const4u:
6282         case DW_OP_const8u:
6283         case DW_OP_constu:
6284         case DW_OP_plus_uconst:
6285         case DW_OP_regx:
6286         case DW_OP_piece:
6287                 printf(": %ju", (uintmax_t)
6288                     lr->lr_number);
6289                 break;
6290
6291         case DW_OP_const1s:
6292         case DW_OP_const2s:
6293         case DW_OP_const4s:
6294         case DW_OP_const8s:
6295         case DW_OP_consts:
6296                 printf(": %jd", (intmax_t)
6297                     lr->lr_number);
6298                 break;
6299
6300         case DW_OP_breg0:
6301         case DW_OP_breg1:
6302         case DW_OP_breg2:
6303         case DW_OP_breg3:
6304         case DW_OP_breg4:
6305         case DW_OP_breg5:
6306         case DW_OP_breg6:
6307         case DW_OP_breg7:
6308         case DW_OP_breg8:
6309         case DW_OP_breg9:
6310         case DW_OP_breg10:
6311         case DW_OP_breg11:
6312         case DW_OP_breg12:
6313         case DW_OP_breg13:
6314         case DW_OP_breg14:
6315         case DW_OP_breg15:
6316         case DW_OP_breg16:
6317         case DW_OP_breg17:
6318         case DW_OP_breg18:
6319         case DW_OP_breg19:
6320         case DW_OP_breg20:
6321         case DW_OP_breg21:
6322         case DW_OP_breg22:
6323         case DW_OP_breg23:
6324         case DW_OP_breg24:
6325         case DW_OP_breg25:
6326         case DW_OP_breg26:
6327         case DW_OP_breg27:
6328         case DW_OP_breg28:
6329         case DW_OP_breg29:
6330         case DW_OP_breg30:
6331         case DW_OP_breg31:
6332                 printf(" (%s): %jd",
6333                     dwarf_regname(re, lr->lr_atom - DW_OP_breg0),
6334                     (intmax_t) lr->lr_number);
6335                 break;
6336
6337         case DW_OP_fbreg:
6338                 printf(": %jd", (intmax_t)
6339                     lr->lr_number);
6340                 break;
6341
6342         case DW_OP_bregx:
6343                 printf(": %ju (%s) %jd",
6344                     (uintmax_t) lr->lr_number,
6345                     dwarf_regname(re, (unsigned int) lr->lr_number),
6346                     (intmax_t) lr->lr_number2);
6347                 break;
6348
6349         case DW_OP_addr:
6350         case DW_OP_GNU_encoded_addr:
6351                 printf(": %#jx", (uintmax_t)
6352                     lr->lr_number);
6353                 break;
6354
6355         case DW_OP_GNU_implicit_pointer:
6356                 printf(": <0x%jx> %jd", (uintmax_t) lr->lr_number,
6357                     (intmax_t) lr->lr_number2);
6358                 break;
6359
6360         case DW_OP_implicit_value:
6361                 printf(": %ju byte block:", (uintmax_t) lr->lr_number);
6362                 b = (uint8_t *)(uintptr_t) lr->lr_number2;
6363                 for (i = 0; (Dwarf_Unsigned) i < lr->lr_number; i++)
6364                         printf(" %x", b[i]);
6365                 break;
6366
6367         case DW_OP_GNU_entry_value:
6368                 printf(": (");
6369                 dump_dwarf_block(re, (uint8_t *)(uintptr_t) lr->lr_number2,
6370                     lr->lr_number);
6371                 putchar(')');
6372                 break;
6373
6374         case DW_OP_GNU_const_type:
6375                 printf(": <0x%jx> ", (uintmax_t) lr->lr_number);
6376                 b = (uint8_t *)(uintptr_t) lr->lr_number2;
6377                 n = *b;
6378                 for (i = 1; (uint8_t) i < n; i++)
6379                         printf(" %x", b[i]);
6380                 break;
6381
6382         case DW_OP_GNU_regval_type:
6383                 printf(": %ju (%s) <0x%jx>", (uintmax_t) lr->lr_number,
6384                     dwarf_regname(re, (unsigned int) lr->lr_number),
6385                     (uintmax_t) lr->lr_number2);
6386                 break;
6387
6388         case DW_OP_GNU_convert:
6389         case DW_OP_GNU_deref_type:
6390         case DW_OP_GNU_parameter_ref:
6391         case DW_OP_GNU_reinterpret:
6392                 printf(": <0x%jx>", (uintmax_t) lr->lr_number);
6393                 break;
6394
6395         default:
6396                 break;
6397         }
6398 }
6399
6400 static void
6401 dump_dwarf_block(struct readelf *re, uint8_t *b, Dwarf_Unsigned len)
6402 {
6403         Dwarf_Locdesc *llbuf;
6404         Dwarf_Signed lcnt;
6405         Dwarf_Error de;
6406         int i;
6407
6408         if (dwarf_loclist_from_expr_b(re->dbg, b, len, re->cu_psize,
6409             re->cu_osize, re->cu_ver, &llbuf, &lcnt, &de) != DW_DLV_OK) {
6410                 warnx("dwarf_loclist_form_expr_b: %s", dwarf_errmsg(de));
6411                 return;
6412         }
6413
6414         for (i = 0; (Dwarf_Half) i < llbuf->ld_cents; i++) {
6415                 dump_dwarf_loc(re, &llbuf->ld_s[i]);
6416                 if (i < llbuf->ld_cents - 1)
6417                         printf("; ");
6418         }
6419
6420         dwarf_dealloc(re->dbg, llbuf->ld_s, DW_DLA_LOC_BLOCK);
6421         dwarf_dealloc(re->dbg, llbuf, DW_DLA_LOCDESC);
6422 }
6423
6424 static void
6425 dump_dwarf_loclist(struct readelf *re)
6426 {
6427         Dwarf_Die die;
6428         Dwarf_Locdesc **llbuf;
6429         Dwarf_Unsigned lowpc;
6430         Dwarf_Signed lcnt;
6431         Dwarf_Half tag, version, pointer_size, off_size;
6432         Dwarf_Error de;
6433         struct loc_at *la;
6434         int i, j, ret, has_content;
6435
6436         /* Search .debug_info section. */
6437         while ((ret = dwarf_next_cu_header_b(re->dbg, NULL, &version, NULL,
6438             &pointer_size, &off_size, NULL, NULL, &de)) == DW_DLV_OK) {
6439                 set_cu_context(re, pointer_size, off_size, version);
6440                 die = NULL;
6441                 if (dwarf_siblingof(re->dbg, die, &die, &de) != DW_DLV_OK)
6442                         continue;
6443                 if (dwarf_tag(die, &tag, &de) != DW_DLV_OK) {
6444                         warnx("dwarf_tag failed: %s", dwarf_errmsg(de));
6445                         continue;
6446                 }
6447                 /* XXX: What about DW_TAG_partial_unit? */
6448                 lowpc = 0;
6449                 if (tag == DW_TAG_compile_unit) {
6450                         if (dwarf_attrval_unsigned(die, DW_AT_low_pc,
6451                             &lowpc, &de) != DW_DLV_OK)
6452                                 lowpc = 0;
6453                 }
6454
6455                 /* Search attributes for reference to .debug_loc section. */
6456                 search_loclist_at(re, die, lowpc);
6457         }
6458         if (ret == DW_DLV_ERROR)
6459                 warnx("dwarf_next_cu_header: %s", dwarf_errmsg(de));
6460
6461         /* Search .debug_types section. */
6462         do {
6463                 while ((ret = dwarf_next_cu_header_c(re->dbg, 0, NULL,
6464                     &version, NULL, &pointer_size, &off_size, NULL, NULL,
6465                     NULL, NULL, &de)) == DW_DLV_OK) {
6466                         set_cu_context(re, pointer_size, off_size, version);
6467                         die = NULL;
6468                         if (dwarf_siblingof(re->dbg, die, &die, &de) !=
6469                             DW_DLV_OK)
6470                                 continue;
6471                         if (dwarf_tag(die, &tag, &de) != DW_DLV_OK) {
6472                                 warnx("dwarf_tag failed: %s",
6473                                     dwarf_errmsg(de));
6474                                 continue;
6475                         }
6476
6477                         lowpc = 0;
6478                         if (tag == DW_TAG_type_unit) {
6479                                 if (dwarf_attrval_unsigned(die, DW_AT_low_pc,
6480                                     &lowpc, &de) != DW_DLV_OK)
6481                                         lowpc = 0;
6482                         }
6483
6484                         /*
6485                          * Search attributes for reference to .debug_loc
6486                          * section.
6487                          */
6488                         search_loclist_at(re, die, lowpc);
6489                 }
6490                 if (ret == DW_DLV_ERROR)
6491                         warnx("dwarf_next_cu_header: %s", dwarf_errmsg(de));
6492         } while (dwarf_next_types_section(re->dbg, &de) == DW_DLV_OK);
6493
6494         if (TAILQ_EMPTY(&lalist))
6495                 return;
6496
6497         has_content = 0;
6498         TAILQ_FOREACH(la, &lalist, la_next) {
6499                 if ((ret = dwarf_loclist_n(la->la_at, &llbuf, &lcnt, &de)) !=
6500                     DW_DLV_OK) {
6501                         if (ret != DW_DLV_NO_ENTRY)
6502                                 warnx("dwarf_loclist_n failed: %s",
6503                                     dwarf_errmsg(de));
6504                         continue;
6505                 }
6506                 if (!has_content) {
6507                         has_content = 1;
6508                         printf("\nContents of section .debug_loc:\n");
6509                         printf("    Offset   Begin    End      Expression\n");
6510                 }
6511                 set_cu_context(re, la->la_cu_psize, la->la_cu_osize,
6512                     la->la_cu_ver);
6513                 for (i = 0; i < lcnt; i++) {
6514                         printf("    %8.8jx ", (uintmax_t) la->la_off);
6515                         if (llbuf[i]->ld_lopc == 0 && llbuf[i]->ld_hipc == 0) {
6516                                 printf("<End of list>\n");
6517                                 continue;
6518                         }
6519
6520                         /* TODO: handle base selection entry. */
6521
6522                         printf("%8.8jx %8.8jx ",
6523                             (uintmax_t) (la->la_lowpc + llbuf[i]->ld_lopc),
6524                             (uintmax_t) (la->la_lowpc + llbuf[i]->ld_hipc));
6525
6526                         putchar('(');
6527                         for (j = 0; (Dwarf_Half) j < llbuf[i]->ld_cents; j++) {
6528                                 dump_dwarf_loc(re, &llbuf[i]->ld_s[j]);
6529                                 if (j < llbuf[i]->ld_cents - 1)
6530                                         printf("; ");
6531                         }
6532                         putchar(')');
6533
6534                         if (llbuf[i]->ld_lopc == llbuf[i]->ld_hipc)
6535                                 printf(" (start == end)");
6536                         putchar('\n');
6537                 }
6538                 for (i = 0; i < lcnt; i++) {
6539                         dwarf_dealloc(re->dbg, llbuf[i]->ld_s,
6540                             DW_DLA_LOC_BLOCK);
6541                         dwarf_dealloc(re->dbg, llbuf[i], DW_DLA_LOCDESC);
6542                 }
6543                 dwarf_dealloc(re->dbg, llbuf, DW_DLA_LIST);
6544         }
6545
6546         if (!has_content)
6547                 printf("\nSection '.debug_loc' has no debugging data.\n");
6548 }
6549
6550 /*
6551  * Retrieve a string using string table section index and the string offset.
6552  */
6553 static const char*
6554 get_string(struct readelf *re, int strtab, size_t off)
6555 {
6556         const char *name;
6557
6558         if ((name = elf_strptr(re->elf, strtab, off)) == NULL)
6559                 return ("");
6560
6561         return (name);
6562 }
6563
6564 /*
6565  * Retrieve the name of a symbol using the section index of the symbol
6566  * table and the index of the symbol within that table.
6567  */
6568 static const char *
6569 get_symbol_name(struct readelf *re, int symtab, int i)
6570 {
6571         struct section  *s;
6572         const char      *name;
6573         GElf_Sym         sym;
6574         Elf_Data        *data;
6575         int              elferr;
6576
6577         s = &re->sl[symtab];
6578         if (s->type != SHT_SYMTAB && s->type != SHT_DYNSYM)
6579                 return ("");
6580         (void) elf_errno();
6581         if ((data = elf_getdata(s->scn, NULL)) == NULL) {
6582                 elferr = elf_errno();
6583                 if (elferr != 0)
6584                         warnx("elf_getdata failed: %s", elf_errmsg(elferr));
6585                 return ("");
6586         }
6587         if (gelf_getsym(data, i, &sym) != &sym)
6588                 return ("");
6589         /* Return section name for STT_SECTION symbol. */
6590         if (GELF_ST_TYPE(sym.st_info) == STT_SECTION) {
6591                 if (sym.st_shndx < re->shnum &&
6592                     re->sl[sym.st_shndx].name != NULL)
6593                         return (re->sl[sym.st_shndx].name);
6594                 return ("");
6595         }
6596         if (s->link >= re->shnum ||
6597             (name = elf_strptr(re->elf, s->link, sym.st_name)) == NULL)
6598                 return ("");
6599
6600         return (name);
6601 }
6602
6603 static uint64_t
6604 get_symbol_value(struct readelf *re, int symtab, int i)
6605 {
6606         struct section  *s;
6607         GElf_Sym         sym;
6608         Elf_Data        *data;
6609         int              elferr;
6610
6611         s = &re->sl[symtab];
6612         if (s->type != SHT_SYMTAB && s->type != SHT_DYNSYM)
6613                 return (0);
6614         (void) elf_errno();
6615         if ((data = elf_getdata(s->scn, NULL)) == NULL) {
6616                 elferr = elf_errno();
6617                 if (elferr != 0)
6618                         warnx("elf_getdata failed: %s", elf_errmsg(elferr));
6619                 return (0);
6620         }
6621         if (gelf_getsym(data, i, &sym) != &sym)
6622                 return (0);
6623
6624         return (sym.st_value);
6625 }
6626
6627 static void
6628 hex_dump(struct readelf *re)
6629 {
6630         struct section *s;
6631         Elf_Data *d;
6632         uint8_t *buf;
6633         size_t sz, nbytes;
6634         uint64_t addr;
6635         int elferr, i, j;
6636
6637         for (i = 1; (size_t) i < re->shnum; i++) {
6638                 s = &re->sl[i];
6639                 if (find_dumpop(re, (size_t) i, s->name, HEX_DUMP, -1) == NULL)
6640                         continue;
6641                 (void) elf_errno();
6642                 if ((d = elf_getdata(s->scn, NULL)) == NULL &&
6643                     (d = elf_rawdata(s->scn, NULL)) == NULL) {
6644                         elferr = elf_errno();
6645                         if (elferr != 0)
6646                                 warnx("elf_getdata failed: %s",
6647                                     elf_errmsg(elferr));
6648                         continue;
6649                 }
6650                 (void) elf_errno();
6651                 if (d->d_size <= 0 || d->d_buf == NULL) {
6652                         printf("\nSection '%s' has no data to dump.\n",
6653                             s->name);
6654                         continue;
6655                 }
6656                 buf = d->d_buf;
6657                 sz = d->d_size;
6658                 addr = s->addr;
6659                 printf("\nHex dump of section '%s':\n", s->name);
6660                 while (sz > 0) {
6661                         printf("  0x%8.8jx ", (uintmax_t)addr);
6662                         nbytes = sz > 16? 16 : sz;
6663                         for (j = 0; j < 16; j++) {
6664                                 if ((size_t)j < nbytes)
6665                                         printf("%2.2x", buf[j]);
6666                                 else
6667                                         printf("  ");
6668                                 if ((j & 3) == 3)
6669                                         printf(" ");
6670                         }
6671                         for (j = 0; (size_t)j < nbytes; j++) {
6672                                 if (isprint(buf[j]))
6673                                         printf("%c", buf[j]);
6674                                 else
6675                                         printf(".");
6676                         }
6677                         printf("\n");
6678                         buf += nbytes;
6679                         addr += nbytes;
6680                         sz -= nbytes;
6681                 }
6682         }
6683 }
6684
6685 static void
6686 str_dump(struct readelf *re)
6687 {
6688         struct section *s;
6689         Elf_Data *d;
6690         unsigned char *start, *end, *buf_end;
6691         unsigned int len;
6692         int i, j, elferr, found;
6693
6694         for (i = 1; (size_t) i < re->shnum; i++) {
6695                 s = &re->sl[i];
6696                 if (find_dumpop(re, (size_t) i, s->name, STR_DUMP, -1) == NULL)
6697                         continue;
6698                 (void) elf_errno();
6699                 if ((d = elf_getdata(s->scn, NULL)) == NULL &&
6700                     (d = elf_rawdata(s->scn, NULL)) == NULL) {
6701                         elferr = elf_errno();
6702                         if (elferr != 0)
6703                                 warnx("elf_getdata failed: %s",
6704                                     elf_errmsg(elferr));
6705                         continue;
6706                 }
6707                 (void) elf_errno();
6708                 if (d->d_size <= 0 || d->d_buf == NULL) {
6709                         printf("\nSection '%s' has no data to dump.\n",
6710                             s->name);
6711                         continue;
6712                 }
6713                 buf_end = (unsigned char *) d->d_buf + d->d_size;
6714                 start = (unsigned char *) d->d_buf;
6715                 found = 0;
6716                 printf("\nString dump of section '%s':\n", s->name);
6717                 for (;;) {
6718                         while (start < buf_end && !isprint(*start))
6719                                 start++;
6720                         if (start >= buf_end)
6721                                 break;
6722                         end = start + 1;
6723                         while (end < buf_end && isprint(*end))
6724                                 end++;
6725                         printf("  [%6lx]  ",
6726                             (long) (start - (unsigned char *) d->d_buf));
6727                         len = end - start;
6728                         for (j = 0; (unsigned int) j < len; j++)
6729                                 putchar(start[j]);
6730                         putchar('\n');
6731                         found = 1;
6732                         if (end >= buf_end)
6733                                 break;
6734                         start = end + 1;
6735                 }
6736                 if (!found)
6737                         printf("  No strings found in this section.");
6738                 putchar('\n');
6739         }
6740 }
6741
6742 static void
6743 load_sections(struct readelf *re)
6744 {
6745         struct section  *s;
6746         const char      *name;
6747         Elf_Scn         *scn;
6748         GElf_Shdr        sh;
6749         size_t           shstrndx, ndx;
6750         int              elferr;
6751
6752         /* Allocate storage for internal section list. */
6753         if (!elf_getshnum(re->elf, &re->shnum)) {
6754                 warnx("elf_getshnum failed: %s", elf_errmsg(-1));
6755                 return;
6756         }
6757         if (re->sl != NULL)
6758                 free(re->sl);
6759         if ((re->sl = calloc(re->shnum, sizeof(*re->sl))) == NULL)
6760                 err(EXIT_FAILURE, "calloc failed");
6761
6762         /* Get the index of .shstrtab section. */
6763         if (!elf_getshstrndx(re->elf, &shstrndx)) {
6764                 warnx("elf_getshstrndx failed: %s", elf_errmsg(-1));
6765                 return;
6766         }
6767
6768         if ((scn = elf_getscn(re->elf, 0)) == NULL)
6769                 return;
6770
6771         (void) elf_errno();
6772         do {
6773                 if (gelf_getshdr(scn, &sh) == NULL) {
6774                         warnx("gelf_getshdr failed: %s", elf_errmsg(-1));
6775                         (void) elf_errno();
6776                         continue;
6777                 }
6778                 if ((name = elf_strptr(re->elf, shstrndx, sh.sh_name)) == NULL) {
6779                         (void) elf_errno();
6780                         name = "<no-name>";
6781                 }
6782                 if ((ndx = elf_ndxscn(scn)) == SHN_UNDEF) {
6783                         if ((elferr = elf_errno()) != 0) {
6784                                 warnx("elf_ndxscn failed: %s",
6785                                     elf_errmsg(elferr));
6786                                 continue;
6787                         }
6788                 }
6789                 if (ndx >= re->shnum) {
6790                         warnx("section index of '%s' out of range", name);
6791                         continue;
6792                 }
6793                 if (sh.sh_link >= re->shnum)
6794                         warnx("section link %llu of '%s' out of range",
6795                             (unsigned long long)sh.sh_link, name);
6796                 s = &re->sl[ndx];
6797                 s->name = name;
6798                 s->scn = scn;
6799                 s->off = sh.sh_offset;
6800                 s->sz = sh.sh_size;
6801                 s->entsize = sh.sh_entsize;
6802                 s->align = sh.sh_addralign;
6803                 s->type = sh.sh_type;
6804                 s->flags = sh.sh_flags;
6805                 s->addr = sh.sh_addr;
6806                 s->link = sh.sh_link;
6807                 s->info = sh.sh_info;
6808         } while ((scn = elf_nextscn(re->elf, scn)) != NULL);
6809         elferr = elf_errno();
6810         if (elferr != 0)
6811                 warnx("elf_nextscn failed: %s", elf_errmsg(elferr));
6812 }
6813
6814 static void
6815 unload_sections(struct readelf *re)
6816 {
6817
6818         if (re->sl != NULL) {
6819                 free(re->sl);
6820                 re->sl = NULL;
6821         }
6822         re->shnum = 0;
6823         re->vd_s = NULL;
6824         re->vn_s = NULL;
6825         re->vs_s = NULL;
6826         re->vs = NULL;
6827         re->vs_sz = 0;
6828         if (re->ver != NULL) {
6829                 free(re->ver);
6830                 re->ver = NULL;
6831                 re->ver_sz = 0;
6832         }
6833 }
6834
6835 static void
6836 dump_elf(struct readelf *re)
6837 {
6838
6839         /* Fetch ELF header. No need to continue if it fails. */
6840         if (gelf_getehdr(re->elf, &re->ehdr) == NULL) {
6841                 warnx("gelf_getehdr failed: %s", elf_errmsg(-1));
6842                 return;
6843         }
6844         if ((re->ec = gelf_getclass(re->elf)) == ELFCLASSNONE) {
6845                 warnx("gelf_getclass failed: %s", elf_errmsg(-1));
6846                 return;
6847         }
6848         if (re->ehdr.e_ident[EI_DATA] == ELFDATA2MSB) {
6849                 re->dw_read = _read_msb;
6850                 re->dw_decode = _decode_msb;
6851         } else {
6852                 re->dw_read = _read_lsb;
6853                 re->dw_decode = _decode_lsb;
6854         }
6855
6856         if (re->options & ~RE_H)
6857                 load_sections(re);
6858         if ((re->options & RE_VV) || (re->options & RE_S))
6859                 search_ver(re);
6860         if (re->options & RE_H)
6861                 dump_ehdr(re);
6862         if (re->options & RE_L)
6863                 dump_phdr(re);
6864         if (re->options & RE_SS)
6865                 dump_shdr(re);
6866         if (re->options & RE_G)
6867                 dump_section_groups(re);
6868         if (re->options & RE_D)
6869                 dump_dynamic(re);
6870         if (re->options & RE_R)
6871                 dump_reloc(re);
6872         if (re->options & RE_S)
6873                 dump_symtabs(re);
6874         if (re->options & RE_N)
6875                 dump_notes(re);
6876         if (re->options & RE_II)
6877                 dump_hash(re);
6878         if (re->options & RE_X)
6879                 hex_dump(re);
6880         if (re->options & RE_P)
6881                 str_dump(re);
6882         if (re->options & RE_VV)
6883                 dump_ver(re);
6884         if (re->options & RE_AA)
6885                 dump_arch_specific_info(re);
6886         if (re->options & RE_W)
6887                 dump_dwarf(re);
6888         if (re->options & ~RE_H)
6889                 unload_sections(re);
6890 }
6891
6892 static void
6893 dump_dwarf(struct readelf *re)
6894 {
6895         struct loc_at *la, *_la;
6896         Dwarf_Error de;
6897         int error;
6898
6899         if (dwarf_elf_init(re->elf, DW_DLC_READ, NULL, NULL, &re->dbg, &de)) {
6900                 if ((error = dwarf_errno(de)) != DW_DLE_DEBUG_INFO_NULL)
6901                         errx(EXIT_FAILURE, "dwarf_elf_init failed: %s",
6902                             dwarf_errmsg(de));
6903                 return;
6904         }
6905
6906         if (re->dop & DW_A)
6907                 dump_dwarf_abbrev(re);
6908         if (re->dop & DW_L)
6909                 dump_dwarf_line(re);
6910         if (re->dop & DW_LL)
6911                 dump_dwarf_line_decoded(re);
6912         if (re->dop & DW_I) {
6913                 dump_dwarf_info(re, 0);
6914                 dump_dwarf_info(re, 1);
6915         }
6916         if (re->dop & DW_P)
6917                 dump_dwarf_pubnames(re);
6918         if (re->dop & DW_R)
6919                 dump_dwarf_aranges(re);
6920         if (re->dop & DW_RR)
6921                 dump_dwarf_ranges(re);
6922         if (re->dop & DW_M)
6923                 dump_dwarf_macinfo(re);
6924         if (re->dop & DW_F)
6925                 dump_dwarf_frame(re, 0);
6926         else if (re->dop & DW_FF)
6927                 dump_dwarf_frame(re, 1);
6928         if (re->dop & DW_S)
6929                 dump_dwarf_str(re);
6930         if (re->dop & DW_O)
6931                 dump_dwarf_loclist(re);
6932
6933         TAILQ_FOREACH_SAFE(la, &lalist, la_next, _la) {
6934                 TAILQ_REMOVE(&lalist, la, la_next);
6935                 free(la);
6936         }
6937
6938         dwarf_finish(re->dbg, &de);
6939 }
6940
6941 static void
6942 dump_ar(struct readelf *re, int fd)
6943 {
6944         Elf_Arsym *arsym;
6945         Elf_Arhdr *arhdr;
6946         Elf_Cmd cmd;
6947         Elf *e;
6948         size_t sz;
6949         off_t off;
6950         int i;
6951
6952         re->ar = re->elf;
6953
6954         if (re->options & RE_C) {
6955                 if ((arsym = elf_getarsym(re->ar, &sz)) == NULL) {
6956                         warnx("elf_getarsym() failed: %s", elf_errmsg(-1));
6957                         goto process_members;
6958                 }
6959                 printf("Index of archive %s: (%ju entries)\n", re->filename,
6960                     (uintmax_t) sz - 1);
6961                 off = 0;
6962                 for (i = 0; (size_t) i < sz; i++) {
6963                         if (arsym[i].as_name == NULL)
6964                                 break;
6965                         if (arsym[i].as_off != off) {
6966                                 off = arsym[i].as_off;
6967                                 if (elf_rand(re->ar, off) != off) {
6968                                         warnx("elf_rand() failed: %s",
6969                                             elf_errmsg(-1));
6970                                         continue;
6971                                 }
6972                                 if ((e = elf_begin(fd, ELF_C_READ, re->ar)) ==
6973                                     NULL) {
6974                                         warnx("elf_begin() failed: %s",
6975                                             elf_errmsg(-1));
6976                                         continue;
6977                                 }
6978                                 if ((arhdr = elf_getarhdr(e)) == NULL) {
6979                                         warnx("elf_getarhdr() failed: %s",
6980                                             elf_errmsg(-1));
6981                                         elf_end(e);
6982                                         continue;
6983                                 }
6984                                 printf("Binary %s(%s) contains:\n",
6985                                     re->filename, arhdr->ar_name);
6986                         }
6987                         printf("\t%s\n", arsym[i].as_name);
6988                 }
6989                 if (elf_rand(re->ar, SARMAG) != SARMAG) {
6990                         warnx("elf_rand() failed: %s", elf_errmsg(-1));
6991                         return;
6992                 }
6993         }
6994
6995 process_members:
6996
6997         if ((re->options & ~RE_C) == 0)
6998                 return;
6999
7000         cmd = ELF_C_READ;
7001         while ((re->elf = elf_begin(fd, cmd, re->ar)) != NULL) {
7002                 if ((arhdr = elf_getarhdr(re->elf)) == NULL) {
7003                         warnx("elf_getarhdr() failed: %s", elf_errmsg(-1));
7004                         goto next_member;
7005                 }
7006                 if (strcmp(arhdr->ar_name, "/") == 0 ||
7007                     strcmp(arhdr->ar_name, "//") == 0 ||
7008                     strcmp(arhdr->ar_name, "__.SYMDEF") == 0)
7009                         goto next_member;
7010                 printf("\nFile: %s(%s)\n", re->filename, arhdr->ar_name);
7011                 dump_elf(re);
7012
7013         next_member:
7014                 cmd = elf_next(re->elf);
7015                 elf_end(re->elf);
7016         }
7017         re->elf = re->ar;
7018 }
7019
7020 static void
7021 dump_object(struct readelf *re)
7022 {
7023         int fd;
7024
7025         if ((fd = open(re->filename, O_RDONLY)) == -1) {
7026                 warn("open %s failed", re->filename);
7027                 return;
7028         }
7029
7030         if ((re->flags & DISPLAY_FILENAME) != 0)
7031                 printf("\nFile: %s\n", re->filename);
7032
7033         if ((re->elf = elf_begin(fd, ELF_C_READ, NULL)) == NULL) {
7034                 warnx("elf_begin() failed: %s", elf_errmsg(-1));
7035                 return;
7036         }
7037
7038         switch (elf_kind(re->elf)) {
7039         case ELF_K_NONE:
7040                 warnx("Not an ELF file.");
7041                 return;
7042         case ELF_K_ELF:
7043                 dump_elf(re);
7044                 break;
7045         case ELF_K_AR:
7046                 dump_ar(re, fd);
7047                 break;
7048         default:
7049                 warnx("Internal: libelf returned unknown elf kind.");
7050                 return;
7051         }
7052
7053         elf_end(re->elf);
7054 }
7055
7056 static void
7057 add_dumpop(struct readelf *re, size_t si, const char *sn, int op, int t)
7058 {
7059         struct dumpop *d;
7060
7061         if ((d = find_dumpop(re, si, sn, -1, t)) == NULL) {
7062                 if ((d = calloc(1, sizeof(*d))) == NULL)
7063                         err(EXIT_FAILURE, "calloc failed");
7064                 if (t == DUMP_BY_INDEX)
7065                         d->u.si = si;
7066                 else
7067                         d->u.sn = sn;
7068                 d->type = t;
7069                 d->op = op;
7070                 STAILQ_INSERT_TAIL(&re->v_dumpop, d, dumpop_list);
7071         } else
7072                 d->op |= op;
7073 }
7074
7075 static struct dumpop *
7076 find_dumpop(struct readelf *re, size_t si, const char *sn, int op, int t)
7077 {
7078         struct dumpop *d;
7079
7080         STAILQ_FOREACH(d, &re->v_dumpop, dumpop_list) {
7081                 if ((op == -1 || op & d->op) &&
7082                     (t == -1 || (unsigned) t == d->type)) {
7083                         if ((d->type == DUMP_BY_INDEX && d->u.si == si) ||
7084                             (d->type == DUMP_BY_NAME && !strcmp(d->u.sn, sn)))
7085                                 return (d);
7086                 }
7087         }
7088
7089         return (NULL);
7090 }
7091
7092 static struct {
7093         const char *ln;
7094         char sn;
7095         int value;
7096 } dwarf_op[] = {
7097         {"rawline", 'l', DW_L},
7098         {"decodedline", 'L', DW_LL},
7099         {"info", 'i', DW_I},
7100         {"abbrev", 'a', DW_A},
7101         {"pubnames", 'p', DW_P},
7102         {"aranges", 'r', DW_R},
7103         {"ranges", 'r', DW_R},
7104         {"Ranges", 'R', DW_RR},
7105         {"macro", 'm', DW_M},
7106         {"frames", 'f', DW_F},
7107         {"frames-interp", 'F', DW_FF},
7108         {"str", 's', DW_S},
7109         {"loc", 'o', DW_O},
7110         {NULL, 0, 0}
7111 };
7112
7113 static void
7114 parse_dwarf_op_short(struct readelf *re, const char *op)
7115 {
7116         int i;
7117
7118         if (op == NULL) {
7119                 re->dop |= DW_DEFAULT_OPTIONS;
7120                 return;
7121         }
7122
7123         for (; *op != '\0'; op++) {
7124                 for (i = 0; dwarf_op[i].ln != NULL; i++) {
7125                         if (dwarf_op[i].sn == *op) {
7126                                 re->dop |= dwarf_op[i].value;
7127                                 break;
7128                         }
7129                 }
7130         }
7131 }
7132
7133 static void
7134 parse_dwarf_op_long(struct readelf *re, const char *op)
7135 {
7136         char *p, *token, *bp;
7137         int i;
7138
7139         if (op == NULL) {
7140                 re->dop |= DW_DEFAULT_OPTIONS;
7141                 return;
7142         }
7143
7144         if ((p = strdup(op)) == NULL)
7145                 err(EXIT_FAILURE, "strdup failed");
7146         bp = p;
7147
7148         while ((token = strsep(&p, ",")) != NULL) {
7149                 for (i = 0; dwarf_op[i].ln != NULL; i++) {
7150                         if (!strcmp(token, dwarf_op[i].ln)) {
7151                                 re->dop |= dwarf_op[i].value;
7152                                 break;
7153                         }
7154                 }
7155         }
7156
7157         free(bp);
7158 }
7159
7160 static uint64_t
7161 _read_lsb(Elf_Data *d, uint64_t *offsetp, int bytes_to_read)
7162 {
7163         uint64_t ret;
7164         uint8_t *src;
7165
7166         src = (uint8_t *) d->d_buf + *offsetp;
7167
7168         ret = 0;
7169         switch (bytes_to_read) {
7170         case 8:
7171                 ret |= ((uint64_t) src[4]) << 32 | ((uint64_t) src[5]) << 40;
7172                 ret |= ((uint64_t) src[6]) << 48 | ((uint64_t) src[7]) << 56;
7173                 /* FALLTHROUGH */
7174         case 4:
7175                 ret |= ((uint64_t) src[2]) << 16 | ((uint64_t) src[3]) << 24;
7176                 /* FALLTHROUGH */
7177         case 2:
7178                 ret |= ((uint64_t) src[1]) << 8;
7179                 /* FALLTHROUGH */
7180         case 1:
7181                 ret |= src[0];
7182                 break;
7183         default:
7184                 return (0);
7185         }
7186
7187         *offsetp += bytes_to_read;
7188
7189         return (ret);
7190 }
7191
7192 static uint64_t
7193 _read_msb(Elf_Data *d, uint64_t *offsetp, int bytes_to_read)
7194 {
7195         uint64_t ret;
7196         uint8_t *src;
7197
7198         src = (uint8_t *) d->d_buf + *offsetp;
7199
7200         switch (bytes_to_read) {
7201         case 1:
7202                 ret = src[0];
7203                 break;
7204         case 2:
7205                 ret = src[1] | ((uint64_t) src[0]) << 8;
7206                 break;
7207         case 4:
7208                 ret = src[3] | ((uint64_t) src[2]) << 8;
7209                 ret |= ((uint64_t) src[1]) << 16 | ((uint64_t) src[0]) << 24;
7210                 break;
7211         case 8:
7212                 ret = src[7] | ((uint64_t) src[6]) << 8;
7213                 ret |= ((uint64_t) src[5]) << 16 | ((uint64_t) src[4]) << 24;
7214                 ret |= ((uint64_t) src[3]) << 32 | ((uint64_t) src[2]) << 40;
7215                 ret |= ((uint64_t) src[1]) << 48 | ((uint64_t) src[0]) << 56;
7216                 break;
7217         default:
7218                 return (0);
7219         }
7220
7221         *offsetp += bytes_to_read;
7222
7223         return (ret);
7224 }
7225
7226 static uint64_t
7227 _decode_lsb(uint8_t **data, int bytes_to_read)
7228 {
7229         uint64_t ret;
7230         uint8_t *src;
7231
7232         src = *data;
7233
7234         ret = 0;
7235         switch (bytes_to_read) {
7236         case 8:
7237                 ret |= ((uint64_t) src[4]) << 32 | ((uint64_t) src[5]) << 40;
7238                 ret |= ((uint64_t) src[6]) << 48 | ((uint64_t) src[7]) << 56;
7239                 /* FALLTHROUGH */
7240         case 4:
7241                 ret |= ((uint64_t) src[2]) << 16 | ((uint64_t) src[3]) << 24;
7242                 /* FALLTHROUGH */
7243         case 2:
7244                 ret |= ((uint64_t) src[1]) << 8;
7245                 /* FALLTHROUGH */
7246         case 1:
7247                 ret |= src[0];
7248                 break;
7249         default:
7250                 return (0);
7251         }
7252
7253         *data += bytes_to_read;
7254
7255         return (ret);
7256 }
7257
7258 static uint64_t
7259 _decode_msb(uint8_t **data, int bytes_to_read)
7260 {
7261         uint64_t ret;
7262         uint8_t *src;
7263
7264         src = *data;
7265
7266         ret = 0;
7267         switch (bytes_to_read) {
7268         case 1:
7269                 ret = src[0];
7270                 break;
7271         case 2:
7272                 ret = src[1] | ((uint64_t) src[0]) << 8;
7273                 break;
7274         case 4:
7275                 ret = src[3] | ((uint64_t) src[2]) << 8;
7276                 ret |= ((uint64_t) src[1]) << 16 | ((uint64_t) src[0]) << 24;
7277                 break;
7278         case 8:
7279                 ret = src[7] | ((uint64_t) src[6]) << 8;
7280                 ret |= ((uint64_t) src[5]) << 16 | ((uint64_t) src[4]) << 24;
7281                 ret |= ((uint64_t) src[3]) << 32 | ((uint64_t) src[2]) << 40;
7282                 ret |= ((uint64_t) src[1]) << 48 | ((uint64_t) src[0]) << 56;
7283                 break;
7284         default:
7285                 return (0);
7286                 break;
7287         }
7288
7289         *data += bytes_to_read;
7290
7291         return (ret);
7292 }
7293
7294 static int64_t
7295 _decode_sleb128(uint8_t **dp, uint8_t *dpe)
7296 {
7297         int64_t ret = 0;
7298         uint8_t b = 0;
7299         int shift = 0;
7300
7301         uint8_t *src = *dp;
7302
7303         do {
7304                 if (src >= dpe)
7305                         break;
7306                 b = *src++;
7307                 ret |= ((b & 0x7f) << shift);
7308                 shift += 7;
7309         } while ((b & 0x80) != 0);
7310
7311         if (shift < 32 && (b & 0x40) != 0)
7312                 ret |= (-1 << shift);
7313
7314         *dp = src;
7315
7316         return (ret);
7317 }
7318
7319 static uint64_t
7320 _decode_uleb128(uint8_t **dp, uint8_t *dpe)
7321 {
7322         uint64_t ret = 0;
7323         uint8_t b;
7324         int shift = 0;
7325
7326         uint8_t *src = *dp;
7327
7328         do {
7329                 if (src >= dpe)
7330                         break;
7331                 b = *src++;
7332                 ret |= ((b & 0x7f) << shift);
7333                 shift += 7;
7334         } while ((b & 0x80) != 0);
7335
7336         *dp = src;
7337
7338         return (ret);
7339 }
7340
7341 static void
7342 readelf_version(void)
7343 {
7344         (void) printf("%s (%s)\n", ELFTC_GETPROGNAME(),
7345             elftc_version());
7346         exit(EXIT_SUCCESS);
7347 }
7348
7349 #define USAGE_MESSAGE   "\
7350 Usage: %s [options] file...\n\
7351   Display information about ELF objects and ar(1) archives.\n\n\
7352   Options:\n\
7353   -a | --all               Equivalent to specifying options '-dhIlrsASV'.\n\
7354   -c | --archive-index     Print the archive symbol table for archives.\n\
7355   -d | --dynamic           Print the contents of SHT_DYNAMIC sections.\n\
7356   -e | --headers           Print all headers in the object.\n\
7357   -g | --section-groups    Print the contents of the section groups.\n\
7358   -h | --file-header       Print the file header for the object.\n\
7359   -l | --program-headers   Print the PHDR table for the object.\n\
7360   -n | --notes             Print the contents of SHT_NOTE sections.\n\
7361   -p INDEX | --string-dump=INDEX\n\
7362                            Print the contents of section at index INDEX.\n\
7363   -r | --relocs            Print relocation information.\n\
7364   -s | --syms | --symbols  Print symbol tables.\n\
7365   -t | --section-details   Print additional information about sections.\n\
7366   -v | --version           Print a version identifier and exit.\n\
7367   -w[afilmoprsFLR] | --debug-dump={abbrev,aranges,decodedline,frames,\n\
7368                                frames-interp,info,loc,macro,pubnames,\n\
7369                                ranges,Ranges,rawline,str}\n\
7370                            Display DWARF information.\n\
7371   -x INDEX | --hex-dump=INDEX\n\
7372                            Display contents of a section as hexadecimal.\n\
7373   -A | --arch-specific     (accepted, but ignored)\n\
7374   -D | --use-dynamic       Print the symbol table specified by the DT_SYMTAB\n\
7375                            entry in the \".dynamic\" section.\n\
7376   -H | --help              Print a help message.\n\
7377   -I | --histogram         Print information on bucket list lengths for \n\
7378                            hash sections.\n\
7379   -N | --full-section-name (accepted, but ignored)\n\
7380   -S | --sections | --section-headers\n\
7381                            Print information about section headers.\n\
7382   -V | --version-info      Print symbol versoning information.\n\
7383   -W | --wide              Print information without wrapping long lines.\n"
7384
7385
7386 static void
7387 readelf_usage(int status)
7388 {
7389         fprintf(stderr, USAGE_MESSAGE, ELFTC_GETPROGNAME());
7390         exit(status);
7391 }
7392
7393 int
7394 main(int argc, char **argv)
7395 {
7396         struct readelf  *re, re_storage;
7397         unsigned long    si;
7398         int              opt, i;
7399         char            *ep;
7400
7401         re = &re_storage;
7402         memset(re, 0, sizeof(*re));
7403         STAILQ_INIT(&re->v_dumpop);
7404
7405         while ((opt = getopt_long(argc, argv, "AacDdegHhIi:lNnp:rSstuVvWw::x:",
7406             longopts, NULL)) != -1) {
7407                 switch(opt) {
7408                 case '?':
7409                         readelf_usage(EXIT_SUCCESS);
7410                         break;
7411                 case 'A':
7412                         re->options |= RE_AA;
7413                         break;
7414                 case 'a':
7415                         re->options |= RE_AA | RE_D | RE_G | RE_H | RE_II |
7416                             RE_L | RE_R | RE_SS | RE_S | RE_VV;
7417                         break;
7418                 case 'c':
7419                         re->options |= RE_C;
7420                         break;
7421                 case 'D':
7422                         re->options |= RE_DD;
7423                         break;
7424                 case 'd':
7425                         re->options |= RE_D;
7426                         break;
7427                 case 'e':
7428                         re->options |= RE_H | RE_L | RE_SS;
7429                         break;
7430                 case 'g':
7431                         re->options |= RE_G;
7432                         break;
7433                 case 'H':
7434                         readelf_usage(EXIT_SUCCESS);
7435                         break;
7436                 case 'h':
7437                         re->options |= RE_H;
7438                         break;
7439                 case 'I':
7440                         re->options |= RE_II;
7441                         break;
7442                 case 'i':
7443                         /* Not implemented yet. */
7444                         break;
7445                 case 'l':
7446                         re->options |= RE_L;
7447                         break;
7448                 case 'N':
7449                         re->options |= RE_NN;
7450                         break;
7451                 case 'n':
7452                         re->options |= RE_N;
7453                         break;
7454                 case 'p':
7455                         re->options |= RE_P;
7456                         si = strtoul(optarg, &ep, 10);
7457                         if (*ep == '\0')
7458                                 add_dumpop(re, (size_t) si, NULL, STR_DUMP,
7459                                     DUMP_BY_INDEX);
7460                         else
7461                                 add_dumpop(re, 0, optarg, STR_DUMP,
7462                                     DUMP_BY_NAME);
7463                         break;
7464                 case 'r':
7465                         re->options |= RE_R;
7466                         break;
7467                 case 'S':
7468                         re->options |= RE_SS;
7469                         break;
7470                 case 's':
7471                         re->options |= RE_S;
7472                         break;
7473                 case 't':
7474                         re->options |= RE_T;
7475                         break;
7476                 case 'u':
7477                         re->options |= RE_U;
7478                         break;
7479                 case 'V':
7480                         re->options |= RE_VV;
7481                         break;
7482                 case 'v':
7483                         readelf_version();
7484                         break;
7485                 case 'W':
7486                         re->options |= RE_WW;
7487                         break;
7488                 case 'w':
7489                         re->options |= RE_W;
7490                         parse_dwarf_op_short(re, optarg);
7491                         break;
7492                 case 'x':
7493                         re->options |= RE_X;
7494                         si = strtoul(optarg, &ep, 10);
7495                         if (*ep == '\0')
7496                                 add_dumpop(re, (size_t) si, NULL, HEX_DUMP,
7497                                     DUMP_BY_INDEX);
7498                         else
7499                                 add_dumpop(re, 0, optarg, HEX_DUMP,
7500                                     DUMP_BY_NAME);
7501                         break;
7502                 case OPTION_DEBUG_DUMP:
7503                         re->options |= RE_W;
7504                         parse_dwarf_op_long(re, optarg);
7505                 }
7506         }
7507
7508         argv += optind;
7509         argc -= optind;
7510
7511         if (argc == 0 || re->options == 0)
7512                 readelf_usage(EXIT_FAILURE);
7513
7514         if (argc > 1)
7515                 re->flags |= DISPLAY_FILENAME;
7516
7517         if (elf_version(EV_CURRENT) == EV_NONE)
7518                 errx(EXIT_FAILURE, "ELF library initialization failed: %s",
7519                     elf_errmsg(-1));
7520
7521         for (i = 0; i < argc; i++) {
7522                 re->filename = argv[i];
7523                 dump_object(re);
7524         }
7525
7526         exit(EXIT_SUCCESS);
7527 }