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