xref: /freebsd/contrib/elftoolchain/elfdump/elfdump.c (revision b5864e6de2f3aa8eb9bb269ec86282598b5201b1)
1 /*-
2  * Copyright (c) 2007-2012 Kai Wang
3  * Copyright (c) 2003 David O'Brien.  All rights reserved.
4  * Copyright (c) 2001 Jake Burkholder
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/param.h>
30 #include <sys/queue.h>
31 #include <sys/stat.h>
32 
33 #include <ar.h>
34 #include <assert.h>
35 #include <err.h>
36 #include <fcntl.h>
37 #include <gelf.h>
38 #include <getopt.h>
39 #include <libelftc.h>
40 #include <inttypes.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 
46 #ifdef USE_LIBARCHIVE_AR
47 #include <archive.h>
48 #include <archive_entry.h>
49 #endif
50 
51 #include "_elftc.h"
52 
53 ELFTC_VCSID("$Id: elfdump.c 3474 2016-05-17 20:44:53Z emaste $");
54 
55 #if defined(ELFTC_NEED_ELF_NOTE_DEFINITION)
56 #include "native-elf-format.h"
57 #if ELFTC_CLASS == ELFCLASS32
58 typedef Elf32_Nhdr	Elf_Note;
59 #else
60 typedef Elf64_Nhdr	Elf_Note;
61 #endif
62 #endif
63 
64 /* elfdump(1) options. */
65 #define	ED_DYN		(1<<0)
66 #define	ED_EHDR		(1<<1)
67 #define	ED_GOT		(1<<2)
68 #define	ED_HASH		(1<<3)
69 #define	ED_INTERP	(1<<4)
70 #define	ED_NOTE		(1<<5)
71 #define	ED_PHDR		(1<<6)
72 #define	ED_REL		(1<<7)
73 #define	ED_SHDR		(1<<8)
74 #define	ED_SYMTAB	(1<<9)
75 #define	ED_SYMVER	(1<<10)
76 #define	ED_CHECKSUM	(1<<11)
77 #define	ED_ALL		((1<<12)-1)
78 
79 /* elfdump(1) run control flags. */
80 #define	SOLARIS_FMT		(1<<0)
81 #define	PRINT_FILENAME		(1<<1)
82 #define	PRINT_ARSYM		(1<<2)
83 #define	ONLY_ARSYM		(1<<3)
84 
85 /* Convenient print macro. */
86 #define	PRT(...)	fprintf(ed->out, __VA_ARGS__)
87 
88 /* Internal data structure for sections. */
89 struct section {
90 	const char	*name;		/* section name */
91 	Elf_Scn		*scn;		/* section scn */
92 	uint64_t	 off;		/* section offset */
93 	uint64_t	 sz;		/* section size */
94 	uint64_t	 entsize;	/* section entsize */
95 	uint64_t	 align;		/* section alignment */
96 	uint64_t	 type;		/* section type */
97 	uint64_t	 flags;		/* section flags */
98 	uint64_t	 addr;		/* section virtual addr */
99 	uint32_t	 link;		/* section link ndx */
100 	uint32_t	 info;		/* section info ndx */
101 };
102 
103 struct spec_name {
104 	const char	*name;
105 	STAILQ_ENTRY(spec_name)	sn_list;
106 };
107 
108 /* Structure encapsulates the global data for readelf(1). */
109 struct elfdump {
110 	FILE		*out;		/* output redirection. */
111 	const char	*filename;	/* current processing file. */
112 	const char	*archive;	/* archive name */
113 	int		 options;	/* command line options. */
114 	int		 flags;		/* run control flags. */
115 	Elf		*elf;		/* underlying ELF descriptor. */
116 #ifndef USE_LIBARCHIVE_AR
117 	Elf		*ar;		/* ar(1) archive descriptor. */
118 #endif
119 	GElf_Ehdr	 ehdr;		/* ELF header. */
120 	int		 ec;		/* ELF class. */
121 	size_t		 shnum;		/* #sections. */
122 	struct section	*sl;		/* list of sections. */
123 	STAILQ_HEAD(, spec_name) snl;	/* list of names specified by -N. */
124 };
125 
126 /* Relocation entry. */
127 struct rel_entry {
128 	union {
129 		GElf_Rel rel;
130 		GElf_Rela rela;
131 	} u_r;
132 	const char *symn;
133 	uint32_t type;
134 };
135 
136 #if defined(ELFTC_NEED_BYTEORDER_EXTENSIONS)
137 static __inline uint32_t
138 be32dec(const void *pp)
139 {
140 	unsigned char const *p = (unsigned char const *)pp;
141 
142 	return ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]);
143 }
144 
145 static __inline uint32_t
146 le32dec(const void *pp)
147 {
148 	unsigned char const *p = (unsigned char const *)pp;
149 
150 	return ((p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0]);
151 }
152 #endif
153 
154 /* http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#tag_encodings */
155 static const char *
156 d_tags(uint64_t tag)
157 {
158 	static char unknown_buf[64];
159 
160 	switch (tag) {
161 	case DT_NULL:		return "DT_NULL";
162 	case DT_NEEDED:		return "DT_NEEDED";
163 	case DT_PLTRELSZ:	return "DT_PLTRELSZ";
164 	case DT_PLTGOT:		return "DT_PLTGOT";
165 	case DT_HASH:		return "DT_HASH";
166 	case DT_STRTAB:		return "DT_STRTAB";
167 	case DT_SYMTAB:		return "DT_SYMTAB";
168 	case DT_RELA:		return "DT_RELA";
169 	case DT_RELASZ:		return "DT_RELASZ";
170 	case DT_RELAENT:	return "DT_RELAENT";
171 	case DT_STRSZ:		return "DT_STRSZ";
172 	case DT_SYMENT:		return "DT_SYMENT";
173 	case DT_INIT:		return "DT_INIT";
174 	case DT_FINI:		return "DT_FINI";
175 	case DT_SONAME:		return "DT_SONAME";
176 	case DT_RPATH:		return "DT_RPATH";
177 	case DT_SYMBOLIC:	return "DT_SYMBOLIC";
178 	case DT_REL:		return "DT_REL";
179 	case DT_RELSZ:		return "DT_RELSZ";
180 	case DT_RELENT:		return "DT_RELENT";
181 	case DT_PLTREL:		return "DT_PLTREL";
182 	case DT_DEBUG:		return "DT_DEBUG";
183 	case DT_TEXTREL:	return "DT_TEXTREL";
184 	case DT_JMPREL:		return "DT_JMPREL";
185 	case DT_BIND_NOW:	return "DT_BIND_NOW";
186 	case DT_INIT_ARRAY:	return "DT_INIT_ARRAY";
187 	case DT_FINI_ARRAY:	return "DT_FINI_ARRAY";
188 	case DT_INIT_ARRAYSZ:	return "DT_INIT_ARRAYSZ";
189 	case DT_FINI_ARRAYSZ:	return "DT_FINI_ARRAYSZ";
190 	case DT_RUNPATH:	return "DT_RUNPATH";
191 	case DT_FLAGS:		return "DT_FLAGS";
192 	case DT_PREINIT_ARRAY:	return "DT_PREINIT_ARRAY"; /* XXX DT_ENCODING */
193 	case DT_PREINIT_ARRAYSZ:return "DT_PREINIT_ARRAYSZ";
194 	/* 0x6000000D - 0x6ffff000 operating system-specific semantics */
195 	case 0x6ffffdf5:	return "DT_GNU_PRELINKED";
196 	case 0x6ffffdf6:	return "DT_GNU_CONFLICTSZ";
197 	case 0x6ffffdf7:	return "DT_GNU_LIBLISTSZ";
198 	case 0x6ffffdf8:	return "DT_SUNW_CHECKSUM";
199 	case DT_PLTPADSZ:	return "DT_PLTPADSZ";
200 	case DT_MOVEENT:	return "DT_MOVEENT";
201 	case DT_MOVESZ:		return "DT_MOVESZ";
202 	case 0x6ffffdfc:	return "DT_FEATURE";
203 	case DT_POSFLAG_1:	return "DT_POSFLAG_1";
204 	case DT_SYMINSZ:	return "DT_SYMINSZ";
205 	case DT_SYMINENT:	return "DT_SYMINENT (DT_VALRNGHI)";
206 	case DT_ADDRRNGLO:	return "DT_ADDRRNGLO";
207 	case DT_GNU_HASH:	return "DT_GNU_HASH";
208 	case 0x6ffffef8:	return "DT_GNU_CONFLICT";
209 	case 0x6ffffef9:	return "DT_GNU_LIBLIST";
210 	case 0x6ffffefa:	return "DT_CONFIG";
211 	case 0x6ffffefb:	return "DT_DEPAUDIT";
212 	case 0x6ffffefc:	return "DT_AUDIT";
213 	case 0x6ffffefd:	return "DT_PLTPAD";
214 	case 0x6ffffefe:	return "DT_MOVETAB";
215 	case DT_SYMINFO:	return "DT_SYMINFO (DT_ADDRRNGHI)";
216 	case DT_RELACOUNT:	return "DT_RELACOUNT";
217 	case DT_RELCOUNT:	return "DT_RELCOUNT";
218 	case DT_FLAGS_1:	return "DT_FLAGS_1";
219 	case DT_VERDEF:		return "DT_VERDEF";
220 	case DT_VERDEFNUM:	return "DT_VERDEFNUM";
221 	case DT_VERNEED:	return "DT_VERNEED";
222 	case DT_VERNEEDNUM:	return "DT_VERNEEDNUM";
223 	case 0x6ffffff0:	return "DT_GNU_VERSYM";
224 	/* 0x70000000 - 0x7fffffff processor-specific semantics */
225 	case 0x70000000:	return "DT_IA_64_PLT_RESERVE";
226 	case 0x7ffffffd:	return "DT_SUNW_AUXILIARY";
227 	case 0x7ffffffe:	return "DT_SUNW_USED";
228 	case 0x7fffffff:	return "DT_SUNW_FILTER";
229 	}
230 
231 	snprintf(unknown_buf, sizeof(unknown_buf),
232 		"<unknown: %#llx>", (unsigned long long)tag);
233 	return (unknown_buf);
234 }
235 
236 static const char *
237 e_machines(unsigned int mach)
238 {
239 	static char machdesc[64];
240 
241 	switch (mach) {
242 	case EM_NONE:	return "EM_NONE";
243 	case EM_M32:	return "EM_M32";
244 	case EM_SPARC:	return "EM_SPARC";
245 	case EM_386:	return "EM_386";
246 	case EM_68K:	return "EM_68K";
247 	case EM_88K:	return "EM_88K";
248 	case EM_IAMCU:	return "EM_IAMCU";
249 	case EM_860:	return "EM_860";
250 	case EM_MIPS:	return "EM_MIPS";
251 	case EM_PPC:	return "EM_PPC";
252 	case EM_PPC64:	return "EM_PPC64";
253 	case EM_ARM:	return "EM_ARM";
254 	case EM_ALPHA:	return "EM_ALPHA (legacy)";
255 	case EM_SPARCV9:return "EM_SPARCV9";
256 	case EM_IA_64:	return "EM_IA_64";
257 	case EM_X86_64:	return "EM_X86_64";
258 	case EM_AARCH64:return "EM_AARCH64";
259 	case EM_RISCV:	return "EM_RISCV";
260 	}
261 	snprintf(machdesc, sizeof(machdesc),
262 	    "(unknown machine) -- type 0x%x", mach);
263 	return (machdesc);
264 }
265 
266 static const char *
267 elf_type_str(unsigned int type)
268 {
269 	static char s_type[32];
270 
271 	switch (type)
272 	{
273 	case ET_NONE:	return "ET_NONE";
274 	case ET_REL:	return "ET_REL";
275 	case ET_EXEC:	return "ET_EXEC";
276 	case ET_DYN:	return "ET_DYN";
277 	case ET_CORE:	return "ET_CORE";
278 	}
279 	if (type >= ET_LOPROC)
280 		snprintf(s_type, sizeof(s_type), "<proc: %#x>", type);
281 	else if (type >= ET_LOOS && type <= ET_HIOS)
282 		snprintf(s_type, sizeof(s_type), "<os: %#x>", type);
283 	else
284 		snprintf(s_type, sizeof(s_type), "<unknown: %#x", type);
285 	return (s_type);
286 }
287 
288 static const char *
289 elf_version_str(unsigned int ver)
290 {
291 	static char s_ver[32];
292 
293 	switch (ver) {
294 	case EV_NONE:		return "EV_NONE";
295 	case EV_CURRENT:	return "EV_CURRENT";
296 	}
297 	snprintf(s_ver, sizeof(s_ver), "<unknown: %#x>", ver);
298 	return (s_ver);
299 }
300 
301 static const char *
302 elf_class_str(unsigned int class)
303 {
304 	static char s_class[32];
305 
306 	switch (class) {
307 	case ELFCLASSNONE:	return "ELFCLASSNONE";
308 	case ELFCLASS32:	return "ELFCLASS32";
309 	case ELFCLASS64:	return "ELFCLASS64";
310 	}
311 	snprintf(s_class, sizeof(s_class), "<unknown: %#x>", class);
312 	return (s_class);
313 }
314 
315 static const char *
316 elf_data_str(unsigned int data)
317 {
318 	static char s_data[32];
319 
320 	switch (data) {
321 	case ELFDATANONE:	return "ELFDATANONE";
322 	case ELFDATA2LSB:	return "ELFDATA2LSB";
323 	case ELFDATA2MSB:	return "ELFDATA2MSB";
324 	}
325 	snprintf(s_data, sizeof(s_data), "<unknown: %#x>", data);
326 	return (s_data);
327 }
328 
329 static const char *ei_abis[256] = {
330 	"ELFOSABI_NONE", "ELFOSABI_HPUX", "ELFOSABI_NETBSD", "ELFOSABI_LINUX",
331 	"ELFOSABI_HURD", "ELFOSABI_86OPEN", "ELFOSABI_SOLARIS", "ELFOSABI_AIX",
332 	"ELFOSABI_IRIX", "ELFOSABI_FREEBSD", "ELFOSABI_TRU64",
333 	"ELFOSABI_MODESTO", "ELFOSABI_OPENBSD",
334 	[17] = "ELFOSABI_CLOUDABI",
335 	[255] = "ELFOSABI_STANDALONE"
336 };
337 
338 static const char *
339 elf_phdr_type_str(unsigned int type)
340 {
341 	static char s_type[32];
342 
343 	switch (type) {
344 	case PT_NULL:		return "PT_NULL";
345 	case PT_LOAD:		return "PT_LOAD";
346 	case PT_DYNAMIC:	return "PT_DYNAMIC";
347 	case PT_INTERP:		return "PT_INTERP";
348 	case PT_NOTE:		return "PT_NOTE";
349 	case PT_SHLIB:		return "PT_SHLIB";
350 	case PT_PHDR:		return "PT_PHDR";
351 	case PT_TLS:		return "PT_TLS";
352 	case PT_GNU_EH_FRAME:	return "PT_GNU_EH_FRAME";
353 	case PT_GNU_STACK:	return "PT_GNU_STACK";
354 	case PT_GNU_RELRO:	return "PT_GNU_RELRO";
355 	}
356 	snprintf(s_type, sizeof(s_type), "<unknown: %#x>", type);
357 	return (s_type);
358 }
359 
360 static const char *p_flags[] = {
361 	"", "PF_X", "PF_W", "PF_X|PF_W", "PF_R", "PF_X|PF_R", "PF_W|PF_R",
362 	"PF_X|PF_W|PF_R"
363 };
364 
365 static const char *
366 sh_name(struct elfdump *ed, int ndx)
367 {
368 	static char num[10];
369 
370 	switch (ndx) {
371 	case SHN_UNDEF: return "UNDEF";
372 	case SHN_ABS: return "ABS";
373 	case SHN_COMMON: return "COMMON";
374 	default:
375 		if ((uint64_t)ndx < ed->shnum)
376 			return (ed->sl[ndx].name);
377 		else {
378 			snprintf(num, sizeof(num), "%d", ndx);
379 			return (num);
380 		}
381 	}
382 }
383 
384 /* http://www.sco.com/developers/gabi/latest/ch4.sheader.html#sh_type */
385 static const char *
386 sh_types(uint64_t mach, uint64_t sht) {
387 	static char unknown_buf[64];
388 
389 	if (sht < 0x60000000) {
390 		switch (sht) {
391 		case SHT_NULL:		return "SHT_NULL";
392 		case SHT_PROGBITS:	return "SHT_PROGBITS";
393 		case SHT_SYMTAB:	return "SHT_SYMTAB";
394 		case SHT_STRTAB:	return "SHT_STRTAB";
395 		case SHT_RELA:		return "SHT_RELA";
396 		case SHT_HASH:		return "SHT_HASH";
397 		case SHT_DYNAMIC:	return "SHT_DYNAMIC";
398 		case SHT_NOTE:		return "SHT_NOTE";
399 		case SHT_NOBITS:	return "SHT_NOBITS";
400 		case SHT_REL:		return "SHT_REL";
401 		case SHT_SHLIB:		return "SHT_SHLIB";
402 		case SHT_DYNSYM:	return "SHT_DYNSYM";
403 		case SHT_INIT_ARRAY:	return "SHT_INIT_ARRAY";
404 		case SHT_FINI_ARRAY:	return "SHT_FINI_ARRAY";
405 		case SHT_PREINIT_ARRAY:	return "SHT_PREINIT_ARRAY";
406 		case SHT_GROUP:		return "SHT_GROUP";
407 		case SHT_SYMTAB_SHNDX:	return "SHT_SYMTAB_SHNDX";
408 		}
409 	} else if (sht < 0x70000000) {
410 		/* 0x60000000-0x6fffffff operating system-specific semantics */
411 		switch (sht) {
412 		case 0x6ffffff0:	return "XXX:VERSYM";
413 		case SHT_SUNW_dof:	return "SHT_SUNW_dof";
414 		case SHT_GNU_HASH:	return "SHT_GNU_HASH";
415 		case 0x6ffffff7:	return "SHT_GNU_LIBLIST";
416 		case 0x6ffffffc:	return "XXX:VERDEF";
417 		case SHT_SUNW_verdef:	return "SHT_SUNW(GNU)_verdef";
418 		case SHT_SUNW_verneed:	return "SHT_SUNW(GNU)_verneed";
419 		case SHT_SUNW_versym:	return "SHT_SUNW(GNU)_versym";
420 		}
421 	} else if (sht < 0x80000000) {
422 		/* 0x70000000 - 0x7fffffff processor-specific semantics */
423 		switch (mach) {
424 		case EM_ARM:
425 			switch (sht) {
426 			case SHT_ARM_EXIDX: return "SHT_ARM_EXIDX";
427 			case SHT_ARM_PREEMPTMAP: return "SHT_ARM_PREEMPTMAP";
428 			case SHT_ARM_ATTRIBUTES: return "SHT_ARM_ATTRIBUTES";
429 			case SHT_ARM_DEBUGOVERLAY:
430 			    return "SHT_ARM_DEBUGOVERLAY";
431 			case SHT_ARM_OVERLAYSECTION:
432 			    return "SHT_ARM_OVERLAYSECTION";
433 			}
434 			break;
435 		case EM_IA_64:
436 			switch (sht) {
437 			case 0x70000000: return "SHT_IA_64_EXT";
438 			case 0x70000001: return "SHT_IA_64_UNWIND";
439 			}
440 			break;
441 		case EM_MIPS:
442 			switch (sht) {
443 			case SHT_MIPS_REGINFO: return "SHT_MIPS_REGINFO";
444 			case SHT_MIPS_OPTIONS: return "SHT_MIPS_OPTIONS";
445 			case SHT_MIPS_ABIFLAGS: return "SHT_MIPS_ABIFLAGS";
446 			}
447 			break;
448 		}
449 		switch (sht) {
450 		case 0x7ffffffd: return "XXX:AUXILIARY";
451 		case 0x7fffffff: return "XXX:FILTER";
452 		}
453 	}
454 	/* 0x80000000 - 0xffffffff application programs */
455 
456 	snprintf(unknown_buf, sizeof(unknown_buf),
457 		"<unknown: %#llx>", (unsigned long long)sht);
458 	return (unknown_buf);
459 }
460 
461 /*
462  * Define known section flags. These flags are defined in the order
463  * they are to be printed out.
464  */
465 #define	DEFINE_SHFLAGS()			\
466 	DEFINE_SHF(WRITE)			\
467 	DEFINE_SHF(ALLOC)			\
468 	DEFINE_SHF(EXECINSTR)			\
469 	DEFINE_SHF(MERGE)			\
470 	DEFINE_SHF(STRINGS)			\
471 	DEFINE_SHF(INFO_LINK)			\
472 	DEFINE_SHF(LINK_ORDER)			\
473 	DEFINE_SHF(OS_NONCONFORMING)		\
474 	DEFINE_SHF(GROUP)			\
475 	DEFINE_SHF(TLS)				\
476 	DEFINE_SHF(COMPRESSED)
477 
478 #undef	DEFINE_SHF
479 #define	DEFINE_SHF(F) "SHF_" #F "|"
480 #define ALLSHFLAGS	DEFINE_SHFLAGS()
481 
482 static const char *
483 sh_flags(uint64_t shf)
484 {
485 	static char	flg[sizeof(ALLSHFLAGS)+1];
486 
487 	flg[0] = '\0';
488 
489 #undef	DEFINE_SHF
490 #define	DEFINE_SHF(N)				\
491 	if (shf & SHF_##N)			\
492 		strcat(flg, "SHF_" #N "|");	\
493 
494 	DEFINE_SHFLAGS()
495 
496 	flg[strlen(flg) - 1] = '\0'; /* Remove the trailing "|". */
497 
498 	return (flg);
499 }
500 
501 static const char *
502 st_type(unsigned int mach, unsigned int type)
503 {
504 	static char s_type[32];
505 
506 	switch (type) {
507 	case STT_NOTYPE: return "STT_NOTYPE";
508 	case STT_OBJECT: return "STT_OBJECT";
509 	case STT_FUNC: return "STT_FUNC";
510 	case STT_SECTION: return "STT_SECTION";
511 	case STT_FILE: return "STT_FILE";
512 	case STT_COMMON: return "STT_COMMON";
513 	case STT_TLS: return "STT_TLS";
514 	case 13:
515 		if (mach == EM_SPARCV9)
516 			return "STT_SPARC_REGISTER";
517 		break;
518 	}
519 	snprintf(s_type, sizeof(s_type), "<unknown: %#x>", type);
520 	return (s_type);
521 }
522 
523 static const char *
524 st_type_S(unsigned int type)
525 {
526 	static char s_type[32];
527 
528 	switch (type) {
529 	case STT_NOTYPE: return "NOTY";
530 	case STT_OBJECT: return "OBJT";
531 	case STT_FUNC: return "FUNC";
532 	case STT_SECTION: return "SECT";
533 	case STT_FILE: return "FILE";
534 	}
535 	snprintf(s_type, sizeof(s_type), "<unknown: %#x>", type);
536 	return (s_type);
537 }
538 
539 static const char *
540 st_bindings(unsigned int sbind)
541 {
542 	static char s_sbind[32];
543 
544 	switch (sbind) {
545 	case STB_LOCAL: return "STB_LOCAL";
546 	case STB_GLOBAL: return "STB_GLOBAL";
547 	case STB_WEAK: return "STB_WEAK";
548 	case STB_GNU_UNIQUE: return "STB_GNU_UNIQUE";
549 	default:
550 		if (sbind >= STB_LOOS && sbind <= STB_HIOS)
551 			return "OS";
552 		else if (sbind >= STB_LOPROC && sbind <= STB_HIPROC)
553 			return "PROC";
554 		else
555 			snprintf(s_sbind, sizeof(s_sbind), "<unknown: %#x>",
556 			    sbind);
557 		return (s_sbind);
558 	}
559 }
560 
561 static const char *
562 st_bindings_S(unsigned int sbind)
563 {
564 	static char s_sbind[32];
565 
566 	switch (sbind) {
567 	case STB_LOCAL: return "LOCL";
568 	case STB_GLOBAL: return "GLOB";
569 	case STB_WEAK: return "WEAK";
570 	case STB_GNU_UNIQUE: return "UNIQ";
571 	default:
572 		if (sbind >= STB_LOOS && sbind <= STB_HIOS)
573 			return "OS";
574 		else if (sbind >= STB_LOPROC && sbind <= STB_HIPROC)
575 			return "PROC";
576 		else
577 			snprintf(s_sbind, sizeof(s_sbind), "<%#x>",
578 			    sbind);
579 		return (s_sbind);
580 	}
581 }
582 
583 static unsigned char st_others[] = {
584 	'D', 'I', 'H', 'P'
585 };
586 
587 static void	add_name(struct elfdump *ed, const char *name);
588 static void	elf_print_object(struct elfdump *ed);
589 static void	elf_print_elf(struct elfdump *ed);
590 static void	elf_print_ehdr(struct elfdump *ed);
591 static void	elf_print_phdr(struct elfdump *ed);
592 static void	elf_print_shdr(struct elfdump *ed);
593 static void	elf_print_symtab(struct elfdump *ed, int i);
594 static void	elf_print_symtabs(struct elfdump *ed);
595 static void	elf_print_symver(struct elfdump *ed);
596 static void	elf_print_verdef(struct elfdump *ed, struct section *s);
597 static void	elf_print_verneed(struct elfdump *ed, struct section *s);
598 static void	elf_print_interp(struct elfdump *ed);
599 static void	elf_print_dynamic(struct elfdump *ed);
600 static void	elf_print_rel_entry(struct elfdump *ed, struct section *s,
601     int j, struct rel_entry *r);
602 static void	elf_print_rela(struct elfdump *ed, struct section *s,
603     Elf_Data *data);
604 static void	elf_print_rel(struct elfdump *ed, struct section *s,
605     Elf_Data *data);
606 static void	elf_print_reloc(struct elfdump *ed);
607 static void	elf_print_got(struct elfdump *ed);
608 static void	elf_print_got_section(struct elfdump *ed, struct section *s);
609 static void	elf_print_note(struct elfdump *ed);
610 static void	elf_print_svr4_hash(struct elfdump *ed, struct section *s);
611 static void	elf_print_svr4_hash64(struct elfdump *ed, struct section *s);
612 static void	elf_print_gnu_hash(struct elfdump *ed, struct section *s);
613 static void	elf_print_hash(struct elfdump *ed);
614 static void	elf_print_checksum(struct elfdump *ed);
615 static void	find_gotrel(struct elfdump *ed, struct section *gs,
616     struct rel_entry *got);
617 static struct spec_name	*find_name(struct elfdump *ed, const char *name);
618 static int	get_ent_count(const struct section *s, int *ent_count);
619 static const char *get_symbol_name(struct elfdump *ed, uint32_t symtab, int i);
620 static const char *get_string(struct elfdump *ed, int strtab, size_t off);
621 static void	get_versym(struct elfdump *ed, int i, uint16_t **vs, int *nvs);
622 static void	load_sections(struct elfdump *ed);
623 static void	unload_sections(struct elfdump *ed);
624 static void	usage(void);
625 #ifdef	USE_LIBARCHIVE_AR
626 static int	ac_detect_ar(int fd);
627 static void	ac_print_ar(struct elfdump *ed, int fd);
628 #else
629 static void	elf_print_ar(struct elfdump *ed, int fd);
630 #endif	/* USE_LIBARCHIVE_AR */
631 
632 static struct option elfdump_longopts[] =
633 {
634 	{ "help",	no_argument,	NULL,	'H' },
635 	{ "version",	no_argument,	NULL,	'V' },
636 	{ NULL,		0,		NULL,	0   }
637 };
638 
639 int
640 main(int ac, char **av)
641 {
642 	struct elfdump		*ed, ed_storage;
643 	struct spec_name	*sn;
644 	int			 ch, i;
645 
646 	ed = &ed_storage;
647 	memset(ed, 0, sizeof(*ed));
648 	STAILQ_INIT(&ed->snl);
649 	ed->out = stdout;
650 	while ((ch = getopt_long(ac, av, "acdeiGHhknN:prsSvVw:",
651 		elfdump_longopts, NULL)) != -1)
652 		switch (ch) {
653 		case 'a':
654 			ed->options = ED_ALL;
655 			break;
656 		case 'c':
657 			ed->options |= ED_SHDR;
658 			break;
659 		case 'd':
660 			ed->options |= ED_DYN;
661 			break;
662 		case 'e':
663 			ed->options |= ED_EHDR;
664 			break;
665 		case 'i':
666 			ed->options |= ED_INTERP;
667 			break;
668 		case 'G':
669 			ed->options |= ED_GOT;
670 			break;
671 		case 'h':
672 			ed->options |= ED_HASH;
673 			break;
674 		case 'k':
675 			ed->options |= ED_CHECKSUM;
676 			break;
677 		case 'n':
678 			ed->options |= ED_NOTE;
679 			break;
680 		case 'N':
681 			add_name(ed, optarg);
682 			break;
683 		case 'p':
684 			ed->options |= ED_PHDR;
685 			break;
686 		case 'r':
687 			ed->options |= ED_REL;
688 			break;
689 		case 's':
690 			ed->options |= ED_SYMTAB;
691 			break;
692 		case 'S':
693 			ed->flags |= SOLARIS_FMT;
694 			break;
695 		case 'v':
696 			ed->options |= ED_SYMVER;
697 			break;
698 		case 'V':
699 			(void) printf("%s (%s)\n", ELFTC_GETPROGNAME(),
700 			    elftc_version());
701 			exit(EXIT_SUCCESS);
702 			break;
703 		case 'w':
704 			if ((ed->out = fopen(optarg, "w")) == NULL)
705 				err(EXIT_FAILURE, "%s", optarg);
706 			break;
707 		case '?':
708 		case 'H':
709 		default:
710 			usage();
711 		}
712 
713 	ac -= optind;
714 	av += optind;
715 
716 	if (ed->options == 0)
717 		ed->options = ED_ALL;
718 	sn = NULL;
719 	if (ed->options & ED_SYMTAB &&
720 	    (STAILQ_EMPTY(&ed->snl) || (sn = find_name(ed, "ARSYM")) != NULL)) {
721 		ed->flags |= PRINT_ARSYM;
722 		if (sn != NULL) {
723 			STAILQ_REMOVE(&ed->snl, sn, spec_name, sn_list);
724 			if (STAILQ_EMPTY(&ed->snl))
725 				ed->flags |= ONLY_ARSYM;
726 		}
727 	}
728 	if (ac == 0)
729 		usage();
730 	if (ac > 1)
731 		ed->flags |= PRINT_FILENAME;
732 	if (elf_version(EV_CURRENT) == EV_NONE)
733 		errx(EXIT_FAILURE, "ELF library initialization failed: %s",
734 		    elf_errmsg(-1));
735 
736 	for (i = 0; i < ac; i++) {
737 		ed->filename = av[i];
738 		ed->archive = NULL;
739 		elf_print_object(ed);
740 	}
741 
742 	exit(EXIT_SUCCESS);
743 }
744 
745 #ifdef USE_LIBARCHIVE_AR
746 
747 /* Archive symbol table entry. */
748 struct arsym_entry {
749 	char *sym_name;
750 	size_t off;
751 };
752 
753 /*
754  * Convenient wrapper for general libarchive error handling.
755  */
756 #define	AC(CALL) do {							\
757 	if ((CALL)) {							\
758 		warnx("%s", archive_error_string(a));			\
759 		return;							\
760 	}								\
761 } while (0)
762 
763 /*
764  * Detect an ar(1) archive using libarchive(3).
765  */
766 static int
767 ac_detect_ar(int fd)
768 {
769 	struct archive		*a;
770 	struct archive_entry	*entry;
771 	int			 r;
772 
773 	r = -1;
774 	if ((a = archive_read_new()) == NULL)
775 		return (0);
776 	archive_read_support_format_ar(a);
777 	if (archive_read_open_fd(a, fd, 10240) == ARCHIVE_OK)
778 		r = archive_read_next_header(a, &entry);
779 	archive_read_close(a);
780 	archive_read_free(a);
781 
782 	return (r == ARCHIVE_OK);
783 }
784 
785 /*
786  * Dump an ar(1) archive using libarchive(3).
787  */
788 static void
789 ac_print_ar(struct elfdump *ed, int fd)
790 {
791 	struct archive		*a;
792 	struct archive_entry	*entry;
793 	struct arsym_entry	*arsym;
794 	const char		*name;
795 	char			 idx[10], *b;
796 	void			*buff;
797 	size_t			 size;
798 	uint32_t		 cnt, i;
799 	int			 r;
800 
801 	if (lseek(fd, 0, SEEK_SET) == -1)
802 		err(EXIT_FAILURE, "lseek failed");
803 	if ((a = archive_read_new()) == NULL)
804 		errx(EXIT_FAILURE, "%s", archive_error_string(a));
805 	archive_read_support_format_ar(a);
806 	AC(archive_read_open_fd(a, fd, 10240));
807 	for(;;) {
808 		r = archive_read_next_header(a, &entry);
809 		if (r == ARCHIVE_FATAL)
810 			errx(EXIT_FAILURE, "%s", archive_error_string(a));
811 		if (r == ARCHIVE_EOF)
812 			break;
813 		if (r == ARCHIVE_WARN || r == ARCHIVE_RETRY)
814 			warnx("%s", archive_error_string(a));
815 		if (r == ARCHIVE_RETRY)
816 			continue;
817 		name = archive_entry_pathname(entry);
818 		size = archive_entry_size(entry);
819 		if (size == 0)
820 			continue;
821 		if ((buff = malloc(size)) == NULL) {
822 			warn("malloc failed");
823 			continue;
824 		}
825 		if (archive_read_data(a, buff, size) != (ssize_t)size) {
826 			warnx("%s", archive_error_string(a));
827 			free(buff);
828 			continue;
829 		}
830 
831 		/*
832 		 * Note that when processing arsym via libarchive, there is
833 		 * no way to tell which member a certain symbol belongs to,
834 		 * since we can not just "lseek" to a member offset and read
835 		 * the member header.
836 		 */
837 		if (!strcmp(name, "/") && ed->flags & PRINT_ARSYM) {
838 			b = buff;
839 			cnt = be32dec(b);
840 			if (cnt == 0) {
841 				free(buff);
842 				continue;
843 			}
844 			arsym = calloc(cnt, sizeof(*arsym));
845 			if (arsym == NULL)
846 				err(EXIT_FAILURE, "calloc failed");
847 			b += sizeof(uint32_t);
848 			for (i = 0; i < cnt; i++) {
849 				arsym[i].off = be32dec(b);
850 				b += sizeof(uint32_t);
851 			}
852 			for (i = 0; i < cnt; i++) {
853 				arsym[i].sym_name = b;
854 				b += strlen(b) + 1;
855 			}
856 			if (ed->flags & SOLARIS_FMT) {
857 				PRT("\nSymbol Table: (archive)\n");
858 				PRT("     index    offset    symbol\n");
859 			} else
860 				PRT("\nsymbol table (archive):\n");
861 			for (i = 0; i < cnt; i++) {
862 				if (ed->flags & SOLARIS_FMT) {
863 					snprintf(idx, sizeof(idx), "[%d]", i);
864 					PRT("%10s  ", idx);
865 					PRT("0x%8.8jx  ",
866 					    (uintmax_t)arsym[i].off);
867 					PRT("%s\n", arsym[i].sym_name);
868 				} else {
869 					PRT("\nentry: %d\n", i);
870 					PRT("\toffset: %#jx\n",
871 					    (uintmax_t)arsym[i].off);
872 					PRT("\tsymbol: %s\n",
873 					    arsym[i].sym_name);
874 				}
875 			}
876 			free(arsym);
877 			free(buff);
878 			/* No need to continue if we only dump ARSYM. */
879 			if (ed->flags & ONLY_ARSYM) {
880 				AC(archive_read_close(a));
881 				AC(archive_read_free(a));
882 				return;
883 			}
884 			continue;
885 		}
886 		if ((ed->elf = elf_memory(buff, size)) == NULL) {
887 			warnx("elf_memroy() failed: %s",
888 			      elf_errmsg(-1));
889 			free(buff);
890 			continue;
891 		}
892 		/* Skip non-ELF member. */
893 		if (elf_kind(ed->elf) == ELF_K_ELF) {
894 			printf("\n%s(%s):\n", ed->archive, name);
895 			elf_print_elf(ed);
896 		}
897 		elf_end(ed->elf);
898 		free(buff);
899 	}
900 	AC(archive_read_close(a));
901 	AC(archive_read_free(a));
902 }
903 
904 #else  /* USE_LIBARCHIVE_AR */
905 
906 /*
907  * Dump an ar(1) archive.
908  */
909 static void
910 elf_print_ar(struct elfdump *ed, int fd)
911 {
912 	Elf		*e;
913 	Elf_Arhdr	*arh;
914 	Elf_Arsym	*arsym;
915 	Elf_Cmd		 cmd;
916 	char		 idx[10];
917 	size_t		 cnt, i;
918 
919 	ed->ar = ed->elf;
920 
921 	if (ed->flags & PRINT_ARSYM) {
922 		cnt = 0;
923 		if ((arsym = elf_getarsym(ed->ar, &cnt)) == NULL) {
924 			warnx("elf_getarsym failed: %s", elf_errmsg(-1));
925 			goto print_members;
926 		}
927 		if (cnt == 0)
928 			goto print_members;
929 		if (ed->flags & SOLARIS_FMT) {
930 			PRT("\nSymbol Table: (archive)\n");
931 			PRT("     index    offset    member name and symbol\n");
932 		} else
933 			PRT("\nsymbol table (archive):\n");
934 		for (i = 0; i < cnt - 1; i++) {
935 			if (elf_rand(ed->ar, arsym[i].as_off) !=
936 			    arsym[i].as_off) {
937 				warnx("elf_rand failed: %s", elf_errmsg(-1));
938 				break;
939 			}
940 			if ((e = elf_begin(fd, ELF_C_READ, ed->ar)) == NULL) {
941 				warnx("elf_begin failed: %s", elf_errmsg(-1));
942 				break;
943 			}
944 			if ((arh = elf_getarhdr(e)) == NULL) {
945 				warnx("elf_getarhdr failed: %s",
946 				    elf_errmsg(-1));
947 				break;
948 			}
949 			if (ed->flags & SOLARIS_FMT) {
950 				snprintf(idx, sizeof(idx), "[%zu]", i);
951 				PRT("%10s  ", idx);
952 				PRT("0x%8.8jx  ",
953 				    (uintmax_t)arsym[i].as_off);
954 				PRT("(%s):%s\n", arh->ar_name,
955 				    arsym[i].as_name);
956 			} else {
957 				PRT("\nentry: %zu\n", i);
958 				PRT("\toffset: %#jx\n",
959 				    (uintmax_t)arsym[i].as_off);
960 				PRT("\tmember: %s\n", arh->ar_name);
961 				PRT("\tsymbol: %s\n", arsym[i].as_name);
962 			}
963 			elf_end(e);
964 		}
965 
966 		/* No need to continue if we only dump ARSYM. */
967 		if (ed->flags & ONLY_ARSYM)
968 			return;
969 	}
970 
971 print_members:
972 
973 	/* Rewind the archive. */
974 	if (elf_rand(ed->ar, SARMAG) != SARMAG) {
975 		warnx("elf_rand failed: %s", elf_errmsg(-1));
976 		return;
977 	}
978 
979 	/* Dump each member of the archive. */
980 	cmd = ELF_C_READ;
981 	while ((ed->elf = elf_begin(fd, cmd, ed->ar)) != NULL) {
982 		/* Skip non-ELF member. */
983 		if (elf_kind(ed->elf) == ELF_K_ELF) {
984 			if ((arh = elf_getarhdr(ed->elf)) == NULL) {
985 				warnx("elf_getarhdr failed: %s",
986 				    elf_errmsg(-1));
987 				break;
988 			}
989 			printf("\n%s(%s):\n", ed->archive, arh->ar_name);
990 			elf_print_elf(ed);
991 		}
992 		cmd = elf_next(ed->elf);
993 		elf_end(ed->elf);
994 	}
995 }
996 
997 #endif	/* USE_LIBARCHIVE_AR */
998 
999 /*
1000  * Dump an object. (ELF object or ar(1) archive)
1001  */
1002 static void
1003 elf_print_object(struct elfdump *ed)
1004 {
1005 	int fd;
1006 
1007 	if ((fd = open(ed->filename, O_RDONLY)) == -1) {
1008 		warn("open %s failed", ed->filename);
1009 		return;
1010 	}
1011 
1012 #ifdef	USE_LIBARCHIVE_AR
1013 	if (ac_detect_ar(fd)) {
1014 		ed->archive = ed->filename;
1015 		ac_print_ar(ed, fd);
1016 		return;
1017 	}
1018 #endif	/* USE_LIBARCHIVE_AR */
1019 
1020 	if ((ed->elf = elf_begin(fd, ELF_C_READ, NULL)) == NULL) {
1021 		warnx("elf_begin() failed: %s", elf_errmsg(-1));
1022 		return;
1023 	}
1024 
1025 	switch (elf_kind(ed->elf)) {
1026 	case ELF_K_NONE:
1027 		warnx("Not an ELF file.");
1028 		return;
1029 	case ELF_K_ELF:
1030 		if (ed->flags & PRINT_FILENAME)
1031 			printf("\n%s:\n", ed->filename);
1032 		elf_print_elf(ed);
1033 		break;
1034 	case ELF_K_AR:
1035 #ifndef	USE_LIBARCHIVE_AR
1036 		ed->archive = ed->filename;
1037 		elf_print_ar(ed, fd);
1038 #endif
1039 		break;
1040 	default:
1041 		warnx("Internal: libelf returned unknown elf kind.");
1042 		return;
1043 	}
1044 
1045 	elf_end(ed->elf);
1046 }
1047 
1048 /*
1049  * Dump an ELF object.
1050  */
1051 static void
1052 elf_print_elf(struct elfdump *ed)
1053 {
1054 
1055 	if (gelf_getehdr(ed->elf, &ed->ehdr) == NULL) {
1056 		warnx("gelf_getehdr failed: %s", elf_errmsg(-1));
1057 		return;
1058 	}
1059 	if ((ed->ec = gelf_getclass(ed->elf)) == ELFCLASSNONE) {
1060 		warnx("gelf_getclass failed: %s", elf_errmsg(-1));
1061 		return;
1062 	}
1063 
1064 	if (ed->options & (ED_SHDR | ED_DYN | ED_REL | ED_GOT | ED_SYMTAB |
1065 	    ED_SYMVER | ED_NOTE | ED_HASH))
1066 		load_sections(ed);
1067 
1068 	if (ed->options & ED_EHDR)
1069 		elf_print_ehdr(ed);
1070 	if (ed->options & ED_PHDR)
1071 		elf_print_phdr(ed);
1072 	if (ed->options & ED_INTERP)
1073 		elf_print_interp(ed);
1074 	if (ed->options & ED_SHDR)
1075 		elf_print_shdr(ed);
1076 	if (ed->options & ED_DYN)
1077 		elf_print_dynamic(ed);
1078 	if (ed->options & ED_REL)
1079 		elf_print_reloc(ed);
1080 	if (ed->options & ED_GOT)
1081 		elf_print_got(ed);
1082 	if (ed->options & ED_SYMTAB)
1083 		elf_print_symtabs(ed);
1084 	if (ed->options & ED_SYMVER)
1085 		elf_print_symver(ed);
1086 	if (ed->options & ED_NOTE)
1087 		elf_print_note(ed);
1088 	if (ed->options & ED_HASH)
1089 		elf_print_hash(ed);
1090 	if (ed->options & ED_CHECKSUM)
1091 		elf_print_checksum(ed);
1092 
1093 	unload_sections(ed);
1094 }
1095 
1096 /*
1097  * Read the section headers from ELF object and store them in the
1098  * internal cache.
1099  */
1100 static void
1101 load_sections(struct elfdump *ed)
1102 {
1103 	struct section	*s;
1104 	const char	*name;
1105 	Elf_Scn		*scn;
1106 	GElf_Shdr	 sh;
1107 	size_t		 shstrndx, ndx;
1108 	int		 elferr;
1109 
1110 	assert(ed->sl == NULL);
1111 
1112 	if (!elf_getshnum(ed->elf, &ed->shnum)) {
1113 		warnx("elf_getshnum failed: %s", elf_errmsg(-1));
1114 		return;
1115 	}
1116 	if (ed->shnum == 0)
1117 		return;
1118 	if ((ed->sl = calloc(ed->shnum, sizeof(*ed->sl))) == NULL)
1119 		err(EXIT_FAILURE, "calloc failed");
1120 	if (!elf_getshstrndx(ed->elf, &shstrndx)) {
1121 		warnx("elf_getshstrndx failed: %s", elf_errmsg(-1));
1122 		return;
1123 	}
1124 	if ((scn = elf_getscn(ed->elf, 0)) == NULL) {
1125 		warnx("elf_getscn failed: %s", elf_errmsg(-1));
1126 		return;
1127 	}
1128 	(void) elf_errno();
1129 	do {
1130 		if (gelf_getshdr(scn, &sh) == NULL) {
1131 			warnx("gelf_getshdr failed: %s", elf_errmsg(-1));
1132 			(void) elf_errno();
1133 			continue;
1134 		}
1135 		if ((name = elf_strptr(ed->elf, shstrndx, sh.sh_name)) == NULL) {
1136 			(void) elf_errno();
1137 			name = "ERROR";
1138 		}
1139 		if ((ndx = elf_ndxscn(scn)) == SHN_UNDEF)
1140 			if ((elferr = elf_errno()) != 0) {
1141 				warnx("elf_ndxscn failed: %s",
1142 				    elf_errmsg(elferr));
1143 				continue;
1144 			}
1145 		if (ndx >= ed->shnum) {
1146 			warnx("section index of '%s' out of range", name);
1147 			continue;
1148 		}
1149 		s = &ed->sl[ndx];
1150 		s->name = name;
1151 		s->scn = scn;
1152 		s->off = sh.sh_offset;
1153 		s->sz = sh.sh_size;
1154 		s->entsize = sh.sh_entsize;
1155 		s->align = sh.sh_addralign;
1156 		s->type = sh.sh_type;
1157 		s->flags = sh.sh_flags;
1158 		s->addr = sh.sh_addr;
1159 		s->link = sh.sh_link;
1160 		s->info = sh.sh_info;
1161 	} while ((scn = elf_nextscn(ed->elf, scn)) != NULL);
1162 	elferr = elf_errno();
1163 	if (elferr != 0)
1164 		warnx("elf_nextscn failed: %s", elf_errmsg(elferr));
1165 }
1166 
1167 /*
1168  * Release section related resources.
1169  */
1170 static void
1171 unload_sections(struct elfdump *ed)
1172 {
1173 	if (ed->sl != NULL) {
1174 		free(ed->sl);
1175 		ed->sl = NULL;
1176 	}
1177 }
1178 
1179 /*
1180  * Add a name to the '-N' name list.
1181  */
1182 static void
1183 add_name(struct elfdump *ed, const char *name)
1184 {
1185 	struct spec_name *sn;
1186 
1187 	if (find_name(ed, name))
1188 		return;
1189 	if ((sn = malloc(sizeof(*sn))) == NULL) {
1190 		warn("malloc failed");
1191 		return;
1192 	}
1193 	sn->name = name;
1194 	STAILQ_INSERT_TAIL(&ed->snl, sn, sn_list);
1195 }
1196 
1197 /*
1198  * Lookup a name in the '-N' name list.
1199  */
1200 static struct spec_name *
1201 find_name(struct elfdump *ed, const char *name)
1202 {
1203 	struct spec_name *sn;
1204 
1205 	STAILQ_FOREACH(sn, &ed->snl, sn_list) {
1206 		if (!strcmp(sn->name, name))
1207 			return (sn);
1208 	}
1209 
1210 	return (NULL);
1211 }
1212 
1213 /*
1214  * Retrieve the name of a symbol using the section index of the symbol
1215  * table and the index of the symbol within that table.
1216  */
1217 static const char *
1218 get_symbol_name(struct elfdump *ed, uint32_t symtab, int i)
1219 {
1220 	static char	 sname[64];
1221 	struct section	*s;
1222 	const char	*name;
1223 	GElf_Sym	 sym;
1224 	Elf_Data	*data;
1225 	int		 elferr;
1226 
1227 	if (symtab >= ed->shnum)
1228 		return ("");
1229 	s = &ed->sl[symtab];
1230 	if (s->type != SHT_SYMTAB && s->type != SHT_DYNSYM)
1231 		return ("");
1232 	(void) elf_errno();
1233 	if ((data = elf_getdata(s->scn, NULL)) == NULL) {
1234 		elferr = elf_errno();
1235 		if (elferr != 0)
1236 			warnx("elf_getdata failed: %s", elf_errmsg(elferr));
1237 		return ("");
1238 	}
1239 	if (gelf_getsym(data, i, &sym) != &sym)
1240 		return ("");
1241 	if (GELF_ST_TYPE(sym.st_info) == STT_SECTION) {
1242 		if (sym.st_shndx < ed->shnum) {
1243 			snprintf(sname, sizeof(sname), "%s (section)",
1244 			    ed->sl[sym.st_shndx].name);
1245 			return (sname);
1246 		} else
1247 			return ("");
1248 	}
1249 	if ((name = elf_strptr(ed->elf, s->link, sym.st_name)) == NULL)
1250 		return ("");
1251 
1252 	return (name);
1253 }
1254 
1255 /*
1256  * Retrieve a string using string table section index and the string offset.
1257  */
1258 static const char*
1259 get_string(struct elfdump *ed, int strtab, size_t off)
1260 {
1261 	const char *name;
1262 
1263 	if ((name = elf_strptr(ed->elf, strtab, off)) == NULL)
1264 		return ("");
1265 
1266 	return (name);
1267 }
1268 
1269 /*
1270  * Dump the ELF Executable Header.
1271  */
1272 static void
1273 elf_print_ehdr(struct elfdump *ed)
1274 {
1275 
1276 	if (!STAILQ_EMPTY(&ed->snl))
1277 		return;
1278 
1279 	if (ed->flags & SOLARIS_FMT) {
1280 		PRT("\nELF Header\n");
1281 		PRT("  ei_magic:   { %#x, %c, %c, %c }\n",
1282 		    ed->ehdr.e_ident[0], ed->ehdr.e_ident[1],
1283 		    ed->ehdr.e_ident[2], ed->ehdr.e_ident[3]);
1284 		PRT("  ei_class:   %-18s",
1285 		    elf_class_str(ed->ehdr.e_ident[EI_CLASS]));
1286 		PRT("  ei_data:      %s\n",
1287 		    elf_data_str(ed->ehdr.e_ident[EI_DATA]));
1288 		PRT("  e_machine:  %-18s", e_machines(ed->ehdr.e_machine));
1289 		PRT("  e_version:    %s\n",
1290 		    elf_version_str(ed->ehdr.e_version));
1291 		PRT("  e_type:     %s\n", elf_type_str(ed->ehdr.e_type));
1292 		PRT("  e_flags:    %18d\n", ed->ehdr.e_flags);
1293 		PRT("  e_entry:    %#18jx", (uintmax_t)ed->ehdr.e_entry);
1294 		PRT("  e_ehsize: %6d", ed->ehdr.e_ehsize);
1295 		PRT("  e_shstrndx:%5d\n", ed->ehdr.e_shstrndx);
1296 		PRT("  e_shoff:    %#18jx", (uintmax_t)ed->ehdr.e_shoff);
1297 		PRT("  e_shentsize: %3d", ed->ehdr.e_shentsize);
1298 		PRT("  e_shnum:   %5d\n", ed->ehdr.e_shnum);
1299 		PRT("  e_phoff:    %#18jx", (uintmax_t)ed->ehdr.e_phoff);
1300 		PRT("  e_phentsize: %3d", ed->ehdr.e_phentsize);
1301 		PRT("  e_phnum:   %5d\n", ed->ehdr.e_phnum);
1302 	} else {
1303 		PRT("\nelf header:\n");
1304 		PRT("\n");
1305 		PRT("\te_ident: %s %s %s\n",
1306 		    elf_class_str(ed->ehdr.e_ident[EI_CLASS]),
1307 		    elf_data_str(ed->ehdr.e_ident[EI_DATA]),
1308 		    ei_abis[ed->ehdr.e_ident[EI_OSABI]]);
1309 		PRT("\te_type: %s\n", elf_type_str(ed->ehdr.e_type));
1310 		PRT("\te_machine: %s\n", e_machines(ed->ehdr.e_machine));
1311 		PRT("\te_version: %s\n", elf_version_str(ed->ehdr.e_version));
1312 		PRT("\te_entry: %#jx\n", (uintmax_t)ed->ehdr.e_entry);
1313 		PRT("\te_phoff: %ju\n", (uintmax_t)ed->ehdr.e_phoff);
1314 		PRT("\te_shoff: %ju\n", (uintmax_t) ed->ehdr.e_shoff);
1315 		PRT("\te_flags: %u\n", ed->ehdr.e_flags);
1316 		PRT("\te_ehsize: %u\n", ed->ehdr.e_ehsize);
1317 		PRT("\te_phentsize: %u\n", ed->ehdr.e_phentsize);
1318 		PRT("\te_phnum: %u\n", ed->ehdr.e_phnum);
1319 		PRT("\te_shentsize: %u\n", ed->ehdr.e_shentsize);
1320 		PRT("\te_shnum: %u\n", ed->ehdr.e_shnum);
1321 		PRT("\te_shstrndx: %u\n", ed->ehdr.e_shstrndx);
1322 	}
1323 }
1324 
1325 /*
1326  * Dump the ELF Program Header Table.
1327  */
1328 static void
1329 elf_print_phdr(struct elfdump *ed)
1330 {
1331 	GElf_Phdr	 ph;
1332 	size_t		 phnum, i;
1333 	int		 header;
1334 
1335 	if (elf_getphnum(ed->elf, &phnum) == 0) {
1336 		warnx("elf_getphnum failed: %s", elf_errmsg(-1));
1337 		return;
1338 	}
1339 	header = 0;
1340 	for (i = 0; i < phnum; i++) {
1341 		if (gelf_getphdr(ed->elf, i, &ph) != &ph) {
1342 			warnx("elf_getphdr failed: %s", elf_errmsg(-1));
1343 			continue;
1344 		}
1345 		if (!STAILQ_EMPTY(&ed->snl) &&
1346 		    find_name(ed, elf_phdr_type_str(ph.p_type)) == NULL)
1347 			continue;
1348 		if (ed->flags & SOLARIS_FMT) {
1349 			PRT("\nProgram Header[%zu]:\n", i);
1350 			PRT("    p_vaddr:      %#-14jx", (uintmax_t)ph.p_vaddr);
1351 			PRT("  p_flags:    [ %s ]\n",
1352 			    p_flags[ph.p_flags & 0x7]);
1353 			PRT("    p_paddr:      %#-14jx", (uintmax_t)ph.p_paddr);
1354 			PRT("  p_type:     [ %s ]\n",
1355 			    elf_phdr_type_str(ph.p_type));
1356 			PRT("    p_filesz:     %#-14jx",
1357 			    (uintmax_t)ph.p_filesz);
1358 			PRT("  p_memsz:    %#jx\n", (uintmax_t)ph.p_memsz);
1359 			PRT("    p_offset:     %#-14jx",
1360 			    (uintmax_t)ph.p_offset);
1361 			PRT("  p_align:    %#jx\n", (uintmax_t)ph.p_align);
1362 		} else {
1363 			if (!header) {
1364 				PRT("\nprogram header:\n");
1365 				header = 1;
1366 			}
1367 			PRT("\n");
1368 			PRT("entry: %zu\n", i);
1369 			PRT("\tp_type: %s\n", elf_phdr_type_str(ph.p_type));
1370 			PRT("\tp_offset: %ju\n", (uintmax_t)ph.p_offset);
1371 			PRT("\tp_vaddr: %#jx\n", (uintmax_t)ph.p_vaddr);
1372 			PRT("\tp_paddr: %#jx\n", (uintmax_t)ph.p_paddr);
1373 			PRT("\tp_filesz: %ju\n", (uintmax_t)ph.p_filesz);
1374 			PRT("\tp_memsz: %ju\n", (uintmax_t)ph.p_memsz);
1375 			PRT("\tp_flags: %s\n", p_flags[ph.p_flags & 0x7]);
1376 			PRT("\tp_align: %ju\n", (uintmax_t)ph.p_align);
1377 		}
1378 	}
1379 }
1380 
1381 /*
1382  * Dump the ELF Section Header Table.
1383  */
1384 static void
1385 elf_print_shdr(struct elfdump *ed)
1386 {
1387 	struct section *s;
1388 	size_t i;
1389 
1390 	if (!STAILQ_EMPTY(&ed->snl))
1391 		return;
1392 
1393 	if ((ed->flags & SOLARIS_FMT) == 0)
1394 		PRT("\nsection header:\n");
1395 	for (i = 0; i < ed->shnum; i++) {
1396 		s = &ed->sl[i];
1397 		if (ed->flags & SOLARIS_FMT) {
1398 			if (i == 0)
1399 				continue;
1400 			PRT("\nSection Header[%zu]:", i);
1401 			PRT("  sh_name: %s\n", s->name);
1402 			PRT("    sh_addr:      %#-14jx", (uintmax_t)s->addr);
1403 			if (s->flags != 0)
1404 				PRT("  sh_flags:   [ %s ]\n", sh_flags(s->flags));
1405 			else
1406 				PRT("  sh_flags:   0\n");
1407 			PRT("    sh_size:      %#-14jx", (uintmax_t)s->sz);
1408 			PRT("  sh_type:    [ %s ]\n",
1409 			    sh_types(ed->ehdr.e_machine, s->type));
1410 			PRT("    sh_offset:    %#-14jx", (uintmax_t)s->off);
1411 			PRT("  sh_entsize: %#jx\n", (uintmax_t)s->entsize);
1412 			PRT("    sh_link:      %-14u", s->link);
1413 			PRT("  sh_info:    %u\n", s->info);
1414 			PRT("    sh_addralign: %#jx\n", (uintmax_t)s->align);
1415 		} else {
1416 			PRT("\n");
1417 			PRT("entry: %ju\n", (uintmax_t)i);
1418 			PRT("\tsh_name: %s\n", s->name);
1419 			PRT("\tsh_type: %s\n",
1420 			    sh_types(ed->ehdr.e_machine, s->type));
1421 			PRT("\tsh_flags: %s\n", sh_flags(s->flags));
1422 			PRT("\tsh_addr: %#jx\n", (uintmax_t)s->addr);
1423 			PRT("\tsh_offset: %ju\n", (uintmax_t)s->off);
1424 			PRT("\tsh_size: %ju\n", (uintmax_t)s->sz);
1425 			PRT("\tsh_link: %u\n", s->link);
1426 			PRT("\tsh_info: %u\n", s->info);
1427 			PRT("\tsh_addralign: %ju\n", (uintmax_t)s->align);
1428 			PRT("\tsh_entsize: %ju\n", (uintmax_t)s->entsize);
1429 		}
1430 	}
1431 }
1432 
1433 /*
1434  * Return number of entries in the given section. We'd prefer ent_count be a
1435  * size_t, but libelf APIs already use int for section indices.
1436  */
1437 static int
1438 get_ent_count(const struct section *s, int *ent_count)
1439 {
1440 	if (s->entsize == 0) {
1441 		warnx("section %s has entry size 0", s->name);
1442 		return (0);
1443 	} else if (s->sz / s->entsize > INT_MAX) {
1444 		warnx("section %s has invalid section count", s->name);
1445 		return (0);
1446 	}
1447 	*ent_count = (int)(s->sz / s->entsize);
1448 	return (1);
1449 }
1450 
1451 /*
1452  * Retrieve the content of the corresponding SHT_SUNW_versym section for
1453  * a symbol table section.
1454  */
1455 static void
1456 get_versym(struct elfdump *ed, int i, uint16_t **vs, int *nvs)
1457 {
1458 	struct section	*s;
1459 	Elf_Data	*data;
1460 	size_t		 j;
1461 	int		 elferr;
1462 
1463 	s = NULL;
1464 	for (j = 0; j < ed->shnum; j++) {
1465 		s = &ed->sl[j];
1466 		if (s->type == SHT_SUNW_versym && s->link == (uint32_t)i)
1467 			break;
1468 	}
1469 	if (j >= ed->shnum) {
1470 		*vs = NULL;
1471 		return;
1472 	}
1473 	(void) elf_errno();
1474 	if ((data = elf_getdata(s->scn, NULL)) == NULL) {
1475 		elferr = elf_errno();
1476 		if (elferr != 0)
1477 			warnx("elf_getdata failed: %s", elf_errmsg(elferr));
1478 		*vs = NULL;
1479 		return;
1480 	}
1481 
1482 	*vs = data->d_buf;
1483 	assert(data->d_size == s->sz);
1484 	if (!get_ent_count(s, nvs))
1485 		*nvs = 0;
1486 }
1487 
1488 /*
1489  * Dump the symbol table section.
1490  */
1491 static void
1492 elf_print_symtab(struct elfdump *ed, int i)
1493 {
1494 	struct section	*s;
1495 	const char	*name;
1496 	uint16_t	*vs;
1497 	char		 idx[10];
1498 	Elf_Data	*data;
1499 	GElf_Sym	 sym;
1500 	int		 len, j, elferr, nvs;
1501 
1502 	s = &ed->sl[i];
1503 	if (ed->flags & SOLARIS_FMT)
1504 		PRT("\nSymbol Table Section:  %s\n", s->name);
1505 	else
1506 		PRT("\nsymbol table (%s):\n", s->name);
1507 	(void) elf_errno();
1508 	if ((data = elf_getdata(s->scn, NULL)) == NULL) {
1509 		elferr = elf_errno();
1510 		if (elferr != 0)
1511 			warnx("elf_getdata failed: %s", elf_errmsg(elferr));
1512 		return;
1513 	}
1514 	vs = NULL;
1515 	nvs = 0;
1516 	assert(data->d_size == s->sz);
1517 	if (!get_ent_count(s, &len))
1518 		return;
1519 	if (ed->flags & SOLARIS_FMT) {
1520 		if (ed->ec == ELFCLASS32)
1521 			PRT("     index    value       ");
1522 		else
1523 			PRT("     index        value           ");
1524 		PRT("size     type bind oth ver shndx       name\n");
1525 		get_versym(ed, i, &vs, &nvs);
1526 		if (vs != NULL && nvs != len) {
1527 			warnx("#symbol not equal to #versym");
1528 			vs = NULL;
1529 		}
1530 	}
1531 	for (j = 0; j < len; j++) {
1532 		if (gelf_getsym(data, j, &sym) != &sym) {
1533 			warnx("gelf_getsym failed: %s", elf_errmsg(-1));
1534 			continue;
1535 		}
1536 		name = get_string(ed, s->link, sym.st_name);
1537 		if (ed->flags & SOLARIS_FMT) {
1538 			snprintf(idx, sizeof(idx), "[%d]", j);
1539 			if (ed->ec == ELFCLASS32)
1540 				PRT("%10s  ", idx);
1541 			else
1542 				PRT("%10s      ", idx);
1543 			PRT("0x%8.8jx ", (uintmax_t)sym.st_value);
1544 			if (ed->ec == ELFCLASS32)
1545 				PRT("0x%8.8jx  ", (uintmax_t)sym.st_size);
1546 			else
1547 				PRT("0x%12.12jx  ", (uintmax_t)sym.st_size);
1548 			PRT("%s ", st_type_S(GELF_ST_TYPE(sym.st_info)));
1549 			PRT("%s  ", st_bindings_S(GELF_ST_BIND(sym.st_info)));
1550 			PRT("%c  ", st_others[sym.st_other]);
1551 			PRT("%3u ", (vs == NULL ? 0 : vs[j]));
1552 			PRT("%-11.11s ", sh_name(ed, sym.st_shndx));
1553 			PRT("%s\n", name);
1554 		} else {
1555 			PRT("\nentry: %d\n", j);
1556 			PRT("\tst_name: %s\n", name);
1557 			PRT("\tst_value: %#jx\n", (uintmax_t)sym.st_value);
1558 			PRT("\tst_size: %ju\n", (uintmax_t)sym.st_size);
1559 			PRT("\tst_info: %s %s\n",
1560 			    st_type(ed->ehdr.e_machine,
1561 			    GELF_ST_TYPE(sym.st_info)),
1562 			    st_bindings(GELF_ST_BIND(sym.st_info)));
1563 			PRT("\tst_shndx: %ju\n", (uintmax_t)sym.st_shndx);
1564 		}
1565 	}
1566 }
1567 
1568 /*
1569  * Dump the symbol tables. (.dynsym and .symtab)
1570  */
1571 static void
1572 elf_print_symtabs(struct elfdump *ed)
1573 {
1574 	size_t i;
1575 
1576 	for (i = 0; i < ed->shnum; i++)
1577 		if ((ed->sl[i].type == SHT_SYMTAB ||
1578 		    ed->sl[i].type == SHT_DYNSYM) &&
1579 		    (STAILQ_EMPTY(&ed->snl) || find_name(ed, ed->sl[i].name)))
1580 			elf_print_symtab(ed, i);
1581 }
1582 
1583 /*
1584  * Dump the content of .dynamic section.
1585  */
1586 static void
1587 elf_print_dynamic(struct elfdump *ed)
1588 {
1589 	struct section	*s;
1590 	const char	*name;
1591 	char		 idx[10];
1592 	Elf_Data	*data;
1593 	GElf_Dyn	 dyn;
1594 	int		 elferr, i, len;
1595 
1596 	s = NULL;
1597 	for (i = 0; (size_t)i < ed->shnum; i++) {
1598 		s = &ed->sl[i];
1599 		if (s->type == SHT_DYNAMIC &&
1600 		    (STAILQ_EMPTY(&ed->snl) || find_name(ed, s->name)))
1601 			break;
1602 	}
1603 	if ((size_t)i >= ed->shnum)
1604 		return;
1605 
1606 	if (ed->flags & SOLARIS_FMT) {
1607 		PRT("Dynamic Section:  %s\n", s->name);
1608 		PRT("     index  tag               value\n");
1609 	} else
1610 		PRT("\ndynamic:\n");
1611 	(void) elf_errno();
1612 	if ((data = elf_getdata(s->scn, NULL)) == NULL) {
1613 		elferr = elf_errno();
1614 		if (elferr != 0)
1615 			warnx("elf_getdata failed: %s", elf_errmsg(elferr));
1616 		return;
1617 	}
1618 	assert(data->d_size == s->sz);
1619 	if (!get_ent_count(s, &len))
1620 		return;
1621 	for (i = 0; i < len; i++) {
1622 		if (gelf_getdyn(data, i, &dyn) != &dyn) {
1623 			warnx("gelf_getdyn failed: %s", elf_errmsg(-1));
1624 			continue;
1625 		}
1626 
1627 		if (ed->flags & SOLARIS_FMT) {
1628 			snprintf(idx, sizeof(idx), "[%d]", i);
1629 			PRT("%10s  %-16s ", idx, d_tags(dyn.d_tag));
1630 		} else {
1631 			PRT("\n");
1632 			PRT("entry: %d\n", i);
1633 			PRT("\td_tag: %s\n", d_tags(dyn.d_tag));
1634 		}
1635 		switch(dyn.d_tag) {
1636 		case DT_NEEDED:
1637 		case DT_SONAME:
1638 		case DT_RPATH:
1639 		case DT_RUNPATH:
1640 			if ((name = elf_strptr(ed->elf, s->link,
1641 				    dyn.d_un.d_val)) == NULL)
1642 				name = "";
1643 			if (ed->flags & SOLARIS_FMT)
1644 				PRT("%#-16jx %s\n", (uintmax_t)dyn.d_un.d_val,
1645 				    name);
1646 			else
1647 				PRT("\td_val: %s\n", name);
1648 			break;
1649 		case DT_PLTRELSZ:
1650 		case DT_RELA:
1651 		case DT_RELASZ:
1652 		case DT_RELAENT:
1653 		case DT_RELACOUNT:
1654 		case DT_STRSZ:
1655 		case DT_SYMENT:
1656 		case DT_RELSZ:
1657 		case DT_RELENT:
1658 		case DT_PLTREL:
1659 		case DT_VERDEF:
1660 		case DT_VERDEFNUM:
1661 		case DT_VERNEED:
1662 		case DT_VERNEEDNUM:
1663 		case DT_VERSYM:
1664 			if (ed->flags & SOLARIS_FMT)
1665 				PRT("%#jx\n", (uintmax_t)dyn.d_un.d_val);
1666 			else
1667 				PRT("\td_val: %ju\n",
1668 				    (uintmax_t)dyn.d_un.d_val);
1669 			break;
1670 		case DT_PLTGOT:
1671 		case DT_HASH:
1672 		case DT_GNU_HASH:
1673 		case DT_STRTAB:
1674 		case DT_SYMTAB:
1675 		case DT_INIT:
1676 		case DT_FINI:
1677 		case DT_REL:
1678 		case DT_JMPREL:
1679 		case DT_DEBUG:
1680 			if (ed->flags & SOLARIS_FMT)
1681 				PRT("%#jx\n", (uintmax_t)dyn.d_un.d_ptr);
1682 			else
1683 				PRT("\td_ptr: %#jx\n",
1684 				    (uintmax_t)dyn.d_un.d_ptr);
1685 			break;
1686 		case DT_NULL:
1687 		case DT_SYMBOLIC:
1688 		case DT_TEXTREL:
1689 		default:
1690 			if (ed->flags & SOLARIS_FMT)
1691 				PRT("\n");
1692 			break;
1693 		}
1694 	}
1695 }
1696 
1697 /*
1698  * Dump a .rel/.rela section entry.
1699  */
1700 static void
1701 elf_print_rel_entry(struct elfdump *ed, struct section *s, int j,
1702     struct rel_entry *r)
1703 {
1704 
1705 	if (ed->flags & SOLARIS_FMT) {
1706 		PRT("        %-23s ", elftc_reloc_type_str(ed->ehdr.e_machine,
1707 			GELF_R_TYPE(r->u_r.rel.r_info)));
1708 		PRT("%#12jx ", (uintmax_t)r->u_r.rel.r_offset);
1709 		if (r->type == SHT_RELA)
1710 			PRT("%10jd  ", (intmax_t)r->u_r.rela.r_addend);
1711 		else
1712 			PRT("    ");
1713 		PRT("%-14s ", s->name);
1714 		PRT("%s\n", r->symn);
1715 	} else {
1716 		PRT("\n");
1717 		PRT("entry: %d\n", j);
1718 		PRT("\tr_offset: %#jx\n", (uintmax_t)r->u_r.rel.r_offset);
1719 		if (ed->ec == ELFCLASS32)
1720 			PRT("\tr_info: %#jx\n", (uintmax_t)
1721 			    ELF32_R_INFO(ELF64_R_SYM(r->u_r.rel.r_info),
1722 			    ELF64_R_TYPE(r->u_r.rel.r_info)));
1723 		else
1724 			PRT("\tr_info: %#jx\n", (uintmax_t)r->u_r.rel.r_info);
1725 		if (r->type == SHT_RELA)
1726 			PRT("\tr_addend: %jd\n",
1727 			    (intmax_t)r->u_r.rela.r_addend);
1728 	}
1729 }
1730 
1731 /*
1732  * Dump a relocation section of type SHT_RELA.
1733  */
1734 static void
1735 elf_print_rela(struct elfdump *ed, struct section *s, Elf_Data *data)
1736 {
1737 	struct rel_entry	r;
1738 	int			j, len;
1739 
1740 	if (ed->flags & SOLARIS_FMT) {
1741 		PRT("\nRelocation Section:  %s\n", s->name);
1742 		PRT("        type                          offset     "
1743 		    "addend  section        with respect to\n");
1744 	} else
1745 		PRT("\nrelocation with addend (%s):\n", s->name);
1746 	r.type = SHT_RELA;
1747 	assert(data->d_size == s->sz);
1748 	if (!get_ent_count(s, &len))
1749 		return;
1750 	for (j = 0; j < len; j++) {
1751 		if (gelf_getrela(data, j, &r.u_r.rela) != &r.u_r.rela) {
1752 			warnx("gelf_getrela failed: %s",
1753 			    elf_errmsg(-1));
1754 			continue;
1755 		}
1756 		r.symn = get_symbol_name(ed, s->link,
1757 		    GELF_R_SYM(r.u_r.rela.r_info));
1758 		elf_print_rel_entry(ed, s, j, &r);
1759 	}
1760 }
1761 
1762 /*
1763  * Dump a relocation section of type SHT_REL.
1764  */
1765 static void
1766 elf_print_rel(struct elfdump *ed, struct section *s, Elf_Data *data)
1767 {
1768 	struct rel_entry	r;
1769 	int			j, len;
1770 
1771 	if (ed->flags & SOLARIS_FMT) {
1772 		PRT("\nRelocation Section:  %s\n", s->name);
1773 		PRT("        type                          offset     "
1774 		    "section        with respect to\n");
1775 	} else
1776 		PRT("\nrelocation (%s):\n", s->name);
1777 	r.type = SHT_REL;
1778 	assert(data->d_size == s->sz);
1779 	if (!get_ent_count(s, &len))
1780 		return;
1781 	for (j = 0; j < len; j++) {
1782 		if (gelf_getrel(data, j, &r.u_r.rel) != &r.u_r.rel) {
1783 			warnx("gelf_getrel failed: %s", elf_errmsg(-1));
1784 			continue;
1785 		}
1786 		r.symn = get_symbol_name(ed, s->link,
1787 		    GELF_R_SYM(r.u_r.rel.r_info));
1788 		elf_print_rel_entry(ed, s, j, &r);
1789 	}
1790 }
1791 
1792 /*
1793  * Dump relocation sections.
1794  */
1795 static void
1796 elf_print_reloc(struct elfdump *ed)
1797 {
1798 	struct section	*s;
1799 	Elf_Data	*data;
1800 	size_t		 i;
1801 	int		 elferr;
1802 
1803 	for (i = 0; i < ed->shnum; i++) {
1804 		s = &ed->sl[i];
1805 		if ((s->type == SHT_REL || s->type == SHT_RELA) &&
1806 		    (STAILQ_EMPTY(&ed->snl) || find_name(ed, s->name))) {
1807 			(void) elf_errno();
1808 			if ((data = elf_getdata(s->scn, NULL)) == NULL) {
1809 				elferr = elf_errno();
1810 				if (elferr != 0)
1811 					warnx("elf_getdata failed: %s",
1812 					    elf_errmsg(elferr));
1813 				continue;
1814 			}
1815 			if (s->type == SHT_REL)
1816 				elf_print_rel(ed, s, data);
1817 			else
1818 				elf_print_rela(ed, s, data);
1819 		}
1820 	}
1821 }
1822 
1823 /*
1824  * Dump the content of PT_INTERP segment.
1825  */
1826 static void
1827 elf_print_interp(struct elfdump *ed)
1828 {
1829 	const char *s;
1830 	GElf_Phdr phdr;
1831 	size_t filesize, i, phnum;
1832 
1833 	if (!STAILQ_EMPTY(&ed->snl) && find_name(ed, "PT_INTERP") == NULL)
1834 		return;
1835 
1836 	if ((s = elf_rawfile(ed->elf, &filesize)) == NULL) {
1837 		warnx("elf_rawfile failed: %s", elf_errmsg(-1));
1838 		return;
1839 	}
1840 	if (!elf_getphnum(ed->elf, &phnum)) {
1841 		warnx("elf_getphnum failed: %s", elf_errmsg(-1));
1842 		return;
1843 	}
1844 	for (i = 0; i < phnum; i++) {
1845 		if (gelf_getphdr(ed->elf, i, &phdr) != &phdr) {
1846 			warnx("elf_getphdr failed: %s", elf_errmsg(-1));
1847 			continue;
1848 		}
1849 		if (phdr.p_type == PT_INTERP) {
1850 			if (phdr.p_offset >= filesize) {
1851 				warnx("invalid phdr offset");
1852 				continue;
1853 			}
1854 			PRT("\ninterp:\n");
1855 			PRT("\t%s\n", s + phdr.p_offset);
1856 		}
1857 	}
1858 }
1859 
1860 /*
1861  * Search the relocation sections for entries referring to the .got section.
1862  */
1863 static void
1864 find_gotrel(struct elfdump *ed, struct section *gs, struct rel_entry *got)
1865 {
1866 	struct section		*s;
1867 	struct rel_entry	 r;
1868 	Elf_Data		*data;
1869 	size_t			 i;
1870 	int			 elferr, j, k, len;
1871 
1872 	for(i = 0; i < ed->shnum; i++) {
1873 		s = &ed->sl[i];
1874 		if (s->type != SHT_REL && s->type != SHT_RELA)
1875 			continue;
1876 		(void) elf_errno();
1877 		if ((data = elf_getdata(s->scn, NULL)) == NULL) {
1878 			elferr = elf_errno();
1879 			if (elferr != 0)
1880 				warnx("elf_getdata failed: %s",
1881 				    elf_errmsg(elferr));
1882 			return;
1883 		}
1884 		memset(&r, 0, sizeof(struct rel_entry));
1885 		r.type = s->type;
1886 		assert(data->d_size == s->sz);
1887 		if (!get_ent_count(s, &len))
1888 			return;
1889 		for (j = 0; j < len; j++) {
1890 			if (s->type == SHT_REL) {
1891 				if (gelf_getrel(data, j, &r.u_r.rel) !=
1892 				    &r.u_r.rel) {
1893 					warnx("gelf_getrel failed: %s",
1894 					    elf_errmsg(-1));
1895 					continue;
1896 				}
1897 			} else {
1898 				if (gelf_getrela(data, j, &r.u_r.rela) !=
1899 				    &r.u_r.rela) {
1900 					warnx("gelf_getrel failed: %s",
1901 					    elf_errmsg(-1));
1902 					continue;
1903 				}
1904 			}
1905 			if (r.u_r.rel.r_offset >= gs->addr &&
1906 			    r.u_r.rel.r_offset < gs->addr + gs->sz) {
1907 				r.symn = get_symbol_name(ed, s->link,
1908 				    GELF_R_SYM(r.u_r.rel.r_info));
1909 				k = (r.u_r.rel.r_offset - gs->addr) /
1910 				    gs->entsize;
1911 				memcpy(&got[k], &r, sizeof(struct rel_entry));
1912 			}
1913 		}
1914 	}
1915 }
1916 
1917 static void
1918 elf_print_got_section(struct elfdump *ed, struct section *s)
1919 {
1920 	struct rel_entry	*got;
1921 	Elf_Data		*data, dst;
1922 	int			 elferr, i, len;
1923 
1924 	if (s->entsize == 0) {
1925 		/* XXX IA64 GOT section generated by gcc has entry size 0. */
1926 		if (s->align != 0)
1927 			s->entsize = s->align;
1928 		else
1929 			return;
1930 	}
1931 
1932 	if (!get_ent_count(s, &len))
1933 		return;
1934 	if (ed->flags & SOLARIS_FMT)
1935 		PRT("\nGlobal Offset Table Section:  %s  (%d entries)\n",
1936 		    s->name, len);
1937 	else
1938 		PRT("\nglobal offset table: %s\n", s->name);
1939 	(void) elf_errno();
1940 	if ((data = elf_getdata(s->scn, NULL)) == NULL) {
1941 		elferr = elf_errno();
1942 		if (elferr != 0)
1943 			warnx("elf_getdata failed: %s", elf_errmsg(elferr));
1944 		return;
1945 	}
1946 
1947 	/*
1948 	 * GOT section has section type SHT_PROGBITS, thus libelf treats it as
1949 	 * byte stream and will not perform any translation on it. As a result,
1950 	 * an exlicit call to gelf_xlatetom is needed here. Depends on arch,
1951 	 * GOT section should be translated to either WORD or XWORD.
1952 	 */
1953 	if (ed->ec == ELFCLASS32)
1954 		data->d_type = ELF_T_WORD;
1955 	else
1956 		data->d_type = ELF_T_XWORD;
1957 	memcpy(&dst, data, sizeof(Elf_Data));
1958 	if (gelf_xlatetom(ed->elf, &dst, data, ed->ehdr.e_ident[EI_DATA]) !=
1959 	    &dst) {
1960 		warnx("gelf_xlatetom failed: %s", elf_errmsg(-1));
1961 		return;
1962 	}
1963 	assert(dst.d_size == s->sz);
1964 	if (ed->flags & SOLARIS_FMT) {
1965 		/*
1966 		 * In verbose/Solaris mode, we search the relocation sections
1967 		 * and try to find the corresponding reloc entry for each GOT
1968 		 * section entry.
1969 		 */
1970 		if ((got = calloc(len, sizeof(struct rel_entry))) == NULL)
1971 			err(EXIT_FAILURE, "calloc failed");
1972 		find_gotrel(ed, s, got);
1973 		if (ed->ec == ELFCLASS32) {
1974 			PRT(" ndx     addr      value    reloc              ");
1975 			PRT("addend   symbol\n");
1976 		} else {
1977 			PRT(" ndx     addr              value             ");
1978 			PRT("reloc              addend       symbol\n");
1979 		}
1980 		for(i = 0; i < len; i++) {
1981 			PRT("[%5.5d]  ", i);
1982 			if (ed->ec == ELFCLASS32) {
1983 				PRT("%-8.8jx  ",
1984 				    (uintmax_t) (s->addr + i * s->entsize));
1985 				PRT("%-8.8x ", *((uint32_t *)dst.d_buf + i));
1986 			} else {
1987 				PRT("%-16.16jx  ",
1988 				    (uintmax_t) (s->addr + i * s->entsize));
1989 				PRT("%-16.16jx  ",
1990 				    (uintmax_t) *((uint64_t *)dst.d_buf + i));
1991 			}
1992 			PRT("%-18s ", elftc_reloc_type_str(ed->ehdr.e_machine,
1993 				GELF_R_TYPE(got[i].u_r.rel.r_info)));
1994 			if (ed->ec == ELFCLASS32)
1995 				PRT("%-8.8jd ",
1996 				    (intmax_t)got[i].u_r.rela.r_addend);
1997 			else
1998 				PRT("%-12.12jd ",
1999 				    (intmax_t)got[i].u_r.rela.r_addend);
2000 			if (got[i].symn == NULL)
2001 				got[i].symn = "";
2002 			PRT("%s\n", got[i].symn);
2003 		}
2004 		free(got);
2005 	} else {
2006 		for(i = 0; i < len; i++) {
2007 			PRT("\nentry: %d\n", i);
2008 			if (ed->ec == ELFCLASS32)
2009 				PRT("\t%#x\n", *((uint32_t *)dst.d_buf + i));
2010 			else
2011 				PRT("\t%#jx\n",
2012 				    (uintmax_t) *((uint64_t *)dst.d_buf + i));
2013 		}
2014 	}
2015 }
2016 
2017 /*
2018  * Dump the content of Global Offset Table section.
2019  */
2020 static void
2021 elf_print_got(struct elfdump *ed)
2022 {
2023 	struct section	*s;
2024 	size_t		 i;
2025 
2026 	if (!STAILQ_EMPTY(&ed->snl))
2027 		return;
2028 
2029 	s = NULL;
2030 	for (i = 0; i < ed->shnum; i++) {
2031 		s = &ed->sl[i];
2032 		if (s->name && !strncmp(s->name, ".got", 4) &&
2033 		    (STAILQ_EMPTY(&ed->snl) || find_name(ed, s->name)))
2034 			elf_print_got_section(ed, s);
2035 	}
2036 }
2037 
2038 /*
2039  * Dump the content of .note.ABI-tag section.
2040  */
2041 static void
2042 elf_print_note(struct elfdump *ed)
2043 {
2044 	struct section	*s;
2045 	Elf_Data        *data;
2046 	Elf_Note	*en;
2047 	uint32_t	 namesz;
2048 	uint32_t	 descsz;
2049 	uint32_t	 desc;
2050 	size_t		 count;
2051 	int		 elferr, i;
2052 	uint8_t		*src;
2053 	char		 idx[10];
2054 
2055 	s = NULL;
2056 	for (i = 0; (size_t)i < ed->shnum; i++) {
2057 		s = &ed->sl[i];
2058 		if (s->type == SHT_NOTE && s->name &&
2059 		    !strcmp(s->name, ".note.ABI-tag") &&
2060 		    (STAILQ_EMPTY(&ed->snl) || find_name(ed, s->name)))
2061 			break;
2062 	}
2063 	if ((size_t)i >= ed->shnum)
2064 		return;
2065 	if (ed->flags & SOLARIS_FMT)
2066 		PRT("\nNote Section:  %s\n", s->name);
2067 	else
2068 		PRT("\nnote (%s):\n", s->name);
2069 	(void) elf_errno();
2070 	if ((data = elf_getdata(s->scn, NULL)) == NULL) {
2071 		elferr = elf_errno();
2072 		if (elferr != 0)
2073 			warnx("elf_getdata failed: %s", elf_errmsg(elferr));
2074 		return;
2075 	}
2076 	src = data->d_buf;
2077 	count = data->d_size;
2078 	while (count > sizeof(Elf_Note)) {
2079 		en = (Elf_Note *) (uintptr_t) src;
2080 		namesz = en->n_namesz;
2081 		descsz = en->n_descsz;
2082 		src += sizeof(Elf_Note);
2083 		count -= sizeof(Elf_Note);
2084 		if (roundup2(namesz, 4) + roundup2(descsz, 4) > count) {
2085 			warnx("truncated note section");
2086 			return;
2087 		}
2088 		if (ed->flags & SOLARIS_FMT) {
2089 			PRT("\n    type   %#x\n", en->n_type);
2090 			PRT("    namesz %#x:\n", en->n_namesz);
2091 			PRT("%s\n", src);
2092 		} else
2093 			PRT("\t%s ", src);
2094 		src += roundup2(namesz, 4);
2095 		count -= roundup2(namesz, 4);
2096 
2097 		/*
2098 		 * Note that we dump the whole desc part if we're in
2099 		 * "Solaris mode", while in the normal mode, we only look
2100 		 * at the first 4 bytes (a 32bit word) of the desc, i.e,
2101 		 * we assume that it's always a FreeBSD version number.
2102 		 */
2103 		if (ed->flags & SOLARIS_FMT) {
2104 			PRT("    descsz %#x:", en->n_descsz);
2105 			for (i = 0; (uint32_t)i < descsz; i++) {
2106 				if ((i & 0xF) == 0) {
2107 					snprintf(idx, sizeof(idx), "desc[%d]",
2108 					    i);
2109 					PRT("\n      %-9s", idx);
2110 				} else if ((i & 0x3) == 0)
2111 					PRT("  ");
2112 				PRT(" %2.2x", src[i]);
2113 			}
2114 			PRT("\n");
2115 		} else {
2116 			if (ed->ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
2117 				desc = be32dec(src);
2118 			else
2119 				desc = le32dec(src);
2120 			PRT("%d\n", desc);
2121 		}
2122 		src += roundup2(descsz, 4);
2123 		count -= roundup2(descsz, 4);
2124 	}
2125 }
2126 
2127 /*
2128  * Dump a hash table.
2129  */
2130 static void
2131 elf_print_svr4_hash(struct elfdump *ed, struct section *s)
2132 {
2133 	Elf_Data	*data;
2134 	uint32_t	*buf;
2135 	uint32_t	*bucket, *chain;
2136 	uint32_t	 nbucket, nchain;
2137 	uint32_t	*bl, *c, maxl, total;
2138 	uint32_t	 i, j;
2139 	int		 first, elferr;
2140 	char		 idx[10];
2141 
2142 	if (ed->flags & SOLARIS_FMT)
2143 		PRT("\nHash Section:  %s\n", s->name);
2144 	else
2145 		PRT("\nhash table (%s):\n", s->name);
2146 	(void) elf_errno();
2147 	if ((data = elf_getdata(s->scn, NULL)) == NULL) {
2148 		elferr = elf_errno();
2149 		if (elferr != 0)
2150 			warnx("elf_getdata failed: %s",
2151 			    elf_errmsg(elferr));
2152 		return;
2153 	}
2154 	if (data->d_size < 2 * sizeof(uint32_t)) {
2155 		warnx(".hash section too small");
2156 		return;
2157 	}
2158 	buf = data->d_buf;
2159 	nbucket = buf[0];
2160 	nchain = buf[1];
2161 	if (nbucket <= 0 || nchain <= 0) {
2162 		warnx("Malformed .hash section");
2163 		return;
2164 	}
2165 	if (data->d_size !=
2166 	    ((uint64_t)nbucket + (uint64_t)nchain + 2) * sizeof(uint32_t)) {
2167 		warnx("Malformed .hash section");
2168 		return;
2169 	}
2170 	bucket = &buf[2];
2171 	chain = &buf[2 + nbucket];
2172 
2173 	if (ed->flags & SOLARIS_FMT) {
2174 		maxl = 0;
2175 		if ((bl = calloc(nbucket, sizeof(*bl))) == NULL)
2176 			err(EXIT_FAILURE, "calloc failed");
2177 		for (i = 0; i < nbucket; i++)
2178 			for (j = bucket[i]; j > 0 && j < nchain; j = chain[j])
2179 				if (++bl[i] > maxl)
2180 					maxl = bl[i];
2181 		if ((c = calloc(maxl + 1, sizeof(*c))) == NULL)
2182 			err(EXIT_FAILURE, "calloc failed");
2183 		for (i = 0; i < nbucket; i++)
2184 			c[bl[i]]++;
2185 		PRT("    bucket    symndx    name\n");
2186 		for (i = 0; i < nbucket; i++) {
2187 			first = 1;
2188 			for (j = bucket[i]; j > 0 && j < nchain; j = chain[j]) {
2189 				if (first) {
2190 					PRT("%10d  ", i);
2191 					first = 0;
2192 				} else
2193 					PRT("            ");
2194 				snprintf(idx, sizeof(idx), "[%d]", j);
2195 				PRT("%-10s  ", idx);
2196 				PRT("%s\n", get_symbol_name(ed, s->link, j));
2197 			}
2198 		}
2199 		PRT("\n");
2200 		total = 0;
2201 		for (i = 0; i <= maxl; i++) {
2202 			total += c[i] * i;
2203 			PRT("%10u  buckets contain %8d symbols\n", c[i], i);
2204 		}
2205 		PRT("%10u  buckets         %8u symbols (globals)\n", nbucket,
2206 		    total);
2207 	} else {
2208 		PRT("\nnbucket: %u\n", nbucket);
2209 		PRT("nchain: %u\n\n", nchain);
2210 		for (i = 0; i < nbucket; i++)
2211 			PRT("bucket[%d]:\n\t%u\n\n", i, bucket[i]);
2212 		for (i = 0; i < nchain; i++)
2213 			PRT("chain[%d]:\n\t%u\n\n", i, chain[i]);
2214 	}
2215 }
2216 
2217 /*
2218  * Dump a 64bit hash table.
2219  */
2220 static void
2221 elf_print_svr4_hash64(struct elfdump *ed, struct section *s)
2222 {
2223 	Elf_Data	*data, dst;
2224 	uint64_t	*buf;
2225 	uint64_t	*bucket, *chain;
2226 	uint64_t	 nbucket, nchain;
2227 	uint64_t	*bl, *c, maxl, total;
2228 	uint64_t	 i, j;
2229 	int		 elferr, first;
2230 	char		 idx[10];
2231 
2232 	if (ed->flags & SOLARIS_FMT)
2233 		PRT("\nHash Section:  %s\n", s->name);
2234 	else
2235 		PRT("\nhash table (%s):\n", s->name);
2236 
2237 	/*
2238 	 * ALPHA uses 64-bit hash entries. Since libelf assumes that
2239 	 * .hash section contains only 32-bit entry, an explicit
2240 	 * gelf_xlatetom is needed here.
2241 	 */
2242 	(void) elf_errno();
2243 	if ((data = elf_rawdata(s->scn, NULL)) == NULL) {
2244 		elferr = elf_errno();
2245 		if (elferr != 0)
2246 			warnx("elf_rawdata failed: %s",
2247 			    elf_errmsg(elferr));
2248 		return;
2249 	}
2250 	data->d_type = ELF_T_XWORD;
2251 	memcpy(&dst, data, sizeof(Elf_Data));
2252 	if (gelf_xlatetom(ed->elf, &dst, data,
2253 		ed->ehdr.e_ident[EI_DATA]) != &dst) {
2254 		warnx("gelf_xlatetom failed: %s", elf_errmsg(-1));
2255 		return;
2256 	}
2257 	if (dst.d_size < 2 * sizeof(uint64_t)) {
2258 		warnx(".hash section too small");
2259 		return;
2260 	}
2261 	buf = dst.d_buf;
2262 	nbucket = buf[0];
2263 	nchain = buf[1];
2264 	if (nbucket <= 0 || nchain <= 0) {
2265 		warnx("Malformed .hash section");
2266 		return;
2267 	}
2268 	if (dst.d_size != (nbucket + nchain + 2) * sizeof(uint64_t)) {
2269 		warnx("Malformed .hash section");
2270 		return;
2271 	}
2272 	bucket = &buf[2];
2273 	chain = &buf[2 + nbucket];
2274 
2275 	if (ed->flags & SOLARIS_FMT) {
2276 		maxl = 0;
2277 		if ((bl = calloc(nbucket, sizeof(*bl))) == NULL)
2278 			err(EXIT_FAILURE, "calloc failed");
2279 		for (i = 0; i < nbucket; i++)
2280 			for (j = bucket[i]; j > 0 && j < nchain; j = chain[j])
2281 				if (++bl[i] > maxl)
2282 					maxl = bl[i];
2283 		if ((c = calloc(maxl + 1, sizeof(*c))) == NULL)
2284 			err(EXIT_FAILURE, "calloc failed");
2285 		for (i = 0; i < nbucket; i++)
2286 			c[bl[i]]++;
2287 		PRT("    bucket    symndx    name\n");
2288 		for (i = 0; i < nbucket; i++) {
2289 			first = 1;
2290 			for (j = bucket[i]; j > 0 && j < nchain; j = chain[j]) {
2291 				if (first) {
2292 					PRT("%10zu  ", i);
2293 					first = 0;
2294 				} else
2295 					PRT("            ");
2296 				snprintf(idx, sizeof(idx), "[%zu]", (size_t)j);
2297 				PRT("%-10s  ", idx);
2298 				PRT("%s\n", get_symbol_name(ed, s->link, j));
2299 			}
2300 		}
2301 		PRT("\n");
2302 		total = 0;
2303 		for (i = 0; i <= maxl; i++) {
2304 			total += c[i] * i;
2305 			PRT("%10ju  buckets contain %8zu symbols\n",
2306 			    (uintmax_t)c[i], i);
2307 		}
2308 		PRT("%10ju  buckets         %8ju symbols (globals)\n",
2309 		    (uintmax_t)nbucket, (uintmax_t)total);
2310 	} else {
2311 		PRT("\nnbucket: %ju\n", (uintmax_t)nbucket);
2312 		PRT("nchain: %ju\n\n", (uintmax_t)nchain);
2313 		for (i = 0; i < nbucket; i++)
2314 			PRT("bucket[%zu]:\n\t%ju\n\n", i, (uintmax_t)bucket[i]);
2315 		for (i = 0; i < nchain; i++)
2316 			PRT("chain[%zu]:\n\t%ju\n\n", i, (uintmax_t)chain[i]);
2317 	}
2318 
2319 }
2320 
2321 /*
2322  * Dump a GNU hash table.
2323  */
2324 static void
2325 elf_print_gnu_hash(struct elfdump *ed, struct section *s)
2326 {
2327 	struct section	*ds;
2328 	Elf_Data	*data;
2329 	uint32_t	*buf;
2330 	uint32_t	*bucket, *chain;
2331 	uint32_t	 nbucket, nchain, symndx, maskwords, shift2;
2332 	uint32_t	*bl, *c, maxl, total;
2333 	uint32_t	 i, j;
2334 	int		 first, elferr, dynsymcount;
2335 	char		 idx[10];
2336 
2337 	if (ed->flags & SOLARIS_FMT)
2338 		PRT("\nGNU Hash Section:  %s\n", s->name);
2339 	else
2340 		PRT("\ngnu hash table (%s):\n", s->name);
2341 	(void) elf_errno();
2342 	if ((data = elf_getdata(s->scn, NULL)) == NULL) {
2343 		elferr = elf_errno();
2344 		if (elferr != 0)
2345 			warnx("elf_getdata failed: %s",
2346 			    elf_errmsg(elferr));
2347 		return;
2348 	}
2349 	if (data->d_size < 4 * sizeof(uint32_t)) {
2350 		warnx(".gnu.hash section too small");
2351 		return;
2352 	}
2353 	buf = data->d_buf;
2354 	nbucket = buf[0];
2355 	symndx = buf[1];
2356 	maskwords = buf[2];
2357 	shift2 = buf[3];
2358 	buf += 4;
2359 	if (s->link >= ed->shnum) {
2360 		warnx("Malformed .gnu.hash section");
2361 		return;
2362 	}
2363 	ds = &ed->sl[s->link];
2364 	if (!get_ent_count(ds, &dynsymcount))
2365 		return;
2366 	if (symndx >= (uint32_t)dynsymcount) {
2367 		warnx("Malformed .gnu.hash section");
2368 		return;
2369 	}
2370 	nchain = dynsymcount - symndx;
2371 	if (data->d_size != 4 * sizeof(uint32_t) + maskwords *
2372 	    (ed->ec == ELFCLASS32 ? sizeof(uint32_t) : sizeof(uint64_t)) +
2373 	    ((uint64_t)nbucket + (uint64_t)nchain) * sizeof(uint32_t)) {
2374 		warnx("Malformed .gnu.hash section");
2375 		return;
2376 	}
2377 	bucket = buf + (ed->ec == ELFCLASS32 ? maskwords : maskwords * 2);
2378 	chain = bucket + nbucket;
2379 
2380 	if (ed->flags & SOLARIS_FMT) {
2381 		maxl = 0;
2382 		if ((bl = calloc(nbucket, sizeof(*bl))) == NULL)
2383 			err(EXIT_FAILURE, "calloc failed");
2384 		for (i = 0; i < nbucket; i++)
2385 			for (j = bucket[i]; j > 0 && j - symndx < nchain; j++) {
2386 				if (++bl[i] > maxl)
2387 					maxl = bl[i];
2388 				if (chain[j - symndx] & 1)
2389 					break;
2390 			}
2391 		if ((c = calloc(maxl + 1, sizeof(*c))) == NULL)
2392 			err(EXIT_FAILURE, "calloc failed");
2393 		for (i = 0; i < nbucket; i++)
2394 			c[bl[i]]++;
2395 		PRT("    bucket    symndx    name\n");
2396 		for (i = 0; i < nbucket; i++) {
2397 			first = 1;
2398 			for (j = bucket[i]; j > 0 && j - symndx < nchain; j++) {
2399 				if (first) {
2400 					PRT("%10d  ", i);
2401 					first = 0;
2402 				} else
2403 					PRT("            ");
2404 				snprintf(idx, sizeof(idx), "[%d]", j );
2405 				PRT("%-10s  ", idx);
2406 				PRT("%s\n", get_symbol_name(ed, s->link, j));
2407 				if (chain[j - symndx] & 1)
2408 					break;
2409 			}
2410 		}
2411 		PRT("\n");
2412 		total = 0;
2413 		for (i = 0; i <= maxl; i++) {
2414 			total += c[i] * i;
2415 			PRT("%10u  buckets contain %8d symbols\n", c[i], i);
2416 		}
2417 		PRT("%10u  buckets         %8u symbols (globals)\n", nbucket,
2418 		    total);
2419 	} else {
2420 		PRT("\nnbucket: %u\n", nbucket);
2421 		PRT("symndx: %u\n", symndx);
2422 		PRT("maskwords: %u\n", maskwords);
2423 		PRT("shift2: %u\n", shift2);
2424 		PRT("nchain: %u\n\n", nchain);
2425 		for (i = 0; i < nbucket; i++)
2426 			PRT("bucket[%d]:\n\t%u\n\n", i, bucket[i]);
2427 		for (i = 0; i < nchain; i++)
2428 			PRT("chain[%d]:\n\t%u\n\n", i, chain[i]);
2429 	}
2430 }
2431 
2432 /*
2433  * Dump hash tables.
2434  */
2435 static void
2436 elf_print_hash(struct elfdump *ed)
2437 {
2438 	struct section	*s;
2439 	size_t		 i;
2440 
2441 	for (i = 0; i < ed->shnum; i++) {
2442 		s = &ed->sl[i];
2443 		if ((s->type == SHT_HASH || s->type == SHT_GNU_HASH) &&
2444 		    (STAILQ_EMPTY(&ed->snl) || find_name(ed, s->name))) {
2445 			if (s->type == SHT_GNU_HASH)
2446 				elf_print_gnu_hash(ed, s);
2447 			else if (ed->ehdr.e_machine == EM_ALPHA &&
2448 			    s->entsize == 8)
2449 				elf_print_svr4_hash64(ed, s);
2450 			else
2451 				elf_print_svr4_hash(ed, s);
2452 		}
2453 	}
2454 }
2455 
2456 /*
2457  * Dump the content of a Version Definition(SHT_SUNW_Verdef) Section.
2458  */
2459 static void
2460 elf_print_verdef(struct elfdump *ed, struct section *s)
2461 {
2462 	Elf_Data	*data;
2463 	Elf32_Verdef	*vd;
2464 	Elf32_Verdaux	*vda;
2465 	const char 	*str;
2466 	char		 idx[10];
2467 	uint8_t		*buf, *end, *buf2;
2468 	int		 i, j, elferr, count;
2469 
2470 	if (ed->flags & SOLARIS_FMT)
2471 		PRT("Version Definition Section:  %s\n", s->name);
2472 	else
2473 		PRT("\nversion definition section (%s):\n", s->name);
2474 	(void) elf_errno();
2475 	if ((data = elf_getdata(s->scn, NULL)) == NULL) {
2476 		elferr = elf_errno();
2477 		if (elferr != 0)
2478 			warnx("elf_getdata failed: %s",
2479 			    elf_errmsg(elferr));
2480 		return;
2481 	}
2482 	buf = data->d_buf;
2483 	end = buf + data->d_size;
2484 	i = 0;
2485 	if (ed->flags & SOLARIS_FMT)
2486 		PRT("     index  version                     dependency\n");
2487 	while (buf + sizeof(Elf32_Verdef) <= end) {
2488 		vd = (Elf32_Verdef *) (uintptr_t) buf;
2489 		if (ed->flags & SOLARIS_FMT) {
2490 			snprintf(idx, sizeof(idx), "[%d]", vd->vd_ndx);
2491 			PRT("%10s  ", idx);
2492 		} else {
2493 			PRT("\nentry: %d\n", i++);
2494 			PRT("\tvd_version: %u\n", vd->vd_version);
2495 			PRT("\tvd_flags: %u\n", vd->vd_flags);
2496 			PRT("\tvd_ndx: %u\n", vd->vd_ndx);
2497 			PRT("\tvd_cnt: %u\n", vd->vd_cnt);
2498 			PRT("\tvd_hash: %u\n", vd->vd_hash);
2499 			PRT("\tvd_aux: %u\n", vd->vd_aux);
2500 			PRT("\tvd_next: %u\n\n", vd->vd_next);
2501 		}
2502 		buf2 = buf + vd->vd_aux;
2503 		j = 0;
2504 		count = 0;
2505 		while (buf2 + sizeof(Elf32_Verdaux) <= end && j < vd->vd_cnt) {
2506 			vda = (Elf32_Verdaux *) (uintptr_t) buf2;
2507 			str = get_string(ed, s->link, vda->vda_name);
2508 			if (ed->flags & SOLARIS_FMT) {
2509 				if (count == 0)
2510 					PRT("%-26.26s", str);
2511 				else if (count == 1)
2512 					PRT("  %-20.20s", str);
2513 				else {
2514 					PRT("\n%40.40s", "");
2515 					PRT("%s", str);
2516 				}
2517 			} else {
2518 				PRT("\t\tvda: %d\n", j++);
2519 				PRT("\t\t\tvda_name: %s\n", str);
2520 				PRT("\t\t\tvda_next: %u\n", vda->vda_next);
2521 			}
2522 			if (vda->vda_next == 0) {
2523 				if (ed->flags & SOLARIS_FMT) {
2524 					if (vd->vd_flags & VER_FLG_BASE) {
2525 						if (count == 0)
2526 							PRT("%-20.20s", "");
2527 						PRT("%s", "[ BASE ]");
2528 					}
2529 					PRT("\n");
2530 				}
2531 				break;
2532 			}
2533 			if (ed->flags & SOLARIS_FMT)
2534 				count++;
2535 			buf2 += vda->vda_next;
2536 		}
2537 		if (vd->vd_next == 0)
2538 			break;
2539 		buf += vd->vd_next;
2540 	}
2541 }
2542 
2543 /*
2544  * Dump the content of a Version Needed(SHT_SUNW_Verneed) Section.
2545  */
2546 static void
2547 elf_print_verneed(struct elfdump *ed, struct section *s)
2548 {
2549 	Elf_Data	*data;
2550 	Elf32_Verneed	*vn;
2551 	Elf32_Vernaux	*vna;
2552 	uint8_t		*buf, *end, *buf2;
2553 	int		 i, j, elferr, first;
2554 
2555 	if (ed->flags & SOLARIS_FMT)
2556 		PRT("\nVersion Needed Section:  %s\n", s->name);
2557 	else
2558 		PRT("\nversion need section (%s):\n", s->name);
2559 	(void) elf_errno();
2560 	if ((data = elf_getdata(s->scn, NULL)) == NULL) {
2561 		elferr = elf_errno();
2562 		if (elferr != 0)
2563 			warnx("elf_getdata failed: %s",
2564 			    elf_errmsg(elferr));
2565 		return;
2566 	}
2567 	buf = data->d_buf;
2568 	end = buf + data->d_size;
2569 	if (ed->flags & SOLARIS_FMT)
2570 		PRT("            file                        version\n");
2571 	i = 0;
2572 	while (buf + sizeof(Elf32_Verneed) <= end) {
2573 		vn = (Elf32_Verneed *) (uintptr_t) buf;
2574 		if (ed->flags & SOLARIS_FMT)
2575 			PRT("            %-26.26s  ",
2576 			    get_string(ed, s->link, vn->vn_file));
2577 		else {
2578 			PRT("\nentry: %d\n", i++);
2579 			PRT("\tvn_version: %u\n", vn->vn_version);
2580 			PRT("\tvn_cnt: %u\n", vn->vn_cnt);
2581 			PRT("\tvn_file: %s\n",
2582 			    get_string(ed, s->link, vn->vn_file));
2583 			PRT("\tvn_aux: %u\n", vn->vn_aux);
2584 			PRT("\tvn_next: %u\n\n", vn->vn_next);
2585 		}
2586 		buf2 = buf + vn->vn_aux;
2587 		j = 0;
2588 		first = 1;
2589 		while (buf2 + sizeof(Elf32_Vernaux) <= end && j < vn->vn_cnt) {
2590 			vna = (Elf32_Vernaux *) (uintptr_t) buf2;
2591 			if (ed->flags & SOLARIS_FMT) {
2592 				if (!first)
2593 					PRT("%40.40s", "");
2594 				else
2595 					first = 0;
2596 				PRT("%s\n", get_string(ed, s->link,
2597 				    vna->vna_name));
2598 			} else {
2599 				PRT("\t\tvna: %d\n", j++);
2600 				PRT("\t\t\tvna_hash: %u\n", vna->vna_hash);
2601 				PRT("\t\t\tvna_flags: %u\n", vna->vna_flags);
2602 				PRT("\t\t\tvna_other: %u\n", vna->vna_other);
2603 				PRT("\t\t\tvna_name: %s\n",
2604 				    get_string(ed, s->link, vna->vna_name));
2605 				PRT("\t\t\tvna_next: %u\n", vna->vna_next);
2606 			}
2607 			if (vna->vna_next == 0)
2608 				break;
2609 			buf2 += vna->vna_next;
2610 		}
2611 		if (vn->vn_next == 0)
2612 			break;
2613 		buf += vn->vn_next;
2614 	}
2615 }
2616 
2617 /*
2618  * Dump the symbol-versioning sections.
2619  */
2620 static void
2621 elf_print_symver(struct elfdump *ed)
2622 {
2623 	struct section	*s;
2624 	size_t		 i;
2625 
2626 	for (i = 0; i < ed->shnum; i++) {
2627 		s = &ed->sl[i];
2628 		if (!STAILQ_EMPTY(&ed->snl) && !find_name(ed, s->name))
2629 			continue;
2630 		if (s->type == SHT_SUNW_verdef)
2631 			elf_print_verdef(ed, s);
2632 		if (s->type == SHT_SUNW_verneed)
2633 			elf_print_verneed(ed, s);
2634 	}
2635 }
2636 
2637 /*
2638  * Dump the ELF checksum. See gelf_checksum(3) for details.
2639  */
2640 static void
2641 elf_print_checksum(struct elfdump *ed)
2642 {
2643 
2644 	if (!STAILQ_EMPTY(&ed->snl))
2645 		return;
2646 
2647 	PRT("\nelf checksum: %#lx\n", gelf_checksum(ed->elf));
2648 }
2649 
2650 #define	USAGE_MESSAGE	"\
2651 Usage: %s [options] file...\n\
2652   Display information about ELF objects and ar(1) archives.\n\n\
2653   Options:\n\
2654   -a                        Show all information.\n\
2655   -c                        Show shared headers.\n\
2656   -d                        Show dynamic symbols.\n\
2657   -e                        Show the ELF header.\n\
2658   -G                        Show the GOT.\n\
2659   -H | --help               Show a usage message and exit.\n\
2660   -h                        Show hash values.\n\
2661   -i                        Show the dynamic interpreter.\n\
2662   -k                        Show the ELF checksum.\n\
2663   -n                        Show the contents of note sections.\n\
2664   -N NAME                   Show the section named \"NAME\".\n\
2665   -p                        Show the program header.\n\
2666   -r                        Show relocations.\n\
2667   -s                        Show the symbol table.\n\
2668   -S                        Use the Solaris elfdump format.\n\
2669   -v                        Show symbol-versioning information.\n\
2670   -V | --version            Print a version identifier and exit.\n\
2671   -w FILE                   Write output to \"FILE\".\n"
2672 
2673 static void
2674 usage(void)
2675 {
2676 	fprintf(stderr, USAGE_MESSAGE, ELFTC_GETPROGNAME());
2677 	exit(EXIT_FAILURE);
2678 }
2679