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