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