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