xref: /third_party/toybox/toys/posix/file.c (revision 0f66f451)
1/* file.c - describe file type
2 *
3 * Copyright 2016 The Android Open Source Project
4 *
5 * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/file.html
6
7USE_FILE(NEWTOY(file, "<1bhLs[!hL]", TOYFLAG_USR|TOYFLAG_BIN))
8
9config FILE
10  bool "file"
11  default y
12  help
13    usage: file [-bhLs] [file...]
14
15    Examine the given files and describe their content types.
16
17    -b	Brief (no filename)
18    -h	Don't follow symlinks (default)
19    -L	Follow symlinks
20    -s	Show block/char device contents
21*/
22
23#define FOR_file
24#include "toys.h"
25
26GLOBALS(
27  int max_name_len;
28
29  off_t len;
30)
31
32// We don't trust elf.h to be there, and two codepaths for 32/64 is awkward
33// anyway, so calculate struct offsets manually. (It's a fixed ABI.)
34static void do_elf_file(int fd)
35{
36  int endian = toybuf[5], bits = toybuf[4], i, j, dynamic = 0, stripped = 1,
37      phentsize, phnum, shsize, shnum;
38  int64_t (*elf_int)(void *ptr, unsigned size);
39  // Values from include/linux/elf-em.h (plus arch/*/include/asm/elf.h)
40  // Names are linux/arch/ directory (sometimes before 32/64 bit merges)
41  struct {int val; char *name;} type[] = {{0x9026, "alpha"}, {93, "arc"},
42    {195, "arcv2"}, {40, "arm"}, {183, "arm64"}, {0x18ad, "avr32"},
43    {247, "bpf"}, {106, "blackfin"}, {140, "c6x"}, {23, "cell"}, {76, "cris"},
44    {252, "csky"}, {0x5441, "frv"}, {46, "h8300"}, {164, "hexagon"},
45    {50, "ia64"}, {88, "m32r"}, {0x9041, "m32r"}, {4, "m68k"}, {174, "metag"},
46    {189, "microblaze"}, {0xbaab, "microblaze-old"}, {8, "mips"},
47    {10, "mips-old"}, {89, "mn10300"}, {0xbeef, "mn10300-old"}, {113, "nios2"},
48    {92, "openrisc"}, {0x8472, "openrisc-old"}, {15, "parisc"}, {20, "ppc"},
49    {21, "ppc64"}, {243, "riscv"}, {22, "s390"}, {0xa390, "s390-old"},
50    {135, "score"}, {42, "sh"}, {2, "sparc"}, {18, "sparc8+"}, {43, "sparc9"},
51    {188, "tile"}, {191, "tilegx"}, {3, "386"}, {6, "486"}, {62, "x86-64"},
52    {94, "xtensa"}, {0xabc7, "xtensa-old"}
53  };
54  char *map = 0;
55  off_t phoff, shoff;
56
57  printf("ELF ");
58  elf_int = (endian==2) ? peek_be : peek_le;
59
60  // executable type
61  i = elf_int(toybuf+16, 2);
62  if (i == 1) printf("relocatable");
63  else if (i == 2) printf("executable");
64  else if (i == 3) printf("shared object");
65  else if (i == 4) printf("core dump");
66  else printf("(bad type %d)", i);
67  if (elf_int(toybuf+36+12*(bits==2), 4) & 0x8000) printf(" (fdpic)");
68  printf(", ");
69
70  // "64-bit"
71  if (bits == 1) printf("32-bit ");
72  else if (bits == 2) printf("64-bit ");
73  else {
74    printf("(bad class %d) ", bits);
75    bits = 0;
76  }
77
78  // "LSB"
79  if (endian == 1) printf("LSB ");
80  else if (endian == 2) printf("MSB ");
81  else {
82    printf("(bad endian %d) \n", endian);
83    endian = 0;
84  }
85
86  // e_machine, ala "x86", from big table above
87  j = elf_int(toybuf+18, 2);
88  for (i = 0; i<ARRAY_LEN(type); i++) if (j==type[i].val) break;
89  if (i<ARRAY_LEN(type)) printf("%s", type[i].name);
90  else printf("(unknown arch %d)", j);
91
92  bits--;
93  // If what we've seen so far doesn't seem consistent, bail.
94  if (!((bits&1)==bits && endian)) {
95    printf(", corrupt?\n");
96    return;
97  }
98
99  // Parsing ELF means following tables that may point to data earlier in
100  // the file, so sequential reading involves buffering unknown amounts of
101  // data. Just skip it if we can't mmap.
102  if (MAP_FAILED == (map = mmap(0, TT.len, PROT_READ, MAP_SHARED, fd, 0)))
103    goto bad;
104
105  // Stash what we need from the header; it's okay to reuse toybuf after this.
106  phentsize = elf_int(toybuf+42+12*bits, 2);
107  phnum = elf_int(toybuf+44+12*bits, 2);
108  phoff = elf_int(toybuf+28+4*bits, 4+4*bits);
109  shsize = elf_int(toybuf+46+12*bits, 2);
110  shnum = elf_int(toybuf+48+12*bits, 2);
111  shoff = elf_int(toybuf+32+8*bits, 4+4*bits);
112
113  // With binutils, phentsize seems to only be non-zero if phnum is non-zero.
114  // Such ELF files are rare, but do exist. (Android's crtbegin files, say.)
115  if (phnum && (phentsize != 32+24*bits)) {
116    printf(", corrupt phentsize %d?", phentsize);
117    goto bad;
118  }
119
120  // Parsing ELF means following tables that may point to data earlier in
121  // the file, so sequential reading involves buffering unknown amounts of
122  // data. Just skip it if we can't mmap.
123  if (MAP_FAILED == (map = mmap(0, TT.len, PROT_READ, MAP_SHARED, fd, 0)))
124    goto bad;
125
126  // We need to read the phdrs for dynamic vs static.
127  // (Note: fields got reordered for 64 bit)
128  if (phoff+phnum*phentsize>TT.len) goto bad;
129  for (i = 0; i<phnum; i++) {
130    char *phdr = map+phoff+i*phentsize;
131    int p_type = elf_int(phdr, 4);
132    long long p_offset, p_filesz;
133
134    if (p_type==2 /*PT_DYNAMIC*/) dynamic = 1;
135    if (p_type!=3 /*PT_INTERP*/ && p_type!=4 /*PT_NOTE*/) continue;
136
137    j = bits+1;
138    p_offset = elf_int(phdr+4*j, 4*j);
139    p_filesz = elf_int(phdr+16*j, 4*j);
140
141    if (p_type==3 /*PT_INTERP*/) {
142      if (p_offset+p_filesz>TT.len) goto bad;
143      printf(", dynamic (%.*s)", (int)p_filesz, map+p_offset);
144    }
145  }
146  if (!dynamic) printf(", static");
147
148  // We need to read the shdrs for stripped/unstripped and any notes.
149  // Notes are in program headers *and* section headers, but some files don't
150  // contain program headers, so we prefer to check here.
151  // (Note: fields got reordered for 64 bit)
152  if (shoff+i*shnum>TT.len) goto bad;
153  for (i = 0; i<shnum; i++) {
154    char *shdr = map+shoff+i*shsize;
155    int sh_type = elf_int(shdr+4, 4);
156    long sh_offset = elf_int(shdr+8+8*(bits+1), 4*(bits+1));
157    int sh_size = elf_int(shdr+8+12*(bits+1), 4);
158
159    if (sh_type == 2 /*SHT_SYMTAB*/) {
160      stripped = 0;
161      break;
162    } else if (sh_type == 7 /*SHT_NOTE*/) {
163      char *note = map+sh_offset;
164
165      // An ELF note is a sequence of entries, each consisting of an
166      // ndhr followed by n_namesz+n_descsz bytes of data (each of those
167      // rounded up to the next 4 bytes, without this being reflected in
168      // the header byte counts themselves).
169      while (sh_size >= 3*4) { // Don't try to read a truncated entry.
170        unsigned n_namesz, n_descsz, n_type, notesz;
171
172        if (sh_offset+sh_size>TT.len) goto bad;
173
174        n_namesz = elf_int(note, 4);
175        n_descsz = elf_int(note+4, 4);
176        n_type = elf_int(note+8, 4);
177        notesz = 3*4 + ((n_namesz+3)&~3) + ((n_descsz+3)&~3);
178
179        // Does the claimed size of this note actually fit in the section?
180        if (notesz > sh_size) goto bad;
181
182        if (n_namesz==4 && !memcmp(note+12, "GNU", 4)) {
183          if (n_type==3 /*NT_GNU_BUILD_ID*/) {
184            printf(", BuildID=");
185            for (j = 0; j < n_descsz; ++j) printf("%02x", note[16 + j]);
186          }
187        } else if (n_namesz==8 && !memcmp(note+12, "Android", 8)) {
188          if (n_type==1 /*.android.note.ident*/ && n_descsz >= 4) {
189            printf(", for Android %d", (int)elf_int(note+20, 4));
190            // NDK r14 and later also include NDK version info. OS binaries
191            // and binaries built by older NDKs don't have this.
192            if (n_descsz >= 4+64+64)
193              printf(", built by NDK %.64s (%.64s)", note+24, note+24+64);
194          }
195        }
196
197        note += notesz;
198        sh_size -= notesz;
199      }
200    }
201  }
202  printf(", %sstripped", stripped ? "" : "not ");
203bad:
204  xputc('\n');
205
206  if (map && map != MAP_FAILED) munmap(map, TT.len);
207}
208
209static void do_regular_file(int fd, char *name)
210{
211  char *s;
212  int len, magic;
213
214  // zero through elf shnum, just in case
215  memset(toybuf, 0, 80);
216  if ((len = readall(fd, s = toybuf, sizeof(toybuf)))<0) perror_msg("%s", name);
217
218  if (!len) xputs("empty");
219  // 45 bytes: https://www.muppetlabs.com/~breadbox/software/tiny/teensy.html
220  else if (len>=45 && strstart(&s, "\177ELF")) do_elf_file(fd);
221  else if (len>=8 && strstart(&s, "!<arch>\n")) xputs("ar archive");
222  else if (len>28 && strstart(&s, "\x89PNG\x0d\x0a\x1a\x0a")) {
223    // PNG is big-endian: https://www.w3.org/TR/PNG/#7Integers-and-byte-order
224    int chunk_length = peek_be(s, 4);
225
226    xprintf("PNG image data");
227
228    // The IHDR chunk comes first: https://www.w3.org/TR/PNG/#11IHDR
229    s += 4;
230    if (chunk_length == 13 && strstart(&s, "IHDR")) {
231      // https://www.w3.org/TR/PNG/#6Colour-values
232      char *c = 0, *colors[] = {"grayscale", 0, "color RGB", "indexed color",
233                                "grayscale with alpha", 0, "color RGBA"};
234
235      if (s[9]<ARRAY_LEN(colors)) c = colors[s[9]];
236      if (!c) c = "unknown";
237
238      xprintf(", %d x %d, %d-bit/%s, %sinterlaced", (int)peek_be(s, 4),
239        (int)peek_be(s+4, 4), s[8], c, s[12] ? "" : "non-");
240    }
241
242    xputc('\n');
243
244  // https://www.w3.org/Graphics/GIF/spec-gif89a.txt
245  } else if (len>16 && (strstart(&s, "GIF87a") || strstart(&s, "GIF89a")))
246    xprintf("GIF image data, %d x %d\n",
247      (int)peek_le(s, 2), (int)peek_le(s+8, 2));
248
249  // TODO: parsing JPEG for width/height is harder than GIF or PNG.
250  else if (len>32 && !memcmp(toybuf, "\xff\xd8", 2)) xputs("JPEG image data");
251
252  // https://en.wikipedia.org/wiki/Java_class_file#General_layout
253  else if (len>8 && strstart(&s, "\xca\xfe\xba\xbe"))
254    xprintf("Java class file, version %d.%d (Java 1.%d)\n",
255      (int)peek_be(s+2, 2), (int)peek_be(s, 2), (int)peek_be(s+2, 2)-44);
256
257  // https://source.android.com/devices/tech/dalvik/dex-format#dex-file-magic
258  else if (len>8 && strstart(&s, "dex\n") && s[3] == 0)
259    xprintf("Android dex file, version %s\n", s);
260
261  // https://people.freebsd.org/~kientzle/libarchive/man/cpio.5.txt
262  // the lengths for cpio are size of header + 9 bytes, since any valid
263  // cpio archive ends with a record for "TARGET!!!"
264  else if (len>85 && strstart(&s, "07070")) {
265    char *cpioformat = "unknown type";
266
267    if (toybuf[5] == '7') cpioformat = "pre-SVR4 or odc";
268    else if (toybuf[5] == '1') cpioformat = "SVR4 with no CRC";
269    else if (toybuf[5] == '2') cpioformat = "SVR4 with CRC";
270    xprintf("ASCII cpio archive (%s)\n", cpioformat);
271  } else if (len>33 && (magic=peek(&s,2), magic==0143561 || magic==070707)) {
272    if (magic == 0143561) printf("byte-swapped ");
273    xputs("cpio archive");
274  // tar archive (old, ustar/pax, or gnu)
275  } else if (len>500 && is_tar_header(s))
276    xprintf("%s tar archive%s\n", s[257] ? "POSIX" : "old",
277      strncmp(s+262,"  ",2)?"":" (GNU)");
278  // zip/jar/apk archive, ODF/OOXML document, or such
279  else if (len>5 && strstart(&s, "PK\03\04")) {
280    int ver = toybuf[4];
281
282    xprintf("Zip archive data");
283    if (ver) xprintf(", requires at least v%d.%d to extract", ver/10, ver%10);
284    xputc('\n');
285  } else if (len>4 && strstart(&s, "BZh") && isdigit(*s))
286    xprintf("bzip2 compressed data, block size = %c00k\n", *s);
287  else if (len > 31 && peek_be(s, 7) == 0xfd377a585a0000)
288    xputs("xz compressed data");
289  else if (len>10 && strstart(&s, "\x1f\x8b")) xputs("gzip compressed data");
290  else if (len>32 && !memcmp(s+1, "\xfa\xed\xfe", 3)) {
291    int bit = s[0]=='\xce'?32:64;
292    char *what;
293
294    xprintf("Mach-O %d-bit ", bit);
295
296    if (s[4] == 7) what = (bit==32)?"x86":"x86-";
297    else if (s[4] == 12) what = "arm";
298    else if (s[4] == 18) what = "ppc";
299    else what = NULL;
300    if (what) xprintf("%s%s ", what, (bit==32)?"":"64");
301    else xprintf("(bad arch %d) ", s[4]);
302
303    if (s[12] == 1) what = "object";
304    else if (s[12] == 2) what = "executable";
305    else if (s[12] == 6) what = "shared library";
306    else what = NULL;
307    if (what) xprintf("%s\n", what);
308    else xprintf("(bad type %d)\n", s[9]);
309  } else if (len>36 && !memcmp(s, "OggS\x00\x02", 6)) {
310    xprintf("Ogg data");
311    // https://wiki.xiph.org/MIMETypesCodecs
312    if (!memcmp(s+28, "CELT    ", 8)) xprintf(", celt audio");
313    else if (!memcmp(s+28, "CMML    ", 8)) xprintf(", cmml text");
314    else if (!memcmp(s+28, "BBCD\0", 5)) xprintf(", dirac video");
315    else if (!memcmp(s+28, "\177FLAC", 5)) xprintf(", flac audio");
316    else if (!memcmp(s+28, "\x8bJNG\r\n\x1a\n", 8)) xprintf(", jng video");
317    else if (!memcmp(s+28, "\x80kate\0\0\0", 8)) xprintf(", kate text");
318    else if (!memcmp(s+28, "OggMIDI\0", 8)) xprintf(", midi text");
319    else if (!memcmp(s+28, "\x8aMNG\r\n\x1a\n", 8)) xprintf(", mng video");
320    else if (!memcmp(s+28, "OpusHead", 8)) xprintf(", opus audio");
321    else if (!memcmp(s+28, "PCM     ", 8)) xprintf(", pcm audio");
322    else if (!memcmp(s+28, "\x89PNG\r\n\x1a\n", 8)) xprintf(", png video");
323    else if (!memcmp(s+28, "Speex   ", 8)) xprintf(", speex audio");
324    else if (!memcmp(s+28, "\x80theora", 7)) xprintf(", theora video");
325    else if (!memcmp(s+28, "\x01vorbis", 7)) xprintf(", vorbis audio");
326    else if (!memcmp(s+28, "YUV4MPEG", 8)) xprintf(", yuv4mpeg video");
327    xputc('\n');
328  } else if (len>32 && !memcmp(s, "RIF", 3) && !memcmp(s+8, "WAVEfmt ", 8)) {
329    // https://en.wikipedia.org/wiki/WAV
330    int le = (s[3] == 'F');
331    int format = le ? peek_le(s+20,2) : peek_be(s+20,2);
332    int channels = le ? peek_le(s+22,2) : peek_be(s+22,2);
333    int hz = le ? peek_le(s+24,4) : peek_be(s+24,4);
334    int bits = le ? peek_le(s+34,2) : peek_be(s+34,2);
335
336    xprintf("WAV audio, %s, ", le ? "LE" : "BE");
337    if (bits != 0) xprintf("%d-bit, ", bits);
338    if (channels==1||channels==2) xprintf("%s, ", channels==1?"mono":"stereo");
339    else xprintf("%d-channel, ", channels);
340    xprintf("%d Hz, ", hz);
341    // See https://tools.ietf.org/html/rfc2361, though there appear to be bugs
342    // in the RFC. This assumes wikipedia's example files are more correct.
343    if (format == 0x01) xprintf("PCM");
344    else if (format == 0x03) xprintf("IEEE float");
345    else if (format == 0x06) xprintf("A-law");
346    else if (format == 0x07) xprintf("µ-law");
347    else if (format == 0x11) xprintf("ADPCM");
348    else if (format == 0x22) xprintf("Truespeech");
349    else if (format == 0x31) xprintf("GSM");
350    else if (format == 0x55) xprintf("MP3");
351    else if (format == 0x70) xprintf("CELP");
352    else if (format == 0xfffe) xprintf("extensible");
353    else xprintf("unknown format %d", format);
354    xputc('\n');
355  } else if (len>12 && !memcmp(s, "\x00\x01\x00\x00", 4)) {
356    xputs("TrueType font");
357  } else if (len>12 && !memcmp(s, "ttcf\x00", 5)) {
358    xprintf("TrueType font collection, version %d, %d fonts\n",
359            (int)peek_be(s+4, 2), (int)peek_be(s+8, 4));
360
361  // https://docs.microsoft.com/en-us/typography/opentype/spec/otff
362  } else if (len>12 && !memcmp(s, "OTTO", 4)) {
363    xputs("OpenType font");
364  } else if (len>4 && !memcmp(s, "BC\xc0\xde", 4)) {
365    xputs("LLVM IR bitcode");
366  } else if (strstart(&s, "-----BEGIN CERTIFICATE-----")) {
367    xputs("PEM certificate");
368
369  // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680547(v=vs.85).aspx
370  } else if (len>0x70 && !memcmp(s, "MZ", 2) &&
371      (magic=peek_le(s+0x3c,4))<len-4 && !memcmp(s+magic, "\x50\x45\0\0", 4)) {
372    xprintf("MS PE32%s executable %s", (peek_le(s+magic+24, 2)==0x20b)?"+":"",
373        (peek_le(s+magic+22, 2)&0x2000)?"(DLL) ":"");
374    if (peek_le(s+magic+20, 2)>70) {
375      char *types[] = {0, "native", "GUI", "console", "OS/2", "driver", "CE",
376          "EFI", "EFI boot", "EFI runtime", "EFI ROM", "XBOX", 0, "boot"};
377      int type = peek_le(s+magic+92, 2);
378      char *name = (type>0 && type<ARRAY_LEN(types))?types[type]:0;
379
380      xprintf("(%s) ", name?name:"unknown");
381    }
382    xprintf("%s\n", (peek_le(s+magic+4, 2)==0x14c)?"x86":"x86-64");
383
384    // https://en.wikipedia.org/wiki/BMP_file_format
385  } else if (len > 0x32 && !memcmp(s, "BM", 2) && !memcmp(s+6, "\0\0\0\0", 4)) {
386    int w = peek_le(s+0x12,4), h = peek_le(s+0x16,4), bpp = peek_le(s+0x1c,2);
387
388    xprintf("BMP image, %d x %d, %d bpp\n", w, h, bpp);
389
390    // https://github.com/torvalds/linux/blob/master/tools/perf/Documentation/perf.data-file-format.txt
391  } else if (len>=104 && !memcmp(s, "PERFILE2", 8)) {
392    xputs("Linux perf data");
393
394    // https://android.googlesource.com/platform/system/core/+/master/libsparse/sparse_format.h
395  } else if (len>28 && peek_le(s, 4) == 0xed26ff3a) {
396    xprintf("Android sparse image v%d.%d, %d %d-byte blocks (%d chunks)\n",
397        (int) peek_le(s+4, 2), (int) peek_le(s+6, 2), (int) peek_le(s+16, 4),
398        (int) peek_le(s+12, 4), (int) peek_le(s+20, 4));
399
400    // https://android.googlesource.com/platform/system/tools/mkbootimg/+/refs/heads/master/include/bootimg/bootimg.h
401  } else if (len>1632 && !memcmp(s, "ANDROID!", 8)) {
402    xprintf("Android boot image v%d\n", (int) peek_le(s+40, 4));
403
404    // https://source.android.com/devices/architecture/dto/partitions
405  } else if (len>32 && peek_be(s, 4) == 0xd7b7ab1e) {
406    xprintf("Android DTB/DTBO v%d, %d entries\n", (int) peek_be(s+28, 4),
407        (int) peek_be(s+16, 4));
408
409  } else {
410    char *what = 0;
411    int i, bytes;
412
413    // If shell script, report which interpreter
414    if (len>3 && strstart(&s, "#!")) {
415      // Whitespace is allowed between the #! and the interpreter
416      while (isspace(*s)) s++;
417      if (strstart(&s, "/usr/bin/env")) while (isspace(*s)) s++;
418      for (what = s; (s-toybuf)<len && !isspace(*s); s++);
419      strcpy(s, " script");
420
421    // Distinguish ASCII text, UTF-8 text, or data
422    } else for (i = 0; i<len; ++i) {
423      if (!(isprint(toybuf[i]) || isspace(toybuf[i]))) {
424        unsigned wc;
425        if ((bytes = utf8towc(&wc, s+i, len-i))>0 && wcwidth(wc)>=0) {
426          i += bytes-1;
427          if (!what) what = "UTF-8 text";
428        } else {
429          what = "data";
430          break;
431        }
432      }
433    }
434    xputs(what ? what : "ASCII text");
435  }
436}
437
438void file_main(void)
439{
440  char **arg;
441
442  for (arg = toys.optargs; *arg; ++arg) {
443    int name_len = strlen(*arg);
444
445    if (name_len > TT.max_name_len) TT.max_name_len = name_len;
446  }
447
448  // Can't use loopfiles here because it doesn't call function when can't open
449  for (arg = toys.optargs; *arg; arg++) {
450    char *name = *arg, *what = "unknown";
451    struct stat sb;
452    int fd = !strcmp(name, "-");
453
454    if (!FLAG(b))
455      xprintf("%s: %*s", name, (int)(TT.max_name_len - strlen(name)), "");
456
457    sb.st_size = 0;
458    if (fd || !(FLAG(L) ? stat : lstat)(name, &sb)) {
459      if (!fd && !FLAG(s) && (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode))) {
460        sprintf(what = toybuf, "%s special (%u/%u)",
461            S_ISBLK(sb.st_mode) ? "block" : "character",
462            dev_major(sb.st_rdev), dev_minor(sb.st_rdev));
463      } else if (fd || S_ISREG(sb.st_mode)) {
464        TT.len = sb.st_size;
465        // This test identifies an empty file we don't have permission to read
466        if (!fd && !sb.st_size) what = "empty";
467        else if ((fd = openro(name, O_RDONLY)) != -1) {
468          do_regular_file(fd, name);
469          if (fd) close(fd);
470          continue;
471        }
472      } else if (S_ISFIFO(sb.st_mode)) what = "fifo";
473      else if (S_ISDIR(sb.st_mode)) what = "directory";
474      else if (S_ISSOCK(sb.st_mode)) what = "socket";
475      else if (S_ISLNK(sb.st_mode)) {
476        char *lnk = xreadlink(name);
477
478        sprintf(what = toybuf, "%ssymbolic link to %s",
479            stat(lnk, &sb) ? "broken " : "", lnk);
480        free(lnk);
481      }
482      xputs(what);
483    } else xprintf("cannot open: %s\n", strerror(errno));
484  }
485}
486