readelf.c revision 268515
1/*
2 * Copyright (c) Christos Zoulas 2003.
3 * All Rights Reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice immediately at the beginning of the file, without modification,
10 *    this list of conditions, and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
19 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 */
27#include "file.h"
28
29#ifndef lint
30FILE_RCSID("@(#)$File: readelf.c,v 1.103 2014/05/02 02:25:10 christos Exp $")
31#endif
32
33#ifdef BUILTIN_ELF
34#include <string.h>
35#include <ctype.h>
36#include <stdlib.h>
37#ifdef HAVE_UNISTD_H
38#include <unistd.h>
39#endif
40
41#include "readelf.h"
42#include "magic.h"
43
44#ifdef	ELFCORE
45private int dophn_core(struct magic_set *, int, int, int, off_t, int, size_t,
46    off_t, int *);
47#endif
48private int dophn_exec(struct magic_set *, int, int, int, off_t, int, size_t,
49    off_t, int *, int);
50private int doshn(struct magic_set *, int, int, int, off_t, int, size_t,
51    off_t, int *, int, int);
52private size_t donote(struct magic_set *, void *, size_t, size_t, int,
53    int, size_t, int *);
54
55#define	ELF_ALIGN(a)	((((a) + align - 1) / align) * align)
56
57#define isquote(c) (strchr("'\"`", (c)) != NULL)
58
59private uint16_t getu16(int, uint16_t);
60private uint32_t getu32(int, uint32_t);
61private uint64_t getu64(int, uint64_t);
62
63private uint16_t
64getu16(int swap, uint16_t value)
65{
66	union {
67		uint16_t ui;
68		char c[2];
69	} retval, tmpval;
70
71	if (swap) {
72		tmpval.ui = value;
73
74		retval.c[0] = tmpval.c[1];
75		retval.c[1] = tmpval.c[0];
76
77		return retval.ui;
78	} else
79		return value;
80}
81
82private uint32_t
83getu32(int swap, uint32_t value)
84{
85	union {
86		uint32_t ui;
87		char c[4];
88	} retval, tmpval;
89
90	if (swap) {
91		tmpval.ui = value;
92
93		retval.c[0] = tmpval.c[3];
94		retval.c[1] = tmpval.c[2];
95		retval.c[2] = tmpval.c[1];
96		retval.c[3] = tmpval.c[0];
97
98		return retval.ui;
99	} else
100		return value;
101}
102
103private uint64_t
104getu64(int swap, uint64_t value)
105{
106	union {
107		uint64_t ui;
108		char c[8];
109	} retval, tmpval;
110
111	if (swap) {
112		tmpval.ui = value;
113
114		retval.c[0] = tmpval.c[7];
115		retval.c[1] = tmpval.c[6];
116		retval.c[2] = tmpval.c[5];
117		retval.c[3] = tmpval.c[4];
118		retval.c[4] = tmpval.c[3];
119		retval.c[5] = tmpval.c[2];
120		retval.c[6] = tmpval.c[1];
121		retval.c[7] = tmpval.c[0];
122
123		return retval.ui;
124	} else
125		return value;
126}
127
128#define elf_getu16(swap, value) getu16(swap, value)
129#define elf_getu32(swap, value) getu32(swap, value)
130#define elf_getu64(swap, value) getu64(swap, value)
131
132#define xsh_addr	(clazz == ELFCLASS32			\
133			 ? (void *)&sh32			\
134			 : (void *)&sh64)
135#define xsh_sizeof	(clazz == ELFCLASS32			\
136			 ? sizeof(sh32)				\
137			 : sizeof(sh64))
138#define xsh_size	(size_t)(clazz == ELFCLASS32		\
139			 ? elf_getu32(swap, sh32.sh_size)	\
140			 : elf_getu64(swap, sh64.sh_size))
141#define xsh_offset	(off_t)(clazz == ELFCLASS32		\
142			 ? elf_getu32(swap, sh32.sh_offset)	\
143			 : elf_getu64(swap, sh64.sh_offset))
144#define xsh_type	(clazz == ELFCLASS32			\
145			 ? elf_getu32(swap, sh32.sh_type)	\
146			 : elf_getu32(swap, sh64.sh_type))
147#define xsh_name    	(clazz == ELFCLASS32			\
148			 ? elf_getu32(swap, sh32.sh_name)	\
149			 : elf_getu32(swap, sh64.sh_name))
150#define xph_addr	(clazz == ELFCLASS32			\
151			 ? (void *) &ph32			\
152			 : (void *) &ph64)
153#define xph_sizeof	(clazz == ELFCLASS32			\
154			 ? sizeof(ph32)				\
155			 : sizeof(ph64))
156#define xph_type	(clazz == ELFCLASS32			\
157			 ? elf_getu32(swap, ph32.p_type)	\
158			 : elf_getu32(swap, ph64.p_type))
159#define xph_offset	(off_t)(clazz == ELFCLASS32		\
160			 ? elf_getu32(swap, ph32.p_offset)	\
161			 : elf_getu64(swap, ph64.p_offset))
162#define xph_align	(size_t)((clazz == ELFCLASS32		\
163			 ? (off_t) (ph32.p_align ? 		\
164			    elf_getu32(swap, ph32.p_align) : 4) \
165			 : (off_t) (ph64.p_align ?		\
166			    elf_getu64(swap, ph64.p_align) : 4)))
167#define xph_filesz	(size_t)((clazz == ELFCLASS32		\
168			 ? elf_getu32(swap, ph32.p_filesz)	\
169			 : elf_getu64(swap, ph64.p_filesz)))
170#define xnh_addr	(clazz == ELFCLASS32			\
171			 ? (void *)&nh32			\
172			 : (void *)&nh64)
173#define xph_memsz	(size_t)((clazz == ELFCLASS32		\
174			 ? elf_getu32(swap, ph32.p_memsz)	\
175			 : elf_getu64(swap, ph64.p_memsz)))
176#define xnh_sizeof	(clazz == ELFCLASS32			\
177			 ? sizeof nh32				\
178			 : sizeof nh64)
179#define xnh_type	(clazz == ELFCLASS32			\
180			 ? elf_getu32(swap, nh32.n_type)	\
181			 : elf_getu32(swap, nh64.n_type))
182#define xnh_namesz	(clazz == ELFCLASS32			\
183			 ? elf_getu32(swap, nh32.n_namesz)	\
184			 : elf_getu32(swap, nh64.n_namesz))
185#define xnh_descsz	(clazz == ELFCLASS32			\
186			 ? elf_getu32(swap, nh32.n_descsz)	\
187			 : elf_getu32(swap, nh64.n_descsz))
188#define prpsoffsets(i)	(clazz == ELFCLASS32			\
189			 ? prpsoffsets32[i]			\
190			 : prpsoffsets64[i])
191#define xcap_addr	(clazz == ELFCLASS32			\
192			 ? (void *)&cap32			\
193			 : (void *)&cap64)
194#define xcap_sizeof	(clazz == ELFCLASS32			\
195			 ? sizeof cap32				\
196			 : sizeof cap64)
197#define xcap_tag	(clazz == ELFCLASS32			\
198			 ? elf_getu32(swap, cap32.c_tag)	\
199			 : elf_getu64(swap, cap64.c_tag))
200#define xcap_val	(clazz == ELFCLASS32			\
201			 ? elf_getu32(swap, cap32.c_un.c_val)	\
202			 : elf_getu64(swap, cap64.c_un.c_val))
203
204#ifdef ELFCORE
205/*
206 * Try larger offsets first to avoid false matches
207 * from earlier data that happen to look like strings.
208 */
209static const size_t	prpsoffsets32[] = {
210#ifdef USE_NT_PSINFO
211	104,		/* SunOS 5.x (command line) */
212	88,		/* SunOS 5.x (short name) */
213#endif /* USE_NT_PSINFO */
214
215	100,		/* SunOS 5.x (command line) */
216	84,		/* SunOS 5.x (short name) */
217
218	44,		/* Linux (command line) */
219	28,		/* Linux 2.0.36 (short name) */
220
221	8,		/* FreeBSD */
222};
223
224static const size_t	prpsoffsets64[] = {
225#ifdef USE_NT_PSINFO
226	152,		/* SunOS 5.x (command line) */
227	136,		/* SunOS 5.x (short name) */
228#endif /* USE_NT_PSINFO */
229
230	136,		/* SunOS 5.x, 64-bit (command line) */
231	120,		/* SunOS 5.x, 64-bit (short name) */
232
233	56,		/* Linux (command line) */
234	40,             /* Linux (tested on core from 2.4.x, short name) */
235
236	16,		/* FreeBSD, 64-bit */
237};
238
239#define	NOFFSETS32	(sizeof prpsoffsets32 / sizeof prpsoffsets32[0])
240#define NOFFSETS64	(sizeof prpsoffsets64 / sizeof prpsoffsets64[0])
241
242#define NOFFSETS	(clazz == ELFCLASS32 ? NOFFSETS32 : NOFFSETS64)
243
244/*
245 * Look through the program headers of an executable image, searching
246 * for a PT_NOTE section of type NT_PRPSINFO, with a name "CORE" or
247 * "FreeBSD"; if one is found, try looking in various places in its
248 * contents for a 16-character string containing only printable
249 * characters - if found, that string should be the name of the program
250 * that dropped core.  Note: right after that 16-character string is,
251 * at least in SunOS 5.x (and possibly other SVR4-flavored systems) and
252 * Linux, a longer string (80 characters, in 5.x, probably other
253 * SVR4-flavored systems, and Linux) containing the start of the
254 * command line for that program.
255 *
256 * SunOS 5.x core files contain two PT_NOTE sections, with the types
257 * NT_PRPSINFO (old) and NT_PSINFO (new).  These structs contain the
258 * same info about the command name and command line, so it probably
259 * isn't worthwhile to look for NT_PSINFO, but the offsets are provided
260 * above (see USE_NT_PSINFO), in case we ever decide to do so.  The
261 * NT_PRPSINFO and NT_PSINFO sections are always in order and adjacent;
262 * the SunOS 5.x file command relies on this (and prefers the latter).
263 *
264 * The signal number probably appears in a section of type NT_PRSTATUS,
265 * but that's also rather OS-dependent, in ways that are harder to
266 * dissect with heuristics, so I'm not bothering with the signal number.
267 * (I suppose the signal number could be of interest in situations where
268 * you don't have the binary of the program that dropped core; if you
269 * *do* have that binary, the debugger will probably tell you what
270 * signal it was.)
271 */
272
273#define	OS_STYLE_SVR4		0
274#define	OS_STYLE_FREEBSD	1
275#define	OS_STYLE_NETBSD		2
276
277private const char os_style_names[][8] = {
278	"SVR4",
279	"FreeBSD",
280	"NetBSD",
281};
282
283#define FLAGS_DID_CORE		0x01
284#define FLAGS_DID_NOTE		0x02
285#define FLAGS_DID_BUILD_ID	0x04
286#define FLAGS_DID_CORE_STYLE	0x08
287#define FLAGS_IS_CORE		0x10
288
289private int
290dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
291    int num, size_t size, off_t fsize, int *flags)
292{
293	Elf32_Phdr ph32;
294	Elf64_Phdr ph64;
295	size_t offset, len;
296	unsigned char nbuf[BUFSIZ];
297	ssize_t bufsize;
298
299	if (size != xph_sizeof) {
300		if (file_printf(ms, ", corrupted program header size") == -1)
301			return -1;
302		return 0;
303	}
304
305	/*
306	 * Loop through all the program headers.
307	 */
308	for ( ; num; num--) {
309		if (pread(fd, xph_addr, xph_sizeof, off) == -1) {
310			file_badread(ms);
311			return -1;
312		}
313		off += size;
314
315		if (xph_offset > fsize) {
316			/* Perhaps warn here */
317			continue;
318		}
319
320		if (xph_type != PT_NOTE)
321			continue;
322
323		/*
324		 * This is a PT_NOTE section; loop through all the notes
325		 * in the section.
326		 */
327		len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf);
328		if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) {
329			file_badread(ms);
330			return -1;
331		}
332		offset = 0;
333		for (;;) {
334			if (offset >= (size_t)bufsize)
335				break;
336			offset = donote(ms, nbuf, offset, (size_t)bufsize,
337			    clazz, swap, 4, flags);
338			if (offset == 0)
339				break;
340
341		}
342	}
343	return 0;
344}
345#endif
346
347static void
348do_note_netbsd_version(struct magic_set *ms, int swap, void *v)
349{
350	uint32_t desc;
351	(void)memcpy(&desc, v, sizeof(desc));
352	desc = elf_getu32(swap, desc);
353
354	if (file_printf(ms, ", for NetBSD") == -1)
355		return;
356	/*
357	 * The version number used to be stuck as 199905, and was thus
358	 * basically content-free.  Newer versions of NetBSD have fixed
359	 * this and now use the encoding of __NetBSD_Version__:
360	 *
361	 *	MMmmrrpp00
362	 *
363	 * M = major version
364	 * m = minor version
365	 * r = release ["",A-Z,Z[A-Z] but numeric]
366	 * p = patchlevel
367	 */
368	if (desc > 100000000U) {
369		uint32_t ver_patch = (desc / 100) % 100;
370		uint32_t ver_rel = (desc / 10000) % 100;
371		uint32_t ver_min = (desc / 1000000) % 100;
372		uint32_t ver_maj = desc / 100000000;
373
374		if (file_printf(ms, " %u.%u", ver_maj, ver_min) == -1)
375			return;
376		if (ver_rel == 0 && ver_patch != 0) {
377			if (file_printf(ms, ".%u", ver_patch) == -1)
378				return;
379		} else if (ver_rel != 0) {
380			while (ver_rel > 26) {
381				if (file_printf(ms, "Z") == -1)
382					return;
383				ver_rel -= 26;
384			}
385			if (file_printf(ms, "%c", 'A' + ver_rel - 1)
386			    == -1)
387				return;
388		}
389	}
390}
391
392static void
393do_note_freebsd_version(struct magic_set *ms, int swap, void *v)
394{
395	uint32_t desc;
396
397	(void)memcpy(&desc, v, sizeof(desc));
398	desc = elf_getu32(swap, desc);
399	if (file_printf(ms, ", for FreeBSD") == -1)
400		return;
401
402	/*
403	 * Contents is __FreeBSD_version, whose relation to OS
404	 * versions is defined by a huge table in the Porter's
405	 * Handbook.  This is the general scheme:
406	 *
407	 * Releases:
408	 * 	Mmp000 (before 4.10)
409	 * 	Mmi0p0 (before 5.0)
410	 * 	Mmm0p0
411	 *
412	 * Development branches:
413	 * 	Mmpxxx (before 4.6)
414	 * 	Mmp1xx (before 4.10)
415	 * 	Mmi1xx (before 5.0)
416	 * 	M000xx (pre-M.0)
417	 * 	Mmm1xx
418	 *
419	 * M = major version
420	 * m = minor version
421	 * i = minor version increment (491000 -> 4.10)
422	 * p = patchlevel
423	 * x = revision
424	 *
425	 * The first release of FreeBSD to use ELF by default
426	 * was version 3.0.
427	 */
428	if (desc == 460002) {
429		if (file_printf(ms, " 4.6.2") == -1)
430			return;
431	} else if (desc < 460100) {
432		if (file_printf(ms, " %d.%d", desc / 100000,
433		    desc / 10000 % 10) == -1)
434			return;
435		if (desc / 1000 % 10 > 0)
436			if (file_printf(ms, ".%d", desc / 1000 % 10) == -1)
437				return;
438		if ((desc % 1000 > 0) || (desc % 100000 == 0))
439			if (file_printf(ms, " (%d)", desc) == -1)
440				return;
441	} else if (desc < 500000) {
442		if (file_printf(ms, " %d.%d", desc / 100000,
443		    desc / 10000 % 10 + desc / 1000 % 10) == -1)
444			return;
445		if (desc / 100 % 10 > 0) {
446			if (file_printf(ms, " (%d)", desc) == -1)
447				return;
448		} else if (desc / 10 % 10 > 0) {
449			if (file_printf(ms, ".%d", desc / 10 % 10) == -1)
450				return;
451		}
452	} else {
453		if (file_printf(ms, " %d.%d", desc / 100000,
454		    desc / 1000 % 100) == -1)
455			return;
456		if ((desc / 100 % 10 > 0) ||
457		    (desc % 100000 / 100 == 0)) {
458			if (file_printf(ms, " (%d)", desc) == -1)
459				return;
460		} else if (desc / 10 % 10 > 0) {
461			if (file_printf(ms, ".%d", desc / 10 % 10) == -1)
462				return;
463		}
464	}
465}
466
467private size_t
468donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
469    int clazz, int swap, size_t align, int *flags)
470{
471	Elf32_Nhdr nh32;
472	Elf64_Nhdr nh64;
473	size_t noff, doff;
474#ifdef ELFCORE
475	int os_style = -1;
476#endif
477	uint32_t namesz, descsz;
478	unsigned char *nbuf = CAST(unsigned char *, vbuf);
479
480	(void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);
481	offset += xnh_sizeof;
482
483	namesz = xnh_namesz;
484	descsz = xnh_descsz;
485	if ((namesz == 0) && (descsz == 0)) {
486		/*
487		 * We're out of note headers.
488		 */
489		return (offset >= size) ? offset : size;
490	}
491
492	if (namesz & 0x80000000) {
493	    (void)file_printf(ms, ", bad note name size 0x%lx",
494		(unsigned long)namesz);
495	    return offset;
496	}
497
498	if (descsz & 0x80000000) {
499	    (void)file_printf(ms, ", bad note description size 0x%lx",
500		(unsigned long)descsz);
501	    return offset;
502	}
503
504
505	noff = offset;
506	doff = ELF_ALIGN(offset + namesz);
507
508	if (offset + namesz > size) {
509		/*
510		 * We're past the end of the buffer.
511		 */
512		return doff;
513	}
514
515	offset = ELF_ALIGN(doff + descsz);
516	if (doff + descsz > size) {
517		/*
518		 * We're past the end of the buffer.
519		 */
520		return (offset >= size) ? offset : size;
521	}
522
523	if ((*flags & (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) ==
524	    (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID))
525		goto core;
526
527	if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 &&
528	    xnh_type == NT_GNU_VERSION && descsz == 2) {
529	    file_printf(ms, ", for SuSE %d.%d", nbuf[doff], nbuf[doff + 1]);
530	}
531	if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
532	    xnh_type == NT_GNU_VERSION && descsz == 16) {
533		uint32_t desc[4];
534		(void)memcpy(desc, &nbuf[doff], sizeof(desc));
535
536		if (file_printf(ms, ", for GNU/") == -1)
537			return size;
538		switch (elf_getu32(swap, desc[0])) {
539		case GNU_OS_LINUX:
540			if (file_printf(ms, "Linux") == -1)
541				return size;
542			break;
543		case GNU_OS_HURD:
544			if (file_printf(ms, "Hurd") == -1)
545				return size;
546			break;
547		case GNU_OS_SOLARIS:
548			if (file_printf(ms, "Solaris") == -1)
549				return size;
550			break;
551		case GNU_OS_KFREEBSD:
552			if (file_printf(ms, "kFreeBSD") == -1)
553				return size;
554			break;
555		case GNU_OS_KNETBSD:
556			if (file_printf(ms, "kNetBSD") == -1)
557				return size;
558			break;
559		default:
560			if (file_printf(ms, "<unknown>") == -1)
561				return size;
562		}
563		if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]),
564		    elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1)
565			return size;
566		*flags |= FLAGS_DID_NOTE;
567		return size;
568	}
569
570	if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
571	    xnh_type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) {
572	    uint8_t desc[20];
573	    uint32_t i;
574	    if (file_printf(ms, ", BuildID[%s]=", descsz == 16 ? "md5/uuid" :
575		"sha1") == -1)
576		    return size;
577	    (void)memcpy(desc, &nbuf[doff], descsz);
578	    for (i = 0; i < descsz; i++)
579		if (file_printf(ms, "%02x", desc[i]) == -1)
580		    return size;
581	    *flags |= FLAGS_DID_BUILD_ID;
582	}
583
584	if (namesz == 4 && strcmp((char *)&nbuf[noff], "PaX") == 0 &&
585	    xnh_type == NT_NETBSD_PAX && descsz == 4) {
586		static const char *pax[] = {
587		    "+mprotect",
588		    "-mprotect",
589		    "+segvguard",
590		    "-segvguard",
591		    "+ASLR",
592		    "-ASLR",
593		};
594		uint32_t desc;
595		size_t i;
596		int did = 0;
597
598		(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
599		desc = elf_getu32(swap, desc);
600
601		if (desc && file_printf(ms, ", PaX: ") == -1)
602			return size;
603
604		for (i = 0; i < __arraycount(pax); i++) {
605			if (((1 << i) & desc) == 0)
606				continue;
607			if (file_printf(ms, "%s%s", did++ ? "," : "",
608			    pax[i]) == -1)
609				return size;
610		}
611	}
612
613	if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) {
614		switch (xnh_type) {
615		case NT_NETBSD_VERSION:
616			if (descsz == 4) {
617				do_note_netbsd_version(ms, swap, &nbuf[doff]);
618				*flags |= FLAGS_DID_NOTE;
619				return size;
620			}
621			break;
622		case NT_NETBSD_MARCH:
623			if (file_printf(ms, ", compiled for: %.*s", (int)descsz,
624			    (const char *)&nbuf[doff]) == -1)
625				return size;
626			break;
627		case NT_NETBSD_CMODEL:
628			if (file_printf(ms, ", compiler model: %.*s",
629			    (int)descsz, (const char *)&nbuf[doff]) == -1)
630				return size;
631			break;
632		default:
633			if (file_printf(ms, ", note=%u", xnh_type) == -1)
634				return size;
635			break;
636		}
637		return size;
638	}
639
640	if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) {
641	    	if (xnh_type == NT_FREEBSD_VERSION && descsz == 4) {
642			do_note_freebsd_version(ms, swap, &nbuf[doff]);
643			*flags |= FLAGS_DID_NOTE;
644			return size;
645		}
646	}
647
648	if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 &&
649	    xnh_type == NT_OPENBSD_VERSION && descsz == 4) {
650		if (file_printf(ms, ", for OpenBSD") == -1)
651			return size;
652		/* Content of note is always 0 */
653		*flags |= FLAGS_DID_NOTE;
654		return size;
655	}
656
657	if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 &&
658	    xnh_type == NT_DRAGONFLY_VERSION && descsz == 4) {
659		uint32_t desc;
660		if (file_printf(ms, ", for DragonFly") == -1)
661			return size;
662		(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
663		desc = elf_getu32(swap, desc);
664		if (file_printf(ms, " %d.%d.%d", desc / 100000,
665		    desc / 10000 % 10, desc % 10000) == -1)
666			return size;
667		*flags |= FLAGS_DID_NOTE;
668		return size;
669	}
670
671core:
672	/*
673	 * Sigh.  The 2.0.36 kernel in Debian 2.1, at
674	 * least, doesn't correctly implement name
675	 * sections, in core dumps, as specified by
676	 * the "Program Linking" section of "UNIX(R) System
677	 * V Release 4 Programmer's Guide: ANSI C and
678	 * Programming Support Tools", because my copy
679	 * clearly says "The first 'namesz' bytes in 'name'
680	 * contain a *null-terminated* [emphasis mine]
681	 * character representation of the entry's owner
682	 * or originator", but the 2.0.36 kernel code
683	 * doesn't include the terminating null in the
684	 * name....
685	 */
686	if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
687	    (namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
688		os_style = OS_STYLE_SVR4;
689	}
690
691	if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
692		os_style = OS_STYLE_FREEBSD;
693	}
694
695	if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
696	    == 0)) {
697		os_style = OS_STYLE_NETBSD;
698	}
699
700#ifdef ELFCORE
701	if ((*flags & FLAGS_DID_CORE) != 0)
702		return size;
703
704	if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
705		if (file_printf(ms, ", %s-style", os_style_names[os_style])
706		    == -1)
707			return size;
708		*flags |= FLAGS_DID_CORE_STYLE;
709	}
710
711	switch (os_style) {
712	case OS_STYLE_NETBSD:
713		if (xnh_type == NT_NETBSD_CORE_PROCINFO) {
714			uint32_t signo;
715			/*
716			 * Extract the program name.  It is at
717			 * offset 0x7c, and is up to 32-bytes,
718			 * including the terminating NUL.
719			 */
720			if (file_printf(ms, ", from '%.31s'",
721			    &nbuf[doff + 0x7c]) == -1)
722				return size;
723
724			/*
725			 * Extract the signal number.  It is at
726			 * offset 0x08.
727			 */
728			(void)memcpy(&signo, &nbuf[doff + 0x08],
729			    sizeof(signo));
730			if (file_printf(ms, " (signal %u)",
731			    elf_getu32(swap, signo)) == -1)
732				return size;
733			*flags |= FLAGS_DID_CORE;
734			return size;
735		}
736		break;
737
738	default:
739		if (xnh_type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
740			size_t i, j;
741			unsigned char c;
742			/*
743			 * Extract the program name.  We assume
744			 * it to be 16 characters (that's what it
745			 * is in SunOS 5.x and Linux).
746			 *
747			 * Unfortunately, it's at a different offset
748			 * in various OSes, so try multiple offsets.
749			 * If the characters aren't all printable,
750			 * reject it.
751			 */
752			for (i = 0; i < NOFFSETS; i++) {
753				unsigned char *cname, *cp;
754				size_t reloffset = prpsoffsets(i);
755				size_t noffset = doff + reloffset;
756				size_t k;
757				for (j = 0; j < 16; j++, noffset++,
758				    reloffset++) {
759					/*
760					 * Make sure we're not past
761					 * the end of the buffer; if
762					 * we are, just give up.
763					 */
764					if (noffset >= size)
765						goto tryanother;
766
767					/*
768					 * Make sure we're not past
769					 * the end of the contents;
770					 * if we are, this obviously
771					 * isn't the right offset.
772					 */
773					if (reloffset >= descsz)
774						goto tryanother;
775
776					c = nbuf[noffset];
777					if (c == '\0') {
778						/*
779						 * A '\0' at the
780						 * beginning is
781						 * obviously wrong.
782						 * Any other '\0'
783						 * means we're done.
784						 */
785						if (j == 0)
786							goto tryanother;
787						else
788							break;
789					} else {
790						/*
791						 * A nonprintable
792						 * character is also
793						 * wrong.
794						 */
795						if (!isprint(c) || isquote(c))
796							goto tryanother;
797					}
798				}
799				/*
800				 * Well, that worked.
801				 */
802
803				/*
804				 * Try next offsets, in case this match is
805				 * in the middle of a string.
806				 */
807				for (k = i + 1 ; k < NOFFSETS ; k++) {
808					size_t no;
809					int adjust = 1;
810					if (prpsoffsets(k) >= prpsoffsets(i))
811						continue;
812					for (no = doff + prpsoffsets(k);
813					     no < doff + prpsoffsets(i); no++)
814						adjust = adjust
815						         && isprint(nbuf[no]);
816					if (adjust)
817						i = k;
818				}
819
820				cname = (unsigned char *)
821				    &nbuf[doff + prpsoffsets(i)];
822				for (cp = cname; *cp && isprint(*cp); cp++)
823					continue;
824				/*
825				 * Linux apparently appends a space at the end
826				 * of the command line: remove it.
827				 */
828				while (cp > cname && isspace(cp[-1]))
829					cp--;
830				if (file_printf(ms, ", from '%.*s'",
831				    (int)(cp - cname), cname) == -1)
832					return size;
833				*flags |= FLAGS_DID_CORE;
834				return size;
835
836			tryanother:
837				;
838			}
839		}
840		break;
841	}
842#endif
843	return offset;
844}
845
846/* SunOS 5.x hardware capability descriptions */
847typedef struct cap_desc {
848	uint64_t cd_mask;
849	const char *cd_name;
850} cap_desc_t;
851
852static const cap_desc_t cap_desc_sparc[] = {
853	{ AV_SPARC_MUL32,		"MUL32" },
854	{ AV_SPARC_DIV32,		"DIV32" },
855	{ AV_SPARC_FSMULD,		"FSMULD" },
856	{ AV_SPARC_V8PLUS,		"V8PLUS" },
857	{ AV_SPARC_POPC,		"POPC" },
858	{ AV_SPARC_VIS,			"VIS" },
859	{ AV_SPARC_VIS2,		"VIS2" },
860	{ AV_SPARC_ASI_BLK_INIT,	"ASI_BLK_INIT" },
861	{ AV_SPARC_FMAF,		"FMAF" },
862	{ AV_SPARC_FJFMAU,		"FJFMAU" },
863	{ AV_SPARC_IMA,			"IMA" },
864	{ 0, NULL }
865};
866
867static const cap_desc_t cap_desc_386[] = {
868	{ AV_386_FPU,			"FPU" },
869	{ AV_386_TSC,			"TSC" },
870	{ AV_386_CX8,			"CX8" },
871	{ AV_386_SEP,			"SEP" },
872	{ AV_386_AMD_SYSC,		"AMD_SYSC" },
873	{ AV_386_CMOV,			"CMOV" },
874	{ AV_386_MMX,			"MMX" },
875	{ AV_386_AMD_MMX,		"AMD_MMX" },
876	{ AV_386_AMD_3DNow,		"AMD_3DNow" },
877	{ AV_386_AMD_3DNowx,		"AMD_3DNowx" },
878	{ AV_386_FXSR,			"FXSR" },
879	{ AV_386_SSE,			"SSE" },
880	{ AV_386_SSE2,			"SSE2" },
881	{ AV_386_PAUSE,			"PAUSE" },
882	{ AV_386_SSE3,			"SSE3" },
883	{ AV_386_MON,			"MON" },
884	{ AV_386_CX16,			"CX16" },
885	{ AV_386_AHF,			"AHF" },
886	{ AV_386_TSCP,			"TSCP" },
887	{ AV_386_AMD_SSE4A,		"AMD_SSE4A" },
888	{ AV_386_POPCNT,		"POPCNT" },
889	{ AV_386_AMD_LZCNT,		"AMD_LZCNT" },
890	{ AV_386_SSSE3,			"SSSE3" },
891	{ AV_386_SSE4_1,		"SSE4.1" },
892	{ AV_386_SSE4_2,		"SSE4.2" },
893	{ 0, NULL }
894};
895
896private int
897doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num,
898    size_t size, off_t fsize, int *flags, int mach, int strtab)
899{
900	Elf32_Shdr sh32;
901	Elf64_Shdr sh64;
902	int stripped = 1;
903	void *nbuf;
904	off_t noff, coff, name_off;
905	uint64_t cap_hw1 = 0;	/* SunOS 5.x hardware capabilites */
906	uint64_t cap_sf1 = 0;	/* SunOS 5.x software capabilites */
907	char name[50];
908
909	if (size != xsh_sizeof) {
910		if (file_printf(ms, ", corrupted section header size") == -1)
911			return -1;
912		return 0;
913	}
914
915	/* Read offset of name section to be able to read section names later */
916	if (pread(fd, xsh_addr, xsh_sizeof, off + size * strtab) == -1) {
917		file_badread(ms);
918		return -1;
919	}
920	name_off = xsh_offset;
921
922	for ( ; num; num--) {
923		/* Read the name of this section. */
924		if (pread(fd, name, sizeof(name), name_off + xsh_name) == -1) {
925			file_badread(ms);
926			return -1;
927		}
928		name[sizeof(name) - 1] = '\0';
929		if (strcmp(name, ".debug_info") == 0)
930			stripped = 0;
931
932		if (pread(fd, xsh_addr, xsh_sizeof, off) == -1) {
933			file_badread(ms);
934			return -1;
935		}
936		off += size;
937
938		/* Things we can determine before we seek */
939		switch (xsh_type) {
940		case SHT_SYMTAB:
941#if 0
942		case SHT_DYNSYM:
943#endif
944			stripped = 0;
945			break;
946		default:
947			if (xsh_offset > fsize) {
948				/* Perhaps warn here */
949				continue;
950			}
951			break;
952		}
953
954		/* Things we can determine when we seek */
955		switch (xsh_type) {
956		case SHT_NOTE:
957			if ((nbuf = malloc(xsh_size)) == NULL) {
958				file_error(ms, errno, "Cannot allocate memory"
959				    " for note");
960				return -1;
961			}
962			if (pread(fd, nbuf, xsh_size, xsh_offset) == -1) {
963				file_badread(ms);
964				free(nbuf);
965				return -1;
966			}
967
968			noff = 0;
969			for (;;) {
970				if (noff >= (off_t)xsh_size)
971					break;
972				noff = donote(ms, nbuf, (size_t)noff,
973				    xsh_size, clazz, swap, 4, flags);
974				if (noff == 0)
975					break;
976			}
977			free(nbuf);
978			break;
979		case SHT_SUNW_cap:
980			switch (mach) {
981			case EM_SPARC:
982			case EM_SPARCV9:
983			case EM_IA_64:
984			case EM_386:
985			case EM_AMD64:
986				break;
987			default:
988				goto skip;
989			}
990
991			if (lseek(fd, xsh_offset, SEEK_SET) == (off_t)-1) {
992				file_badseek(ms);
993				return -1;
994			}
995			coff = 0;
996			for (;;) {
997				Elf32_Cap cap32;
998				Elf64_Cap cap64;
999				char cbuf[/*CONSTCOND*/
1000				    MAX(sizeof cap32, sizeof cap64)];
1001				if ((coff += xcap_sizeof) > (off_t)xsh_size)
1002					break;
1003				if (read(fd, cbuf, (size_t)xcap_sizeof) !=
1004				    (ssize_t)xcap_sizeof) {
1005					file_badread(ms);
1006					return -1;
1007				}
1008				if (cbuf[0] == 'A') {
1009#ifdef notyet
1010					char *p = cbuf + 1;
1011					uint32_t len, tag;
1012					memcpy(&len, p, sizeof(len));
1013					p += 4;
1014					len = getu32(swap, len);
1015					if (memcmp("gnu", p, 3) != 0) {
1016					    if (file_printf(ms,
1017						", unknown capability %.3s", p)
1018						== -1)
1019						return -1;
1020					    break;
1021					}
1022					p += strlen(p) + 1;
1023					tag = *p++;
1024					memcpy(&len, p, sizeof(len));
1025					p += 4;
1026					len = getu32(swap, len);
1027					if (tag != 1) {
1028					    if (file_printf(ms, ", unknown gnu"
1029						" capability tag %d", tag)
1030						== -1)
1031						return -1;
1032					    break;
1033					}
1034					// gnu attributes
1035#endif
1036					break;
1037				}
1038				(void)memcpy(xcap_addr, cbuf, xcap_sizeof);
1039				switch (xcap_tag) {
1040				case CA_SUNW_NULL:
1041					break;
1042				case CA_SUNW_HW_1:
1043					cap_hw1 |= xcap_val;
1044					break;
1045				case CA_SUNW_SF_1:
1046					cap_sf1 |= xcap_val;
1047					break;
1048				default:
1049					if (file_printf(ms,
1050					    ", with unknown capability "
1051					    "0x%" INT64_T_FORMAT "x = 0x%"
1052					    INT64_T_FORMAT "x",
1053					    (unsigned long long)xcap_tag,
1054					    (unsigned long long)xcap_val) == -1)
1055						return -1;
1056					break;
1057				}
1058			}
1059			/*FALLTHROUGH*/
1060		skip:
1061		default:
1062			break;
1063		}
1064	}
1065
1066	if (file_printf(ms, ", %sstripped", stripped ? "" : "not ") == -1)
1067		return -1;
1068	if (cap_hw1) {
1069		const cap_desc_t *cdp;
1070		switch (mach) {
1071		case EM_SPARC:
1072		case EM_SPARC32PLUS:
1073		case EM_SPARCV9:
1074			cdp = cap_desc_sparc;
1075			break;
1076		case EM_386:
1077		case EM_IA_64:
1078		case EM_AMD64:
1079			cdp = cap_desc_386;
1080			break;
1081		default:
1082			cdp = NULL;
1083			break;
1084		}
1085		if (file_printf(ms, ", uses") == -1)
1086			return -1;
1087		if (cdp) {
1088			while (cdp->cd_name) {
1089				if (cap_hw1 & cdp->cd_mask) {
1090					if (file_printf(ms,
1091					    " %s", cdp->cd_name) == -1)
1092						return -1;
1093					cap_hw1 &= ~cdp->cd_mask;
1094				}
1095				++cdp;
1096			}
1097			if (cap_hw1)
1098				if (file_printf(ms,
1099				    " unknown hardware capability 0x%"
1100				    INT64_T_FORMAT "x",
1101				    (unsigned long long)cap_hw1) == -1)
1102					return -1;
1103		} else {
1104			if (file_printf(ms,
1105			    " hardware capability 0x%" INT64_T_FORMAT "x",
1106			    (unsigned long long)cap_hw1) == -1)
1107				return -1;
1108		}
1109	}
1110	if (cap_sf1) {
1111		if (cap_sf1 & SF1_SUNW_FPUSED) {
1112			if (file_printf(ms,
1113			    (cap_sf1 & SF1_SUNW_FPKNWN)
1114			    ? ", uses frame pointer"
1115			    : ", not known to use frame pointer") == -1)
1116				return -1;
1117		}
1118		cap_sf1 &= ~SF1_SUNW_MASK;
1119		if (cap_sf1)
1120			if (file_printf(ms,
1121			    ", with unknown software capability 0x%"
1122			    INT64_T_FORMAT "x",
1123			    (unsigned long long)cap_sf1) == -1)
1124				return -1;
1125	}
1126	return 0;
1127}
1128
1129/*
1130 * Look through the program headers of an executable image, searching
1131 * for a PT_INTERP section; if one is found, it's dynamically linked,
1132 * otherwise it's statically linked.
1133 */
1134private int
1135dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
1136    int num, size_t size, off_t fsize, int *flags, int sh_num)
1137{
1138	Elf32_Phdr ph32;
1139	Elf64_Phdr ph64;
1140	const char *linking_style = "statically";
1141	const char *shared_libraries = "";
1142	unsigned char nbuf[BUFSIZ];
1143	ssize_t bufsize;
1144	size_t offset, align, len;
1145
1146	if (size != xph_sizeof) {
1147		if (file_printf(ms, ", corrupted program header size") == -1)
1148			return -1;
1149		return 0;
1150	}
1151
1152  	for ( ; num; num--) {
1153		if (pread(fd, xph_addr, xph_sizeof, off) == -1) {
1154			file_badread(ms);
1155			return -1;
1156		}
1157
1158		off += size;
1159
1160		/* Things we can determine before we seek */
1161		switch (xph_type) {
1162		case PT_DYNAMIC:
1163			linking_style = "dynamically";
1164			break;
1165		case PT_INTERP:
1166			shared_libraries = " (uses shared libs)";
1167			break;
1168		default:
1169			if (xph_offset > fsize) {
1170				/* Maybe warn here? */
1171				continue;
1172			}
1173			break;
1174		}
1175
1176		/* Things we can determine when we seek */
1177		switch (xph_type) {
1178		case PT_NOTE:
1179			if ((align = xph_align) & 0x80000000UL) {
1180				if (file_printf(ms,
1181				    ", invalid note alignment 0x%lx",
1182				    (unsigned long)align) == -1)
1183					return -1;
1184				align = 4;
1185			}
1186			if (sh_num)
1187				break;
1188			/*
1189			 * This is a PT_NOTE section; loop through all the notes
1190			 * in the section.
1191			 */
1192			len = xph_filesz < sizeof(nbuf) ? xph_filesz
1193			    : sizeof(nbuf);
1194			bufsize = pread(fd, nbuf, len, xph_offset);
1195			if (bufsize == -1) {
1196				file_badread(ms);
1197				return -1;
1198			}
1199			offset = 0;
1200			for (;;) {
1201				if (offset >= (size_t)bufsize)
1202					break;
1203				offset = donote(ms, nbuf, offset,
1204				    (size_t)bufsize, clazz, swap, align,
1205				    flags);
1206				if (offset == 0)
1207					break;
1208			}
1209			break;
1210		default:
1211			break;
1212		}
1213	}
1214	if (file_printf(ms, ", %s linked%s", linking_style, shared_libraries)
1215	    == -1)
1216	    return -1;
1217	return 0;
1218}
1219
1220
1221protected int
1222file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf,
1223    size_t nbytes)
1224{
1225	union {
1226		int32_t l;
1227		char c[sizeof (int32_t)];
1228	} u;
1229	int clazz;
1230	int swap;
1231	struct stat st;
1232	off_t fsize;
1233	int flags = 0;
1234	Elf32_Ehdr elf32hdr;
1235	Elf64_Ehdr elf64hdr;
1236	uint16_t type;
1237
1238	if (ms->flags & (MAGIC_MIME|MAGIC_APPLE))
1239		return 0;
1240	/*
1241	 * ELF executables have multiple section headers in arbitrary
1242	 * file locations and thus file(1) cannot determine it from easily.
1243	 * Instead we traverse thru all section headers until a symbol table
1244	 * one is found or else the binary is stripped.
1245	 * Return immediately if it's not ELF (so we avoid pipe2file unless needed).
1246	 */
1247	if (buf[EI_MAG0] != ELFMAG0
1248	    || (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1)
1249	    || buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3)
1250		return 0;
1251
1252	/*
1253	 * If we cannot seek, it must be a pipe, socket or fifo.
1254	 */
1255	if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE))
1256		fd = file_pipe2file(ms, fd, buf, nbytes);
1257
1258	if (fstat(fd, &st) == -1) {
1259  		file_badread(ms);
1260		return -1;
1261	}
1262	fsize = st.st_size;
1263
1264	clazz = buf[EI_CLASS];
1265
1266	switch (clazz) {
1267	case ELFCLASS32:
1268#undef elf_getu
1269#define elf_getu(a, b)	elf_getu32(a, b)
1270#undef elfhdr
1271#define elfhdr elf32hdr
1272#include "elfclass.h"
1273	case ELFCLASS64:
1274#undef elf_getu
1275#define elf_getu(a, b)	elf_getu64(a, b)
1276#undef elfhdr
1277#define elfhdr elf64hdr
1278#include "elfclass.h"
1279	default:
1280	    if (file_printf(ms, ", unknown class %d", clazz) == -1)
1281		    return -1;
1282	    break;
1283	}
1284	return 0;
1285}
1286#endif
1287