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