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