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