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