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