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