readelf.c revision 1.23
1/*	$NetBSD: readelf.c,v 1.23 2019/12/17 08:02:00 martin Exp $	*/
2
3/*
4 * Copyright (c) Christos Zoulas 2003.
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 immediately at the beginning of the file, without modification,
12 *    this list of conditions, and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
21 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29#include "file.h"
30
31#ifndef lint
32#if 0
33FILE_RCSID("@(#)$File: readelf.c,v 1.168 2019/12/16 03:49:19 christos Exp $")
34#else
35__RCSID("$NetBSD: readelf.c,v 1.23 2019/12/17 08:02:00 martin Exp $");
36#endif
37#endif
38
39#ifdef BUILTIN_ELF
40#include <string.h>
41#include <ctype.h>
42#include <stdlib.h>
43#ifdef HAVE_UNISTD_H
44#include <unistd.h>
45#endif
46
47#include "readelf.h"
48#include "magic.h"
49
50#ifdef	ELFCORE
51private int dophn_core(struct magic_set *, int, int, int, off_t, int, size_t,
52    off_t, int *, uint16_t *);
53#endif
54private int dophn_exec(struct magic_set *, int, int, int, off_t, int, size_t,
55    off_t, int, int *, uint16_t *);
56private int doshn(struct magic_set *, int, int, int, off_t, int, size_t,
57    off_t, int, int, int *, uint16_t *);
58private size_t donote(struct magic_set *, void *, size_t, size_t, int,
59    int, size_t, int *, uint16_t *, int, off_t, int, off_t);
60
61#define	ELF_ALIGN(a)	((((a) + align - 1) / align) * align)
62
63#define isquote(c) (strchr("'\"`", (c)) != NULL)
64
65private uint16_t getu16(int, uint16_t);
66private uint32_t getu32(int, uint32_t);
67private uint64_t getu64(int, uint64_t);
68
69#define MAX_PHNUM	128
70#define	MAX_SHNUM	32768
71#define SIZE_UNKNOWN	CAST(off_t, -1)
72
73private int
74toomany(struct magic_set *ms, const char *name, uint16_t num)
75{
76	if (file_printf(ms, ", too many %s (%u)", name, num) == -1)
77		return -1;
78	return 1;
79}
80
81private uint16_t
82getu16(int swap, uint16_t value)
83{
84	union {
85		uint16_t ui;
86		char c[2];
87	} retval, tmpval;
88
89	if (swap) {
90		tmpval.ui = value;
91
92		retval.c[0] = tmpval.c[1];
93		retval.c[1] = tmpval.c[0];
94
95		return retval.ui;
96	} else
97		return value;
98}
99
100private uint32_t
101getu32(int swap, uint32_t value)
102{
103	union {
104		uint32_t ui;
105		char c[4];
106	} retval, tmpval;
107
108	if (swap) {
109		tmpval.ui = value;
110
111		retval.c[0] = tmpval.c[3];
112		retval.c[1] = tmpval.c[2];
113		retval.c[2] = tmpval.c[1];
114		retval.c[3] = tmpval.c[0];
115
116		return retval.ui;
117	} else
118		return value;
119}
120
121private uint64_t
122getu64(int swap, uint64_t value)
123{
124	union {
125		uint64_t ui;
126		char c[8];
127	} retval, tmpval;
128
129	if (swap) {
130		tmpval.ui = value;
131
132		retval.c[0] = tmpval.c[7];
133		retval.c[1] = tmpval.c[6];
134		retval.c[2] = tmpval.c[5];
135		retval.c[3] = tmpval.c[4];
136		retval.c[4] = tmpval.c[3];
137		retval.c[5] = tmpval.c[2];
138		retval.c[6] = tmpval.c[1];
139		retval.c[7] = tmpval.c[0];
140
141		return retval.ui;
142	} else
143		return value;
144}
145
146#define elf_getu16(swap, value) getu16(swap, value)
147#define elf_getu32(swap, value) getu32(swap, value)
148#define elf_getu64(swap, value) getu64(swap, value)
149
150#define xsh_addr	(clazz == ELFCLASS32			\
151			 ? CAST(void *, &sh32)			\
152			 : CAST(void *, &sh64))
153#define xsh_sizeof	(clazz == ELFCLASS32			\
154			 ? sizeof(sh32)				\
155			 : sizeof(sh64))
156#define xsh_size	CAST(size_t, (clazz == ELFCLASS32	\
157			 ? elf_getu32(swap, sh32.sh_size)	\
158			 : elf_getu64(swap, sh64.sh_size)))
159#define xsh_offset	CAST(off_t, (clazz == ELFCLASS32	\
160			 ? elf_getu32(swap, sh32.sh_offset)	\
161			 : elf_getu64(swap, sh64.sh_offset)))
162#define xsh_type	(clazz == ELFCLASS32			\
163			 ? elf_getu32(swap, sh32.sh_type)	\
164			 : elf_getu32(swap, sh64.sh_type))
165#define xsh_name    	(clazz == ELFCLASS32			\
166			 ? elf_getu32(swap, sh32.sh_name)	\
167			 : elf_getu32(swap, sh64.sh_name))
168
169#define xph_addr	(clazz == ELFCLASS32			\
170			 ? CAST(void *, &ph32)			\
171			 : CAST(void *, &ph64))
172#define xph_sizeof	(clazz == ELFCLASS32			\
173			 ? sizeof(ph32)				\
174			 : sizeof(ph64))
175#define xph_type	(clazz == ELFCLASS32			\
176			 ? elf_getu32(swap, ph32.p_type)	\
177			 : elf_getu32(swap, ph64.p_type))
178#define xph_offset	CAST(off_t, (clazz == ELFCLASS32	\
179			 ? elf_getu32(swap, ph32.p_offset)	\
180			 : elf_getu64(swap, ph64.p_offset)))
181#define xph_align	CAST(size_t, (clazz == ELFCLASS32	\
182			 ? CAST(off_t, (ph32.p_align ? 		\
183			    elf_getu32(swap, ph32.p_align) : 4))\
184			 : CAST(off_t, (ph64.p_align ?		\
185			    elf_getu64(swap, ph64.p_align) : 4))))
186#define xph_vaddr	CAST(size_t, (clazz == ELFCLASS32	\
187			 ? CAST(off_t, (ph32.p_vaddr ? 		\
188			    elf_getu32(swap, ph32.p_vaddr) : 4))\
189			 : CAST(off_t, (ph64.p_vaddr ?		\
190			    elf_getu64(swap, ph64.p_vaddr) : 4))))
191#define xph_filesz	CAST(size_t, (clazz == ELFCLASS32	\
192			 ? elf_getu32(swap, ph32.p_filesz)	\
193			 : elf_getu64(swap, ph64.p_filesz)))
194#define xph_memsz	CAST(size_t, ((clazz == ELFCLASS32	\
195			 ? elf_getu32(swap, ph32.p_memsz)	\
196			 : elf_getu64(swap, ph64.p_memsz))))
197#define xnh_addr	(clazz == ELFCLASS32			\
198			 ? CAST(void *, &nh32)			\
199			 : CAST(void *, &nh64))
200#define xnh_sizeof	(clazz == ELFCLASS32			\
201			 ? sizeof(nh32)				\
202			 : sizeof(nh64))
203#define xnh_type	(clazz == ELFCLASS32			\
204			 ? elf_getu32(swap, nh32.n_type)	\
205			 : elf_getu32(swap, nh64.n_type))
206#define xnh_namesz	(clazz == ELFCLASS32			\
207			 ? elf_getu32(swap, nh32.n_namesz)	\
208			 : elf_getu32(swap, nh64.n_namesz))
209#define xnh_descsz	(clazz == ELFCLASS32			\
210			 ? elf_getu32(swap, nh32.n_descsz)	\
211			 : elf_getu32(swap, nh64.n_descsz))
212
213#define xdh_addr	(clazz == ELFCLASS32			\
214			 ? CAST(void *, &dh32)			\
215			 : CAST(void *, &dh64))
216#define xdh_sizeof	(clazz == ELFCLASS32			\
217			 ? sizeof(dh32)				\
218			 : sizeof(dh64))
219#define xdh_tag		(clazz == ELFCLASS32			\
220			 ? elf_getu32(swap, dh32.d_tag)		\
221			 : elf_getu64(swap, dh64.d_tag))
222#define xdh_val		(clazz == ELFCLASS32			\
223			 ? elf_getu32(swap, dh32.d_un.d_val)	\
224			 : elf_getu64(swap, dh64.d_un.d_val))
225
226#define xcap_addr	(clazz == ELFCLASS32			\
227			 ? CAST(void *, &cap32)			\
228			 : CAST(void *, &cap64))
229#define xcap_sizeof	(clazz == ELFCLASS32			\
230			 ? sizeof(cap32)			\
231			 : sizeof(cap64))
232#define xcap_tag	(clazz == ELFCLASS32			\
233			 ? elf_getu32(swap, cap32.c_tag)	\
234			 : elf_getu64(swap, cap64.c_tag))
235#define xcap_val	(clazz == ELFCLASS32			\
236			 ? elf_getu32(swap, cap32.c_un.c_val)	\
237			 : elf_getu64(swap, cap64.c_un.c_val))
238
239#define xauxv_addr	(clazz == ELFCLASS32			\
240			 ? CAST(void *, &auxv32)		\
241			 : CAST(void *, &auxv64))
242#define xauxv_sizeof	(clazz == ELFCLASS32			\
243			 ? sizeof(auxv32)			\
244			 : sizeof(auxv64))
245#define xauxv_type	(clazz == ELFCLASS32			\
246			 ? elf_getu32(swap, auxv32.a_type)	\
247			 : elf_getu64(swap, auxv64.a_type))
248#define xauxv_val	(clazz == ELFCLASS32			\
249			 ? elf_getu32(swap, auxv32.a_v)		\
250			 : elf_getu64(swap, auxv64.a_v))
251
252#define prpsoffsets(i)	(clazz == ELFCLASS32			\
253			 ? prpsoffsets32[i]			\
254			 : prpsoffsets64[i])
255
256#ifdef ELFCORE
257/*
258 * Try larger offsets first to avoid false matches
259 * from earlier data that happen to look like strings.
260 */
261static const size_t	prpsoffsets32[] = {
262#ifdef USE_NT_PSINFO
263	104,		/* SunOS 5.x (command line) */
264	88,		/* SunOS 5.x (short name) */
265#endif /* USE_NT_PSINFO */
266
267	100,		/* SunOS 5.x (command line) */
268	84,		/* SunOS 5.x (short name) */
269
270	44,		/* Linux (command line) */
271	28,		/* Linux (short name) */
272
273	48,		/* Linux PowerPC (command line) */
274	32,		/* Linux PowerPC (short name) */
275
276	8,		/* FreeBSD */
277};
278
279static const size_t	prpsoffsets64[] = {
280#ifdef USE_NT_PSINFO
281	152,		/* SunOS 5.x (command line) */
282	136,		/* SunOS 5.x (short name) */
283#endif /* USE_NT_PSINFO */
284
285	136,		/* SunOS 5.x, 64-bit (command line) */
286	120,		/* SunOS 5.x, 64-bit (short name) */
287
288	56,		/* Linux (command line) */
289	40,             /* Linux (tested on core from 2.4.x, short name) */
290
291	16,		/* FreeBSD, 64-bit */
292};
293
294#define	NOFFSETS32	__arraycount(prpsoffsets32)
295#define NOFFSETS64	__arraycount(prpsoffsets64)
296
297#define NOFFSETS	(clazz == ELFCLASS32 ? NOFFSETS32 : NOFFSETS64)
298
299/*
300 * Look through the program headers of an executable image, searching
301 * for a PT_NOTE section of type NT_PRPSINFO, with a name "CORE" or
302 * "FreeBSD"; if one is found, try looking in various places in its
303 * contents for a 16-character string containing only printable
304 * characters - if found, that string should be the name of the program
305 * that dropped core.  Note: right after that 16-character string is,
306 * at least in SunOS 5.x (and possibly other SVR4-flavored systems) and
307 * Linux, a longer string (80 characters, in 5.x, probably other
308 * SVR4-flavored systems, and Linux) containing the start of the
309 * command line for that program.
310 *
311 * SunOS 5.x core files contain two PT_NOTE sections, with the types
312 * NT_PRPSINFO (old) and NT_PSINFO (new).  These structs contain the
313 * same info about the command name and command line, so it probably
314 * isn't worthwhile to look for NT_PSINFO, but the offsets are provided
315 * above (see USE_NT_PSINFO), in case we ever decide to do so.  The
316 * NT_PRPSINFO and NT_PSINFO sections are always in order and adjacent;
317 * the SunOS 5.x file command relies on this (and prefers the latter).
318 *
319 * The signal number probably appears in a section of type NT_PRSTATUS,
320 * but that's also rather OS-dependent, in ways that are harder to
321 * dissect with heuristics, so I'm not bothering with the signal number.
322 * (I suppose the signal number could be of interest in situations where
323 * you don't have the binary of the program that dropped core; if you
324 * *do* have that binary, the debugger will probably tell you what
325 * signal it was.)
326 */
327
328#define	OS_STYLE_SVR4		0
329#define	OS_STYLE_FREEBSD	1
330#define	OS_STYLE_NETBSD		2
331
332private const char os_style_names[][8] = {
333	"SVR4",
334	"FreeBSD",
335	"NetBSD",
336};
337
338#define FLAGS_CORE_STYLE		0x0003
339
340#define FLAGS_DID_CORE			0x0004
341#define FLAGS_DID_OS_NOTE		0x0008
342#define FLAGS_DID_BUILD_ID		0x0010
343#define FLAGS_DID_CORE_STYLE		0x0020
344#define FLAGS_DID_NETBSD_PAX		0x0040
345#define FLAGS_DID_NETBSD_MARCH		0x0080
346#define FLAGS_DID_NETBSD_CMODEL		0x0100
347#define FLAGS_DID_NETBSD_EMULATION	0x0200
348#define FLAGS_DID_NETBSD_UNKNOWN	0x0400
349#define FLAGS_IS_CORE			0x0800
350#define FLAGS_DID_AUXV			0x1000
351
352private int
353dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
354    int num, size_t size, off_t fsize, int *flags, uint16_t *notecount)
355{
356	Elf32_Phdr ph32;
357	Elf64_Phdr ph64;
358	size_t offset, len;
359	unsigned char nbuf[BUFSIZ];
360	ssize_t bufsize;
361	off_t ph_off = off;
362	int ph_num = num;
363
364	if (num == 0) {
365		if (file_printf(ms, ", no program header") == -1)
366			return -1;
367		return 0;
368	}
369	if (size != xph_sizeof) {
370		if (file_printf(ms, ", corrupted program header size") == -1)
371			return -1;
372		return 0;
373	}
374
375	/*
376	 * Loop through all the program headers.
377	 */
378	for ( ; num; num--) {
379		if (pread(fd, xph_addr, xph_sizeof, off) <
380		    CAST(ssize_t, xph_sizeof)) {
381			file_badread(ms);
382			return -1;
383		}
384		off += size;
385
386		if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
387			/* Perhaps warn here */
388			continue;
389		}
390
391		if (xph_type != PT_NOTE)
392			continue;
393
394		/*
395		 * This is a PT_NOTE section; loop through all the notes
396		 * in the section.
397		 */
398		len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf);
399		if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) {
400			file_badread(ms);
401			return -1;
402		}
403		offset = 0;
404		for (;;) {
405			if (offset >= CAST(size_t, bufsize))
406				break;
407			offset = donote(ms, nbuf, offset, CAST(size_t, bufsize),
408			    clazz, swap, 4, flags, notecount, fd, ph_off,
409			    ph_num, fsize);
410			if (offset == 0)
411				break;
412
413		}
414	}
415	return 0;
416}
417#endif
418
419static int
420do_note_netbsd_version(struct magic_set *ms, int swap, void *v)
421{
422	uint32_t desc;
423	memcpy(&desc, v, sizeof(desc));
424	desc = elf_getu32(swap, desc);
425
426	if (file_printf(ms, ", for NetBSD") == -1)
427		return -1;
428	/*
429	 * The version number used to be stuck as 199905, and was thus
430	 * basically content-free.  Newer versions of NetBSD have fixed
431	 * this and now use the encoding of __NetBSD_Version__:
432	 *
433	 *	MMmmrrpp00
434	 *
435	 * M = major version
436	 * m = minor version
437	 * r = release ["",A-Z,Z[A-Z] but numeric]
438	 * p = patchlevel
439	 */
440	if (desc > 100000000U) {
441		uint32_t ver_patch = (desc / 100) % 100;
442		uint32_t ver_rel = (desc / 10000) % 100;
443		uint32_t ver_min = (desc / 1000000) % 100;
444		uint32_t ver_maj = desc / 100000000;
445
446		if (file_printf(ms, " %u.%u", ver_maj, ver_min) == -1)
447			return -1;
448		if (ver_rel == 0 && ver_patch != 0) {
449			if (file_printf(ms, ".%u", ver_patch) == -1)
450				return -1;
451		} else if (ver_rel != 0) {
452			while (ver_rel > 26) {
453				if (file_printf(ms, "Z") == -1)
454					return -1;
455				ver_rel -= 26;
456			}
457			if (file_printf(ms, "%c", 'A' + ver_rel - 1)
458			    == -1)
459				return -1;
460		}
461	}
462	return 0;
463}
464
465static int
466do_note_freebsd_version(struct magic_set *ms, int swap, void *v)
467{
468	uint32_t desc;
469
470	memcpy(&desc, v, sizeof(desc));
471	desc = elf_getu32(swap, desc);
472	if (file_printf(ms, ", for FreeBSD") == -1)
473		return -1;
474
475	/*
476	 * Contents is __FreeBSD_version, whose relation to OS
477	 * versions is defined by a huge table in the Porter's
478	 * Handbook.  This is the general scheme:
479	 *
480	 * Releases:
481	 * 	Mmp000 (before 4.10)
482	 * 	Mmi0p0 (before 5.0)
483	 * 	Mmm0p0
484	 *
485	 * Development branches:
486	 * 	Mmpxxx (before 4.6)
487	 * 	Mmp1xx (before 4.10)
488	 * 	Mmi1xx (before 5.0)
489	 * 	M000xx (pre-M.0)
490	 * 	Mmm1xx
491	 *
492	 * M = major version
493	 * m = minor version
494	 * i = minor version increment (491000 -> 4.10)
495	 * p = patchlevel
496	 * x = revision
497	 *
498	 * The first release of FreeBSD to use ELF by default
499	 * was version 3.0.
500	 */
501	if (desc == 460002) {
502		if (file_printf(ms, " 4.6.2") == -1)
503			return -1;
504	} else if (desc < 460100) {
505		if (file_printf(ms, " %d.%d", desc / 100000,
506		    desc / 10000 % 10) == -1)
507			return -1;
508		if (desc / 1000 % 10 > 0)
509			if (file_printf(ms, ".%d", desc / 1000 % 10) == -1)
510				return -1;
511		if ((desc % 1000 > 0) || (desc % 100000 == 0))
512			if (file_printf(ms, " (%d)", desc) == -1)
513				return -1;
514	} else if (desc < 500000) {
515		if (file_printf(ms, " %d.%d", desc / 100000,
516		    desc / 10000 % 10 + desc / 1000 % 10) == -1)
517			return -1;
518		if (desc / 100 % 10 > 0) {
519			if (file_printf(ms, " (%d)", desc) == -1)
520				return -1;
521		} else if (desc / 10 % 10 > 0) {
522			if (file_printf(ms, ".%d", desc / 10 % 10) == -1)
523				return -1;
524		}
525	} else {
526		if (file_printf(ms, " %d.%d", desc / 100000,
527		    desc / 1000 % 100) == -1)
528			return -1;
529		if ((desc / 100 % 10 > 0) ||
530		    (desc % 100000 / 100 == 0)) {
531			if (file_printf(ms, " (%d)", desc) == -1)
532				return -1;
533		} else if (desc / 10 % 10 > 0) {
534			if (file_printf(ms, ".%d", desc / 10 % 10) == -1)
535				return -1;
536		}
537	}
538	return 0;
539}
540
541private int
542/*ARGSUSED*/
543do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
544    int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz,
545    size_t noff, size_t doff, int *flags)
546{
547	if (namesz == 4 && strcmp(RCAST(char *, &nbuf[noff]), "GNU") == 0 &&
548	    type == NT_GNU_BUILD_ID && (descsz >= 4 && descsz <= 20)) {
549		uint8_t desc[20];
550		const char *btype;
551		uint32_t i;
552		*flags |= FLAGS_DID_BUILD_ID;
553		switch (descsz) {
554		case 8:
555		    btype = "xxHash";
556		    break;
557		case 16:
558		    btype = "md5/uuid";
559		    break;
560		case 20:
561		    btype = "sha1";
562		    break;
563		default:
564		    btype = "unknown";
565		    break;
566		}
567		if (file_printf(ms, ", BuildID[%s]=", btype) == -1)
568			return -1;
569		memcpy(desc, &nbuf[doff], descsz);
570		for (i = 0; i < descsz; i++)
571		    if (file_printf(ms, "%02x", desc[i]) == -1)
572			return -1;
573		return 1;
574	}
575	if (namesz == 4 && strcmp(RCAST(char *, &nbuf[noff]), "Go") == 0 &&
576	    type == NT_GO_BUILD_ID && descsz < 128) {
577		if (file_printf(ms, ", Go BuildID=%.*s",
578		    CAST(int, descsz), RCAST(char *, &nbuf[doff])) == -1)
579			return -1;
580		return 1;
581	}
582	return 0;
583}
584
585private int
586do_os_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
587    int swap, uint32_t namesz, uint32_t descsz,
588    size_t noff, size_t doff, int *flags)
589{
590	const char *name = RCAST(const char *, &nbuf[noff]);
591
592	if (namesz == 5 && strcmp(name, "SuSE") == 0 &&
593		type == NT_GNU_VERSION && descsz == 2) {
594		*flags |= FLAGS_DID_OS_NOTE;
595		if (file_printf(ms, ", for SuSE %d.%d", nbuf[doff],
596		    nbuf[doff + 1]) == -1)
597		    return -1;
598	    return 1;
599	}
600
601	if (namesz == 4 && strcmp(name, "GNU") == 0 &&
602	    type == NT_GNU_VERSION && descsz == 16) {
603		uint32_t desc[4];
604		memcpy(desc, &nbuf[doff], sizeof(desc));
605
606		*flags |= FLAGS_DID_OS_NOTE;
607		if (file_printf(ms, ", for GNU/") == -1)
608			return -1;
609		switch (elf_getu32(swap, desc[0])) {
610		case GNU_OS_LINUX:
611			if (file_printf(ms, "Linux") == -1)
612				return -1;
613			break;
614		case GNU_OS_HURD:
615			if (file_printf(ms, "Hurd") == -1)
616				return -1;
617			break;
618		case GNU_OS_SOLARIS:
619			if (file_printf(ms, "Solaris") == -1)
620				return -1;
621			break;
622		case GNU_OS_KFREEBSD:
623			if (file_printf(ms, "kFreeBSD") == -1)
624				return -1;
625			break;
626		case GNU_OS_KNETBSD:
627			if (file_printf(ms, "kNetBSD") == -1)
628				return -1;
629			break;
630		default:
631			if (file_printf(ms, "<unknown>") == -1)
632				return -1;
633		}
634		if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]),
635		    elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1)
636			return -1;
637		return 1;
638	}
639
640	if (namesz == 7 && strcmp(name, "NetBSD") == 0) {
641	    	if (type == NT_NETBSD_VERSION && descsz == 4) {
642			*flags |= FLAGS_DID_OS_NOTE;
643			if (do_note_netbsd_version(ms, swap, &nbuf[doff]) == -1)
644				return -1;
645			return 1;
646		}
647	}
648
649	if (namesz == 8 && strcmp(name, "FreeBSD") == 0) {
650	    	if (type == NT_FREEBSD_VERSION && descsz == 4) {
651			*flags |= FLAGS_DID_OS_NOTE;
652			if (do_note_freebsd_version(ms, swap, &nbuf[doff])
653			    == -1)
654				return -1;
655			return 1;
656		}
657	}
658
659	if (namesz == 8 && strcmp(name, "OpenBSD") == 0 &&
660	    type == NT_OPENBSD_VERSION && descsz == 4) {
661		*flags |= FLAGS_DID_OS_NOTE;
662		if (file_printf(ms, ", for OpenBSD") == -1)
663			return -1;
664		/* Content of note is always 0 */
665		return 1;
666	}
667
668	if (namesz == 10 && strcmp(name, "DragonFly") == 0 &&
669	    type == NT_DRAGONFLY_VERSION && descsz == 4) {
670		uint32_t desc;
671		*flags |= FLAGS_DID_OS_NOTE;
672		if (file_printf(ms, ", for DragonFly") == -1)
673			return -1;
674		memcpy(&desc, &nbuf[doff], sizeof(desc));
675		desc = elf_getu32(swap, desc);
676		if (file_printf(ms, " %d.%d.%d", desc / 100000,
677		    desc / 10000 % 10, desc % 10000) == -1)
678			return -1;
679		return 1;
680	}
681	return 0;
682}
683
684private int
685do_pax_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
686    int swap, uint32_t namesz, uint32_t descsz,
687    size_t noff, size_t doff, int *flags)
688{
689	const char *name = RCAST(const char *, &nbuf[noff]);
690
691	if (namesz == 4 && strcmp(name, "PaX") == 0 &&
692	    type == NT_NETBSD_PAX && descsz == 4) {
693		static const char *pax[] = {
694		    "+mprotect",
695		    "-mprotect",
696		    "+segvguard",
697		    "-segvguard",
698		    "+ASLR",
699		    "-ASLR",
700		};
701		uint32_t desc;
702		size_t i;
703		int did = 0;
704
705		*flags |= FLAGS_DID_NETBSD_PAX;
706		memcpy(&desc, &nbuf[doff], sizeof(desc));
707		desc = elf_getu32(swap, desc);
708
709		if (desc && file_printf(ms, ", PaX: ") == -1)
710			return -1;
711
712		for (i = 0; i < __arraycount(pax); i++) {
713			if (((1 << CAST(int, i)) & desc) == 0)
714				continue;
715			if (file_printf(ms, "%s%s", did++ ? "," : "",
716			    pax[i]) == -1)
717				return -1;
718		}
719		return 1;
720	}
721	return 0;
722}
723
724private int
725do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
726    int swap, uint32_t namesz, uint32_t descsz,
727    size_t noff, size_t doff, int *flags, size_t size, int clazz)
728{
729#ifdef ELFCORE
730	const char *name = RCAST(const char *, &nbuf[noff]);
731
732	int os_style = -1;
733	/*
734	 * Sigh.  The 2.0.36 kernel in Debian 2.1, at
735	 * least, doesn't correctly implement name
736	 * sections, in core dumps, as specified by
737	 * the "Program Linking" section of "UNIX(R) System
738	 * V Release 4 Programmer's Guide: ANSI C and
739	 * Programming Support Tools", because my copy
740	 * clearly says "The first 'namesz' bytes in 'name'
741	 * contain a *null-terminated* [emphasis mine]
742	 * character representation of the entry's owner
743	 * or originator", but the 2.0.36 kernel code
744	 * doesn't include the terminating null in the
745	 * name....
746	 */
747	if ((namesz == 4 && strncmp(name, "CORE", 4) == 0) ||
748	    (namesz == 5 && strcmp(name, "CORE") == 0)) {
749		os_style = OS_STYLE_SVR4;
750	}
751
752	if ((namesz == 8 && strcmp(name, "FreeBSD") == 0)) {
753		os_style = OS_STYLE_FREEBSD;
754	}
755
756	if ((namesz >= 11 && strncmp(name, "NetBSD-CORE", 11)
757	    == 0)) {
758		os_style = OS_STYLE_NETBSD;
759	}
760
761	if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
762		if (file_printf(ms, ", %s-style", os_style_names[os_style])
763		    == -1)
764			return -1;
765		*flags |= FLAGS_DID_CORE_STYLE;
766		*flags |= os_style;
767	}
768
769	switch (os_style) {
770	case OS_STYLE_NETBSD:
771		if (type == NT_NETBSD_CORE_PROCINFO) {
772			char sbuf[512];
773			struct NetBSD_elfcore_procinfo pi;
774			memset(&pi, 0, sizeof(pi));
775			memcpy(&pi, nbuf + doff, MIN(descsz, sizeof(pi)));
776
777			if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, "
778			    "gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)",
779			    file_printable(sbuf, sizeof(sbuf),
780			    RCAST(char *, pi.cpi_name), sizeof(pi.cpi_name)),
781			    elf_getu32(swap, CAST(uint32_t, pi.cpi_pid)),
782			    elf_getu32(swap, pi.cpi_euid),
783			    elf_getu32(swap, pi.cpi_egid),
784			    elf_getu32(swap, pi.cpi_nlwps),
785			    elf_getu32(swap, CAST(uint32_t, pi.cpi_siglwp)),
786			    elf_getu32(swap, pi.cpi_signo),
787			    elf_getu32(swap, pi.cpi_sigcode)) == -1)
788				return -1;
789
790			*flags |= FLAGS_DID_CORE;
791			return 1;
792		}
793		break;
794
795	case OS_STYLE_FREEBSD:
796		if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
797			size_t argoff, pidoff;
798
799			if (clazz == ELFCLASS32)
800				argoff = 4 + 4 + 17;
801			else
802				argoff = 4 + 4 + 8 + 17;
803			if (file_printf(ms, ", from '%.80s'", nbuf + doff +
804			    argoff) == -1)
805				return -1;
806			pidoff = argoff + 81 + 2;
807			if (doff + pidoff + 4 <= size) {
808				if (file_printf(ms, ", pid=%u",
809				    elf_getu32(swap, *RCAST(uint32_t *, (nbuf +
810				    doff + pidoff)))) == -1)
811					return -1;
812			}
813			*flags |= FLAGS_DID_CORE;
814		}
815		break;
816
817	default:
818		if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
819			size_t i, j;
820			unsigned char c;
821			/*
822			 * Extract the program name.  We assume
823			 * it to be 16 characters (that's what it
824			 * is in SunOS 5.x and Linux).
825			 *
826			 * Unfortunately, it's at a different offset
827			 * in various OSes, so try multiple offsets.
828			 * If the characters aren't all printable,
829			 * reject it.
830			 */
831			for (i = 0; i < NOFFSETS; i++) {
832				unsigned char *cname, *cp;
833				size_t reloffset = prpsoffsets(i);
834				size_t noffset = doff + reloffset;
835				size_t k;
836				for (j = 0; j < 16; j++, noffset++,
837				    reloffset++) {
838					/*
839					 * Make sure we're not past
840					 * the end of the buffer; if
841					 * we are, just give up.
842					 */
843					if (noffset >= size)
844						goto tryanother;
845
846					/*
847					 * Make sure we're not past
848					 * the end of the contents;
849					 * if we are, this obviously
850					 * isn't the right offset.
851					 */
852					if (reloffset >= descsz)
853						goto tryanother;
854
855					c = nbuf[noffset];
856					if (c == '\0') {
857						/*
858						 * A '\0' at the
859						 * beginning is
860						 * obviously wrong.
861						 * Any other '\0'
862						 * means we're done.
863						 */
864						if (j == 0)
865							goto tryanother;
866						else
867							break;
868					} else {
869						/*
870						 * A nonprintable
871						 * character is also
872						 * wrong.
873						 */
874						if (!isprint(c) || isquote(c))
875							goto tryanother;
876					}
877				}
878				/*
879				 * Well, that worked.
880				 */
881
882				/*
883				 * Try next offsets, in case this match is
884				 * in the middle of a string.
885				 */
886				for (k = i + 1 ; k < NOFFSETS; k++) {
887					size_t no;
888					int adjust = 1;
889					if (prpsoffsets(k) >= prpsoffsets(i))
890						continue;
891					for (no = doff + prpsoffsets(k);
892					     no < doff + prpsoffsets(i); no++)
893						adjust = adjust
894						         && isprint(nbuf[no]);
895					if (adjust)
896						i = k;
897				}
898
899				cname = CAST(unsigned char *,
900				    &nbuf[doff + prpsoffsets(i)]);
901				for (cp = cname; cp < nbuf + size && *cp
902				    && isprint(*cp); cp++)
903					continue;
904				/*
905				 * Linux apparently appends a space at the end
906				 * of the command line: remove it.
907				 */
908				while (cp > cname && isspace(cp[-1]))
909					cp--;
910				if (file_printf(ms, ", from '%.*s'",
911				    CAST(int, cp - cname), cname) == -1)
912					return -1;
913				*flags |= FLAGS_DID_CORE;
914				return 1;
915
916			tryanother:
917				;
918			}
919		}
920		break;
921	}
922#endif
923	return 0;
924}
925
926private off_t
927get_offset_from_virtaddr(struct magic_set *ms, int swap, int clazz, int fd,
928    off_t off, int num, off_t fsize, uint64_t virtaddr)
929{
930	Elf32_Phdr ph32;
931	Elf64_Phdr ph64;
932
933	/*
934	 * Loop through all the program headers and find the header with
935	 * virtual address in which the "virtaddr" belongs to.
936	 */
937	for ( ; num; num--) {
938		if (pread(fd, xph_addr, xph_sizeof, off) <
939		    CAST(ssize_t, xph_sizeof)) {
940			file_badread(ms);
941			return -1;
942		}
943		off += xph_sizeof;
944
945		if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
946			/* Perhaps warn here */
947			continue;
948		}
949
950		if (virtaddr >= xph_vaddr && virtaddr < xph_vaddr + xph_filesz)
951			return xph_offset + (virtaddr - xph_vaddr);
952	}
953	return 0;
954}
955
956private size_t
957get_string_on_virtaddr(struct magic_set *ms,
958    int swap, int clazz, int fd, off_t ph_off, int ph_num,
959    off_t fsize, uint64_t virtaddr, char *buf, ssize_t buflen)
960{
961	char *bptr;
962	off_t offset;
963
964	if (buflen == 0)
965		return 0;
966
967	offset = get_offset_from_virtaddr(ms, swap, clazz, fd, ph_off, ph_num,
968	    fsize, virtaddr);
969	if (offset < 0 ||
970	    (buflen = pread(fd, buf, CAST(size_t, buflen), offset)) <= 0) {
971		file_badread(ms);
972		return 0;
973	}
974
975	buf[buflen - 1] = '\0';
976
977	/* We expect only printable characters, so return if buffer contains
978	 * non-printable character before the '\0' or just '\0'. */
979	for (bptr = buf; *bptr && isprint(CAST(unsigned char, *bptr)); bptr++)
980		continue;
981	if (*bptr != '\0')
982		return 0;
983
984	return bptr - buf;
985}
986
987
988/*ARGSUSED*/
989private int
990do_auxv_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
991    int swap, uint32_t namesz __attribute__((__unused__)),
992    uint32_t descsz __attribute__((__unused__)),
993    size_t noff __attribute__((__unused__)), size_t doff,
994    int *flags, size_t size __attribute__((__unused__)), int clazz,
995    int fd, off_t ph_off, int ph_num, off_t fsize)
996{
997#ifdef ELFCORE
998	Aux32Info auxv32;
999	Aux64Info auxv64;
1000	size_t elsize = xauxv_sizeof;
1001	const char *tag;
1002	int is_string;
1003	size_t nval;
1004
1005	if ((*flags & (FLAGS_IS_CORE|FLAGS_DID_CORE_STYLE)) !=
1006	    (FLAGS_IS_CORE|FLAGS_DID_CORE_STYLE))
1007		return 0;
1008
1009	switch (*flags & FLAGS_CORE_STYLE) {
1010	case OS_STYLE_SVR4:
1011		if (type != NT_AUXV)
1012			return 0;
1013		break;
1014#ifdef notyet
1015	case OS_STYLE_NETBSD:
1016		if (type != NT_NETBSD_CORE_AUXV)
1017			return 0;
1018		break;
1019	case OS_STYLE_FREEBSD:
1020		if (type != NT_FREEBSD_PROCSTAT_AUXV)
1021			return 0;
1022		break;
1023#endif
1024	default:
1025		return 0;
1026	}
1027
1028	*flags |= FLAGS_DID_AUXV;
1029
1030	nval = 0;
1031	for (size_t off = 0; off + elsize <= descsz; off += elsize) {
1032		memcpy(xauxv_addr, &nbuf[doff + off], xauxv_sizeof);
1033		/* Limit processing to 50 vector entries to prevent DoS */
1034		if (nval++ >= 50) {
1035			file_error(ms, 0, "Too many ELF Auxv elements");
1036			return 1;
1037		}
1038
1039		switch(xauxv_type) {
1040		case AT_LINUX_EXECFN:
1041			is_string = 1;
1042			tag = "execfn";
1043			break;
1044		case AT_LINUX_PLATFORM:
1045			is_string = 1;
1046			tag = "platform";
1047			break;
1048		case AT_LINUX_UID:
1049			is_string = 0;
1050			tag = "real uid";
1051			break;
1052		case AT_LINUX_GID:
1053			is_string = 0;
1054			tag = "real gid";
1055			break;
1056		case AT_LINUX_EUID:
1057			is_string = 0;
1058			tag = "effective uid";
1059			break;
1060		case AT_LINUX_EGID:
1061			is_string = 0;
1062			tag = "effective gid";
1063			break;
1064		default:
1065			is_string = 0;
1066			tag = NULL;
1067			break;
1068		}
1069
1070		if (tag == NULL)
1071			continue;
1072
1073		if (is_string) {
1074			char buf[256];
1075			ssize_t buflen;
1076			buflen = get_string_on_virtaddr(ms, swap, clazz, fd,
1077			    ph_off, ph_num, fsize, xauxv_val, buf, sizeof(buf));
1078
1079			if (buflen == 0)
1080				continue;
1081
1082			if (file_printf(ms, ", %s: '%s'", tag, buf) == -1)
1083				return -1;
1084		} else {
1085			if (file_printf(ms, ", %s: %d", tag,
1086			    CAST(int, xauxv_val)) == -1)
1087				return -1;
1088		}
1089	}
1090	return 1;
1091#else
1092	return 0;
1093#endif
1094}
1095
1096private size_t
1097dodynamic(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
1098    int clazz, int swap)
1099{
1100	Elf32_Dyn dh32;
1101	Elf64_Dyn dh64;
1102	unsigned char *dbuf = CAST(unsigned char *, vbuf);
1103
1104	if (xdh_sizeof + offset > size) {
1105		/*
1106		 * We're out of note headers.
1107		 */
1108		return xdh_sizeof + offset;
1109	}
1110
1111	memcpy(xdh_addr, &dbuf[offset], xdh_sizeof);
1112	offset += xdh_sizeof;
1113
1114	switch (xdh_tag) {
1115	case DT_FLAGS_1:
1116		if (xdh_val & DF_1_PIE)
1117			ms->mode |= 0111;
1118		else
1119			ms->mode &= ~0111;
1120		break;
1121	default:
1122		break;
1123	}
1124	return offset;
1125}
1126
1127
1128private size_t
1129donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
1130    int clazz, int swap, size_t align, int *flags, uint16_t *notecount,
1131    int fd, off_t ph_off, int ph_num, off_t fsize)
1132{
1133	Elf32_Nhdr nh32;
1134	Elf64_Nhdr nh64;
1135	size_t noff, doff;
1136	uint32_t namesz, descsz;
1137	unsigned char *nbuf = CAST(unsigned char *, vbuf);
1138
1139	if (*notecount == 0)
1140		return 0;
1141	--*notecount;
1142
1143	if (xnh_sizeof + offset > size) {
1144		/*
1145		 * We're out of note headers.
1146		 */
1147		return xnh_sizeof + offset;
1148	}
1149	/*XXX: GCC */
1150	memset(&nh32, 0, sizeof(nh32));
1151	memset(&nh64, 0, sizeof(nh64));
1152
1153	memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);
1154	offset += xnh_sizeof;
1155
1156	namesz = xnh_namesz;
1157	descsz = xnh_descsz;
1158
1159	if ((namesz == 0) && (descsz == 0)) {
1160		/*
1161		 * We're out of note headers.
1162		 */
1163		return (offset >= size) ? offset : size;
1164	}
1165
1166	if (namesz & 0x80000000) {
1167		if (file_printf(ms, ", bad note name size %#lx",
1168		    CAST(unsigned long, namesz)) == -1)
1169			return 0;
1170	    return 0;
1171	}
1172
1173	if (descsz & 0x80000000) {
1174		if (file_printf(ms, ", bad note description size %#lx",
1175		    CAST(unsigned long, descsz)) == -1)
1176		    	return 0;
1177	    return 0;
1178	}
1179
1180	noff = offset;
1181	doff = ELF_ALIGN(offset + namesz);
1182
1183	if (offset + namesz > size) {
1184		/*
1185		 * We're past the end of the buffer.
1186		 */
1187		return doff;
1188	}
1189
1190	offset = ELF_ALIGN(doff + descsz);
1191	if (doff + descsz > size) {
1192		/*
1193		 * We're past the end of the buffer.
1194		 */
1195		return (offset >= size) ? offset : size;
1196	}
1197
1198
1199	if ((*flags & FLAGS_DID_OS_NOTE) == 0) {
1200		if (do_os_note(ms, nbuf, xnh_type, swap,
1201		    namesz, descsz, noff, doff, flags))
1202			return offset;
1203	}
1204
1205	if ((*flags & FLAGS_DID_BUILD_ID) == 0) {
1206		if (do_bid_note(ms, nbuf, xnh_type, swap,
1207		    namesz, descsz, noff, doff, flags))
1208			return offset;
1209	}
1210
1211	if ((*flags & FLAGS_DID_NETBSD_PAX) == 0) {
1212		if (do_pax_note(ms, nbuf, xnh_type, swap,
1213		    namesz, descsz, noff, doff, flags))
1214			return offset;
1215	}
1216
1217	if ((*flags & FLAGS_DID_CORE) == 0) {
1218		if (do_core_note(ms, nbuf, xnh_type, swap,
1219		    namesz, descsz, noff, doff, flags, size, clazz))
1220			return offset;
1221	}
1222
1223	if ((*flags & FLAGS_DID_AUXV) == 0) {
1224		if (do_auxv_note(ms, nbuf, xnh_type, swap,
1225			namesz, descsz, noff, doff, flags, size, clazz,
1226			fd, ph_off, ph_num, fsize))
1227			return offset;
1228	}
1229
1230	if (namesz == 7 && strcmp(RCAST(char *, &nbuf[noff]), "NetBSD") == 0) {
1231		int descw, flag;
1232		const char *str, *tag;
1233		if (descsz > 100)
1234			descsz = 100;
1235		switch (xnh_type) {
1236	    	case NT_NETBSD_VERSION:
1237			return offset;
1238		case NT_NETBSD_MARCH:
1239			flag = FLAGS_DID_NETBSD_MARCH;
1240			tag = "compiled for";
1241			break;
1242		case NT_NETBSD_CMODEL:
1243			flag = FLAGS_DID_NETBSD_CMODEL;
1244			tag = "compiler model";
1245			break;
1246		case NT_NETBSD_EMULATION:
1247			flag = FLAGS_DID_NETBSD_EMULATION;
1248			tag = "emulation:";
1249			break;
1250		default:
1251			if (*flags & FLAGS_DID_NETBSD_UNKNOWN)
1252				return offset;
1253			*flags |= FLAGS_DID_NETBSD_UNKNOWN;
1254			if (file_printf(ms, ", note=%u", xnh_type) == -1)
1255				return offset;
1256			return offset;
1257		}
1258
1259		if (*flags & flag)
1260			return offset;
1261		str = RCAST(const char *, &nbuf[doff]);
1262		descw = CAST(int, descsz);
1263		*flags |= flag;
1264		file_printf(ms, ", %s: %.*s", tag, descw, str);
1265		return offset;
1266	}
1267
1268	return offset;
1269}
1270
1271/* SunOS 5.x hardware capability descriptions */
1272typedef struct cap_desc {
1273	uint64_t cd_mask;
1274	const char *cd_name;
1275} cap_desc_t;
1276
1277static const cap_desc_t cap_desc_sparc[] = {
1278	{ AV_SPARC_MUL32,		"MUL32" },
1279	{ AV_SPARC_DIV32,		"DIV32" },
1280	{ AV_SPARC_FSMULD,		"FSMULD" },
1281	{ AV_SPARC_V8PLUS,		"V8PLUS" },
1282	{ AV_SPARC_POPC,		"POPC" },
1283	{ AV_SPARC_VIS,			"VIS" },
1284	{ AV_SPARC_VIS2,		"VIS2" },
1285	{ AV_SPARC_ASI_BLK_INIT,	"ASI_BLK_INIT" },
1286	{ AV_SPARC_FMAF,		"FMAF" },
1287	{ AV_SPARC_FJFMAU,		"FJFMAU" },
1288	{ AV_SPARC_IMA,			"IMA" },
1289	{ 0, NULL }
1290};
1291
1292static const cap_desc_t cap_desc_386[] = {
1293	{ AV_386_FPU,			"FPU" },
1294	{ AV_386_TSC,			"TSC" },
1295	{ AV_386_CX8,			"CX8" },
1296	{ AV_386_SEP,			"SEP" },
1297	{ AV_386_AMD_SYSC,		"AMD_SYSC" },
1298	{ AV_386_CMOV,			"CMOV" },
1299	{ AV_386_MMX,			"MMX" },
1300	{ AV_386_AMD_MMX,		"AMD_MMX" },
1301	{ AV_386_AMD_3DNow,		"AMD_3DNow" },
1302	{ AV_386_AMD_3DNowx,		"AMD_3DNowx" },
1303	{ AV_386_FXSR,			"FXSR" },
1304	{ AV_386_SSE,			"SSE" },
1305	{ AV_386_SSE2,			"SSE2" },
1306	{ AV_386_PAUSE,			"PAUSE" },
1307	{ AV_386_SSE3,			"SSE3" },
1308	{ AV_386_MON,			"MON" },
1309	{ AV_386_CX16,			"CX16" },
1310	{ AV_386_AHF,			"AHF" },
1311	{ AV_386_TSCP,			"TSCP" },
1312	{ AV_386_AMD_SSE4A,		"AMD_SSE4A" },
1313	{ AV_386_POPCNT,		"POPCNT" },
1314	{ AV_386_AMD_LZCNT,		"AMD_LZCNT" },
1315	{ AV_386_SSSE3,			"SSSE3" },
1316	{ AV_386_SSE4_1,		"SSE4.1" },
1317	{ AV_386_SSE4_2,		"SSE4.2" },
1318	{ 0, NULL }
1319};
1320
1321private int
1322doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num,
1323    size_t size, off_t fsize, int mach, int strtab, int *flags,
1324    uint16_t *notecount)
1325{
1326	Elf32_Shdr sh32;
1327	Elf64_Shdr sh64;
1328	int stripped = 1, has_debug_info = 0;
1329	size_t nbadcap = 0;
1330	void *nbuf;
1331	off_t noff, coff, name_off;
1332	uint64_t cap_hw1 = 0;	/* SunOS 5.x hardware capabilities */
1333	uint64_t cap_sf1 = 0;	/* SunOS 5.x software capabilities */
1334	char name[50];
1335	ssize_t namesize;
1336
1337	if (num == 0) {
1338		if (file_printf(ms, ", no section header") == -1)
1339			return -1;
1340		return 0;
1341	}
1342	if (size != xsh_sizeof) {
1343		if (file_printf(ms, ", corrupted section header size") == -1)
1344			return -1;
1345		return 0;
1346	}
1347
1348	/* Read offset of name section to be able to read section names later */
1349	if (pread(fd, xsh_addr, xsh_sizeof, CAST(off_t, (off + size * strtab)))
1350	    < CAST(ssize_t, xsh_sizeof)) {
1351		if (file_printf(ms, ", missing section headers") == -1)
1352			return -1;
1353		return 0;
1354	}
1355	name_off = xsh_offset;
1356
1357	if (fsize != SIZE_UNKNOWN && fsize < name_off) {
1358		if (file_printf(ms, ", too large section header offset %jd",
1359		    (intmax_t)name_off) == -1)
1360			return -1;
1361		return 0;
1362	}
1363
1364	for ( ; num; num--) {
1365		/* Read the name of this section. */
1366		if ((namesize = pread(fd, name, sizeof(name) - 1,
1367		    name_off + xsh_name)) == -1) {
1368			file_badread(ms);
1369			return -1;
1370		}
1371		name[namesize] = '\0';
1372		if (strcmp(name, ".debug_info") == 0) {
1373			has_debug_info = 1;
1374			stripped = 0;
1375		}
1376
1377		if (pread(fd, xsh_addr, xsh_sizeof, off) <
1378		    CAST(ssize_t, xsh_sizeof)) {
1379			file_badread(ms);
1380			return -1;
1381		}
1382		off += size;
1383
1384		/* Things we can determine before we seek */
1385		switch (xsh_type) {
1386		case SHT_SYMTAB:
1387#if 0
1388		case SHT_DYNSYM:
1389#endif
1390			stripped = 0;
1391			break;
1392		default:
1393			if (fsize != SIZE_UNKNOWN && xsh_offset > fsize) {
1394				/* Perhaps warn here */
1395				continue;
1396			}
1397			break;
1398		}
1399
1400
1401		/* Things we can determine when we seek */
1402		switch (xsh_type) {
1403		case SHT_NOTE:
1404			if (CAST(uintmax_t, (xsh_size + xsh_offset)) >
1405			    CAST(uintmax_t, fsize)) {
1406				if (file_printf(ms,
1407				    ", note offset/size %#" INTMAX_T_FORMAT
1408				    "x+%#" INTMAX_T_FORMAT "x exceeds"
1409				    " file size %#" INTMAX_T_FORMAT "x",
1410				    CAST(uintmax_t, xsh_offset),
1411				    CAST(uintmax_t, xsh_size),
1412				    CAST(uintmax_t, fsize)) == -1)
1413					return -1;
1414				return 0;
1415			}
1416			if ((nbuf = malloc(xsh_size)) == NULL) {
1417				file_error(ms, errno, "Cannot allocate memory"
1418				    " for note");
1419				return -1;
1420			}
1421			if (pread(fd, nbuf, xsh_size, xsh_offset) <
1422			    CAST(ssize_t, xsh_size)) {
1423				file_badread(ms);
1424				free(nbuf);
1425				return -1;
1426			}
1427
1428			noff = 0;
1429			for (;;) {
1430				if (noff >= CAST(off_t, xsh_size))
1431					break;
1432				noff = donote(ms, nbuf, CAST(size_t, noff),
1433				    xsh_size, clazz, swap, 4, flags, notecount,
1434				    fd, 0, 0, 0);
1435				if (noff == 0)
1436					break;
1437			}
1438			free(nbuf);
1439			break;
1440		case SHT_SUNW_cap:
1441			switch (mach) {
1442			case EM_SPARC:
1443			case EM_SPARCV9:
1444			case EM_IA_64:
1445			case EM_386:
1446			case EM_AMD64:
1447				break;
1448			default:
1449				goto skip;
1450			}
1451
1452			if (nbadcap > 5)
1453				break;
1454			if (lseek(fd, xsh_offset, SEEK_SET)
1455			    == CAST(off_t, -1)) {
1456				file_badseek(ms);
1457				return -1;
1458			}
1459			coff = 0;
1460			for (;;) {
1461				Elf32_Cap cap32;
1462				Elf64_Cap cap64;
1463				char cbuf[/*CONSTCOND*/
1464				    MAX(sizeof(cap32), sizeof(cap64))];
1465				if ((coff += xcap_sizeof) >
1466				    CAST(off_t, xsh_size))
1467					break;
1468				if (read(fd, cbuf, CAST(size_t, xcap_sizeof)) !=
1469				    CAST(ssize_t, xcap_sizeof)) {
1470					file_badread(ms);
1471					return -1;
1472				}
1473				if (cbuf[0] == 'A') {
1474#ifdef notyet
1475					char *p = cbuf + 1;
1476					uint32_t len, tag;
1477					memcpy(&len, p, sizeof(len));
1478					p += 4;
1479					len = getu32(swap, len);
1480					if (memcmp("gnu", p, 3) != 0) {
1481					    if (file_printf(ms,
1482						", unknown capability %.3s", p)
1483						== -1)
1484						return -1;
1485					    break;
1486					}
1487					p += strlen(p) + 1;
1488					tag = *p++;
1489					memcpy(&len, p, sizeof(len));
1490					p += 4;
1491					len = getu32(swap, len);
1492					if (tag != 1) {
1493					    if (file_printf(ms, ", unknown gnu"
1494						" capability tag %d", tag)
1495						== -1)
1496						return -1;
1497					    break;
1498					}
1499					// gnu attributes
1500#endif
1501					break;
1502				}
1503				memcpy(xcap_addr, cbuf, xcap_sizeof);
1504				switch (xcap_tag) {
1505				case CA_SUNW_NULL:
1506					break;
1507				case CA_SUNW_HW_1:
1508					cap_hw1 |= xcap_val;
1509					break;
1510				case CA_SUNW_SF_1:
1511					cap_sf1 |= xcap_val;
1512					break;
1513				default:
1514					if (file_printf(ms,
1515					    ", with unknown capability "
1516					    "%#" INT64_T_FORMAT "x = %#"
1517					    INT64_T_FORMAT "x",
1518					    CAST(unsigned long long, xcap_tag),
1519					    CAST(unsigned long long, xcap_val))
1520					    == -1)
1521						return -1;
1522					if (nbadcap++ > 2)
1523						coff = xsh_size;
1524					break;
1525				}
1526			}
1527			/*FALLTHROUGH*/
1528		skip:
1529		default:
1530			break;
1531		}
1532	}
1533
1534	if (has_debug_info) {
1535		if (file_printf(ms, ", with debug_info") == -1)
1536			return -1;
1537	}
1538	if (file_printf(ms, ", %sstripped", stripped ? "" : "not ") == -1)
1539		return -1;
1540	if (cap_hw1) {
1541		const cap_desc_t *cdp;
1542		switch (mach) {
1543		case EM_SPARC:
1544		case EM_SPARC32PLUS:
1545		case EM_SPARCV9:
1546			cdp = cap_desc_sparc;
1547			break;
1548		case EM_386:
1549		case EM_IA_64:
1550		case EM_AMD64:
1551			cdp = cap_desc_386;
1552			break;
1553		default:
1554			cdp = NULL;
1555			break;
1556		}
1557		if (file_printf(ms, ", uses") == -1)
1558			return -1;
1559		if (cdp) {
1560			while (cdp->cd_name) {
1561				if (cap_hw1 & cdp->cd_mask) {
1562					if (file_printf(ms,
1563					    " %s", cdp->cd_name) == -1)
1564						return -1;
1565					cap_hw1 &= ~cdp->cd_mask;
1566				}
1567				++cdp;
1568			}
1569			if (cap_hw1)
1570				if (file_printf(ms,
1571				    " unknown hardware capability %#"
1572				    INT64_T_FORMAT "x",
1573				    CAST(unsigned long long, cap_hw1)) == -1)
1574					return -1;
1575		} else {
1576			if (file_printf(ms,
1577			    " hardware capability %#" INT64_T_FORMAT "x",
1578			    CAST(unsigned long long, cap_hw1)) == -1)
1579				return -1;
1580		}
1581	}
1582	if (cap_sf1) {
1583		if (cap_sf1 & SF1_SUNW_FPUSED) {
1584			if (file_printf(ms,
1585			    (cap_sf1 & SF1_SUNW_FPKNWN)
1586			    ? ", uses frame pointer"
1587			    : ", not known to use frame pointer") == -1)
1588				return -1;
1589		}
1590		cap_sf1 &= ~SF1_SUNW_MASK;
1591		if (cap_sf1)
1592			if (file_printf(ms,
1593			    ", with unknown software capability %#"
1594			    INT64_T_FORMAT "x",
1595			    CAST(unsigned long long, cap_sf1)) == -1)
1596				return -1;
1597	}
1598	return 0;
1599}
1600
1601/*
1602 * Look through the program headers of an executable image, searching
1603 * for a PT_INTERP section; if one is found, it's dynamically linked,
1604 * otherwise it's statically linked.
1605 */
1606private int
1607dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
1608    int num, size_t size, off_t fsize, int sh_num, int *flags,
1609    uint16_t *notecount)
1610{
1611	Elf32_Phdr ph32;
1612	Elf64_Phdr ph64;
1613	const char *linking_style = "statically";
1614	unsigned char nbuf[BUFSIZ];
1615	char ibuf[BUFSIZ];
1616	char interp[BUFSIZ];
1617	ssize_t bufsize;
1618	size_t offset, align, len;
1619
1620	if (num == 0) {
1621		if (file_printf(ms, ", no program header") == -1)
1622			return -1;
1623		return 0;
1624	}
1625	if (size != xph_sizeof) {
1626		if (file_printf(ms, ", corrupted program header size") == -1)
1627			return -1;
1628		return 0;
1629	}
1630
1631	interp[0] = '\0';
1632  	for ( ; num; num--) {
1633		int doread;
1634		if (pread(fd, xph_addr, xph_sizeof, off) <
1635		    CAST(ssize_t, xph_sizeof)) {
1636			file_badread(ms);
1637			return -1;
1638		}
1639
1640		off += size;
1641		bufsize = 0;
1642		align = 4;
1643
1644		/* Things we can determine before we seek */
1645		switch (xph_type) {
1646		case PT_DYNAMIC:
1647			doread = 1;
1648			break;
1649		case PT_NOTE:
1650			if (sh_num)	/* Did this through section headers */
1651				continue;
1652			if (((align = xph_align) & 0x80000000UL) != 0 ||
1653			    align < 4) {
1654				if (file_printf(ms,
1655				    ", invalid note alignment %#lx",
1656				    CAST(unsigned long, align)) == -1)
1657					return -1;
1658				align = 4;
1659			}
1660			/*FALLTHROUGH*/
1661		case PT_INTERP:
1662			linking_style = "dynamically";
1663			doread = 1;
1664			break;
1665		default:
1666			doread = 0;
1667			if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
1668				/* Maybe warn here? */
1669				continue;
1670			}
1671			break;
1672		}
1673
1674		if (doread) {
1675			len = xph_filesz < sizeof(nbuf) ? xph_filesz
1676			    : sizeof(nbuf);
1677			bufsize = pread(fd, nbuf, len, xph_offset);
1678			if (bufsize == -1) {
1679				file_badread(ms);
1680				return -1;
1681			}
1682		} else
1683			len = 0;
1684
1685		/* Things we can determine when we seek */
1686		switch (xph_type) {
1687		case PT_DYNAMIC:
1688			offset = 0;
1689			// Let DF_1 determine if we are PIE or not.
1690			ms->mode &= ~0111;
1691			for (;;) {
1692				if (offset >= CAST(size_t, bufsize))
1693					break;
1694				offset = dodynamic(ms, nbuf, offset,
1695				    CAST(size_t, bufsize), clazz, swap);
1696				if (offset == 0)
1697					break;
1698			}
1699			break;
1700
1701		case PT_INTERP:
1702			if (bufsize && nbuf[0]) {
1703				nbuf[bufsize - 1] = '\0';
1704				memcpy(interp, nbuf, CAST(size_t, bufsize));
1705			} else
1706				strlcpy(interp, "*empty*", sizeof(interp));
1707			break;
1708		case PT_NOTE:
1709			/*
1710			 * This is a PT_NOTE section; loop through all the notes
1711			 * in the section.
1712			 */
1713			offset = 0;
1714			for (;;) {
1715				if (offset >= CAST(size_t, bufsize))
1716					break;
1717				offset = donote(ms, nbuf, offset,
1718				    CAST(size_t, bufsize), clazz, swap, align,
1719				    flags, notecount, fd, 0, 0, 0);
1720				if (offset == 0)
1721					break;
1722			}
1723			break;
1724		default:
1725			break;
1726		}
1727	}
1728	if (file_printf(ms, ", %s linked", linking_style)
1729	    == -1)
1730		return -1;
1731	if (interp[0])
1732		if (file_printf(ms, ", interpreter %s",
1733		    file_printable(ibuf, sizeof(ibuf), interp, sizeof(interp)))
1734			== -1)
1735			return -1;
1736	return 0;
1737}
1738
1739
1740protected int
1741file_tryelf(struct magic_set *ms, const struct buffer *b)
1742{
1743	int fd = b->fd;
1744	const unsigned char *buf = CAST(const unsigned char *, b->fbuf);
1745	size_t nbytes = b->flen;
1746	union {
1747		int32_t l;
1748		char c[sizeof(int32_t)];
1749	} u;
1750	int clazz;
1751	int swap;
1752	struct stat st;
1753	const struct stat *stp;
1754	off_t fsize;
1755	int flags = 0;
1756	Elf32_Ehdr elf32hdr;
1757	Elf64_Ehdr elf64hdr;
1758	uint16_t type, phnum, shnum, notecount;
1759
1760	if (ms->flags & (MAGIC_MIME|MAGIC_APPLE|MAGIC_EXTENSION))
1761		return 0;
1762	/*
1763	 * ELF executables have multiple section headers in arbitrary
1764	 * file locations and thus file(1) cannot determine it from easily.
1765	 * Instead we traverse thru all section headers until a symbol table
1766	 * one is found or else the binary is stripped.
1767	 * Return immediately if it's not ELF (so we avoid pipe2file unless
1768	 * needed).
1769	 */
1770	if (buf[EI_MAG0] != ELFMAG0
1771	    || (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1)
1772	    || buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3)
1773		return 0;
1774
1775	/*
1776	 * If we cannot seek, it must be a pipe, socket or fifo.
1777	 */
1778	if((lseek(fd, CAST(off_t, 0), SEEK_SET) == CAST(off_t, -1))
1779	    && (errno == ESPIPE))
1780		fd = file_pipe2file(ms, fd, buf, nbytes);
1781
1782	if (fd == -1) {
1783		file_badread(ms);
1784		return -1;
1785	}
1786
1787	stp = &b->st;
1788	/*
1789	 * b->st.st_size != 0 if previous fstat() succeeded,
1790	 * which is likely, we can avoid extra stat() call.
1791	 */
1792	if (b->st.st_size == 0) {
1793		stp = &st;
1794		if (fstat(fd, &st) == -1) {
1795			file_badread(ms);
1796			return -1;
1797		}
1798	}
1799	if (S_ISREG(stp->st_mode) || stp->st_size != 0)
1800		fsize = stp->st_size;
1801	else
1802		fsize = SIZE_UNKNOWN;
1803
1804	clazz = buf[EI_CLASS];
1805
1806	switch (clazz) {
1807	case ELFCLASS32:
1808#undef elf_getu
1809#define elf_getu(a, b)	elf_getu32(a, b)
1810#undef elfhdr
1811#define elfhdr elf32hdr
1812#include "elfclass.h"
1813	case ELFCLASS64:
1814#undef elf_getu
1815#define elf_getu(a, b)	elf_getu64(a, b)
1816#undef elfhdr
1817#define elfhdr elf64hdr
1818#include "elfclass.h"
1819	default:
1820	    if (file_printf(ms, ", unknown class %d", clazz) == -1)
1821		    return -1;
1822	    break;
1823	}
1824	return 0;
1825}
1826#endif
1827