Home | History | Annotate | Download | only in posix
      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 
      7 USE_FILE(NEWTOY(file, "<1hL[!hL]", TOYFLAG_USR|TOYFLAG_BIN))
      8 
      9 config FILE
     10   bool "file"
     11   default y
     12   help
     13     usage: file [-hL] [file...]
     14 
     15     Examine the given files and describe their content types.
     16 
     17     -h	don't follow symlinks (default)
     18     -L	follow symlinks
     19 */
     20 
     21 #define FOR_file
     22 #include "toys.h"
     23 
     24 GLOBALS(
     25   int max_name_len;
     26 )
     27 
     28 // We don't trust elf.h to be there, and two codepaths for 32/64 is awkward
     29 // anyway, so calculate struct offsets manually. (It's a fixed ABI.)
     30 static void do_elf_file(int fd, struct stat *sb)
     31 {
     32   int endian = toybuf[5], bits = toybuf[4], i, j;
     33   int64_t (*elf_int)(void *ptr, unsigned size) = peek_le;
     34   // Values from include/linux/elf-em.h (plus arch/*/include/asm/elf.h)
     35   // Names are linux/arch/ directory (sometimes before 32/64 bit merges)
     36   struct {int val; char *name;} type[] = {{0x9026, "alpha"}, {93, "arc"},
     37     {195, "arcv2"}, {40, "arm"}, {183, "arm64"}, {0x18ad, "avr32"},
     38     {106, "blackfin"}, {140, "c6x"}, {23, "cell"}, {76, "cris"},
     39     {0x5441, "frv"}, {46, "h8300"}, {164, "hexagon"}, {50, "ia64"},
     40     {88, "m32r"}, {0x9041, "m32r"}, {4, "m68k"}, {174, "metag"},
     41     {0xbaab, "microblaze"}, {8, "mips"}, {10, "mips-old"}, {89, "mn10300"},
     42     {0xbeef, "mn10300-old"}, {113, "nios2"}, {92, "openrisc"},
     43     {0x8472, "openrisc-old"}, {15, "parisc"}, {20, "ppc"}, {21, "ppc64"},
     44     {22, "s390"}, {0xa390, "s390-old"}, {135, "score"}, {42, "sh"},
     45     {2, "sparc"}, {18, "sparc8+"}, {43, "sparc9"}, {188, "tile"},
     46     {191, "tilegx"}, {3, "386"}, {6, "486"}, {62, "x86-64"}, {94, "xtensa"},
     47     {0xabc7, "xtensa-old"}
     48   };
     49   int dynamic = 0;
     50   int stripped = 1;
     51   char *map;
     52   off_t phoff, shoff;
     53   int phentsize, phnum, shsize, shnum;
     54 
     55   printf("ELF ");
     56 
     57   // executable (ELF says this is short but reality says byte, not MSB swapped)
     58   i = toybuf[16];
     59   if (i == 1) printf("relocatable");
     60   else if (i == 2) printf("executable");
     61   else if (i == 3) printf("shared object");
     62   else if (i == 4) printf("core dump");
     63   else printf("(bad type %d)", i);
     64   printf(", ");
     65 
     66   // "64-bit"
     67   if (bits == 1) printf("32-bit ");
     68   else if (bits == 2) printf("64-bit ");
     69   else {
     70     printf("(bad class %d) ", bits);
     71     bits = 0;
     72   }
     73 
     74   // "LSB"
     75   if (endian == 1) printf("LSB ");
     76   else if (endian == 2) {
     77     printf("MSB ");
     78     elf_int = peek_be;
     79   } else {
     80     printf("(bad endian %d) \n", endian);
     81     endian = 0;
     82   }
     83 
     84   // e_machine, ala "x86", from big table above
     85   j = elf_int(toybuf+18, 2);
     86   for (i = 0; i<ARRAY_LEN(type); i++) if (j==type[i].val) break;
     87   if (i<ARRAY_LEN(type)) printf("%s", type[i].name);
     88   else printf("(unknown arch %d)", j);
     89 
     90   bits--;
     91   // If what we've seen so far doesn't seem consistent, bail.
     92   if (!((bits&1)==bits && endian)) {
     93     printf(", corrupt?\n");
     94     return;
     95   }
     96 
     97   // Stash what we need from the header; it's okay to reuse toybuf after this.
     98   phentsize = elf_int(toybuf+42+12*bits, 2);
     99   phnum = elf_int(toybuf+44+12*bits, 2);
    100   phoff = elf_int(toybuf+28+4*bits, 4+4*bits);
    101   shsize = elf_int(toybuf+46+12*bits, 2);
    102   shnum = elf_int(toybuf+48+12*bits, 2);
    103   shoff = elf_int(toybuf+32+8*bits, 4+4*bits);
    104 
    105   // With binutils, phentsize seems to only be non-zero if phnum is non-zero.
    106   // Such ELF files are rare, but do exist. (Android's crtbegin files, say.)
    107   if (phnum && (phentsize != 32+24*bits)) {
    108     printf(", corrupt phentsize %d?\n", phentsize);
    109     return;
    110   }
    111 
    112   map = mmap(0, sb->st_size, PROT_READ, MAP_SHARED, fd, 0);
    113   if (!map) perror_exit("mmap");
    114 
    115   // We need to read the phdrs for dynamic vs static.
    116   // (Note: fields got reordered for 64 bit)
    117   for (i = 0; i<phnum; i++) {
    118     char *phdr = map+phoff+i*phentsize;
    119     int p_type = elf_int(phdr, 4);
    120     long long p_offset, p_filesz;
    121 
    122     if (p_type==2 /*PT_DYNAMIC*/) dynamic = 1;
    123     if (p_type!=3 /*PT_INTERP*/ && p_type!=4 /*PT_NOTE*/) continue;
    124 
    125     j = bits+1;
    126     p_offset = elf_int(phdr+4*j, 4*j);
    127     p_filesz = elf_int(phdr+16*j, 4*j);
    128 
    129     if (p_type==3 /*PT_INTERP*/)
    130       printf(", dynamic (%.*s)", (int)p_filesz, map+p_offset);
    131   }
    132   if (!dynamic) printf(", static");
    133 
    134   // We need to read the shdrs for stripped/unstripped and any notes.
    135   // Notes are in program headers *and* section headers, but some files don't
    136   // contain program headers, so we prefer to check here.
    137   // (Note: fields got reordered for 64 bit)
    138   for (i = 0; i<shnum; i++) {
    139     char *shdr = map+shoff+i*shsize;
    140     int sh_type = elf_int(shdr+4, 4);
    141     long sh_offset = elf_int(shdr+8+8*(bits+1), 4*(bits+1));
    142     int sh_size = elf_int(shdr+8+12*(bits+1), 4);
    143 
    144     if (sh_type == 2 /*SHT_SYMTAB*/) {
    145       stripped = 0;
    146       break;
    147     } else if (sh_type == 7 /*SHT_NOTE*/) {
    148       char *note = map+sh_offset;
    149 
    150       // An ELF note is a sequence of entries, each consisting of an
    151       // ndhr followed by n_namesz+n_descsz bytes of data (each of those
    152       // rounded up to the next 4 bytes, without this being reflected in
    153       // the header byte counts themselves).
    154       while (sh_size >= 3*4) { // Don't try to read a truncated entry.
    155         int n_namesz = elf_int(note, 4);
    156         int n_descsz = elf_int(note+4, 4);
    157         int n_type = elf_int(note+8, 4);
    158         int notesz = 3*4 + ((n_namesz+3)&~3) + ((n_descsz+3)&~3);
    159 
    160         if (n_namesz==4 && !memcmp(note+12, "GNU", 4)) {
    161           if (n_type==3 /*NT_GNU_BUILD_ID*/) {
    162             printf(", BuildID=");
    163             for (j = 0; j < n_descsz; ++j) printf("%02x", note[16 + j]);
    164           }
    165         } else if (n_namesz==8 && !memcmp(note+12, "Android", 8)) {
    166           if (n_type==1 /*.android.note.ident*/) {
    167             printf(", for Android %d", (int)elf_int(note+20, 4));
    168             if (n_descsz > 24)
    169               printf(", built by NDK %.64s (%.64s)", note+24, note+24+64);
    170           }
    171         }
    172 
    173         note += notesz;
    174         sh_size -= notesz;
    175       }
    176     }
    177   }
    178   printf(", %sstripped", stripped ? "" : "not ");
    179   xputc('\n');
    180 
    181   munmap(map, sb->st_size);
    182 }
    183 
    184 static void do_regular_file(int fd, char *name, struct stat *sb)
    185 {
    186   char *s;
    187   int len = read(fd, s = toybuf, sizeof(toybuf)-256);
    188   int magic;
    189 
    190   if (len<0) perror_msg("%s", name);
    191 
    192   if (len>40 && strstart(&s, "\177ELF")) do_elf_file(fd, sb);
    193   else if (len>=8 && strstart(&s, "!<arch>\n")) xprintf("ar archive\n");
    194   else if (len>28 && strstart(&s, "\x89PNG\x0d\x0a\x1a\x0a")) {
    195     // PNG is big-endian: https://www.w3.org/TR/PNG/#7Integers-and-byte-order
    196     int chunk_length = peek_be(s, 4);
    197 
    198     xprintf("PNG image data");
    199 
    200     // The IHDR chunk comes first: https://www.w3.org/TR/PNG/#11IHDR
    201     s += 4;
    202     if (chunk_length == 13 && strstart(&s, "IHDR")) {
    203       // https://www.w3.org/TR/PNG/#6Colour-values
    204       char *c = 0, *colors[] = {"grayscale", 0, "color RGB", "indexed color",
    205                                 "grayscale with alpha", 0, "color RGBA"};
    206 
    207       if (s[9]<ARRAY_LEN(colors)) c = colors[s[9]];
    208       if (!c) c = "unknown";
    209 
    210       xprintf(", %d x %d, %d-bit/%s, %sinterlaced", (int)peek_be(s, 4),
    211         (int)peek_be(s+4, 4), s[8], c, s[12] ? "" : "non-");
    212     }
    213 
    214     xputc('\n');
    215 
    216   // https://www.w3.org/Graphics/GIF/spec-gif89a.txt
    217   } else if (len>16 && (strstart(&s, "GIF87a") || strstart(&s, "GIF89a")))
    218     xprintf("GIF image data, %d x %d\n",
    219       (int)peek_le(s, 2), (int)peek_le(s+8, 2));
    220 
    221   // TODO: parsing JPEG for width/height is harder than GIF or PNG.
    222   else if (len>32 && memcmp(toybuf, "\xff\xd8", 2) == 0)
    223     xprintf("JPEG image data\n");
    224 
    225   // https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html
    226   else if (len>8 && strstart(&s, "\xca\xfe\xba\xbe"))
    227     xprintf("Java class file, version %d.%d\n",
    228       (int)peek_be(s+2, 2), (int)peek_be(s, 2));
    229 
    230   // https://people.freebsd.org/~kientzle/libarchive/man/cpio.5.txt
    231   // the lengths for cpio are size of header + 9 bytes, since any valid
    232   // cpio archive ends with a record for "TARGET!!!"
    233   else if (len>85 && strstart(&s, "07070")) {
    234     char *cpioformat = "unknown type";
    235     if (toybuf[5] == '7') cpioformat = "pre-SVR4 or odc";
    236     else if (toybuf[5] == '1') cpioformat = "SVR4 with no CRC";
    237     else if (toybuf[5] == '2') cpioformat = "SVR4 with CRC";
    238     xprintf("ASCII cpio archive (%s)\n", cpioformat);
    239   } else if (len>33 && (magic=peek(&s,2), magic==0143561 || magic==070707)) {
    240     if (magic == 0143561) printf("byte-swapped ");
    241     xprintf("cpio archive\n");
    242   // tar archive (ustar/pax or gnu)
    243   } else if (len>500 && !strncmp(s+257, "ustar", 5)) {
    244     xprintf("POSIX tar archive%s\n", strncmp(s+262,"  ",2)?"":" (GNU)");
    245   // zip/jar/apk archive, ODF/OOXML document, or such
    246   } else if (len>5 && strstart(&s, "PK\03\04")) {
    247     int ver = (int)(char)(toybuf[4]);
    248     xprintf("Zip archive data");
    249     if (ver)
    250       xprintf(", requires at least v%d.%d to extract", ver/10, ver%10);
    251     xputc('\n');
    252   } else if (len>4 && strstart(&s, "BZh") && isdigit(*s)) {
    253     xprintf("bzip2 compressed data, block size = %c00k\n", *s);
    254   } else {
    255     char *what = 0;
    256     int i, bytes;
    257 
    258     // If shell script, report which interpreter
    259     if (len>3 && strstart(&s, "#!")) {
    260       // Whitespace is allowed between the #! and the interpreter
    261       while (isspace(*s)) s++;
    262       if (strstart(&s, "/usr/bin/env")) while (isspace(*s)) s++;
    263       for (what = s; (s-toybuf)<len && !isspace(*s); s++);
    264       strcpy(s, " script");
    265 
    266     // Distinguish ASCII text, UTF-8 text, or data
    267     } else for (i = 0; i<len; ++i) {
    268       if (!(isprint(toybuf[i]) || isspace(toybuf[i]))) {
    269         wchar_t wc;
    270         if ((bytes = mbrtowc(&wc, s+i, len-i, 0))>0 && wcwidth(wc)>=0) {
    271           i += bytes-1;
    272           if (!what) what = "UTF-8 text";
    273         } else {
    274           what = "data";
    275           break;
    276         }
    277       }
    278     }
    279     xputs(what ? what : "ASCII text");
    280   }
    281 }
    282 
    283 void file_main(void)
    284 {
    285   char **arg;
    286 
    287   for (arg = toys.optargs; *arg; ++arg) {
    288     int name_len = strlen(*arg);
    289 
    290     if (name_len > TT.max_name_len) TT.max_name_len = name_len;
    291   }
    292 
    293   // Can't use loopfiles here because it doesn't call function when can't open
    294   for (arg = toys.optargs; *arg; arg++) {
    295     char *name = *arg, *what = "cannot open";
    296     struct stat sb;
    297     int fd = !strcmp(name, "-");
    298 
    299     xprintf("%s: %*s", name, (int)(TT.max_name_len - strlen(name)), "");
    300 
    301     if (fd || !((toys.optflags & FLAG_L) ? stat : lstat)(name, &sb)) {
    302       if (fd || S_ISREG(sb.st_mode)) {
    303         if (!sb.st_size) what = "empty";
    304         else if ((fd = openro(name, O_RDONLY)) != -1) {
    305           do_regular_file(fd, name, &sb);
    306           if (fd) close(fd);
    307           continue;
    308         }
    309       } else if (S_ISFIFO(sb.st_mode)) what = "fifo";
    310       else if (S_ISBLK(sb.st_mode)) what = "block special";
    311       else if (S_ISCHR(sb.st_mode)) what = "character special";
    312       else if (S_ISDIR(sb.st_mode)) what = "directory";
    313       else if (S_ISSOCK(sb.st_mode)) what = "socket";
    314       else if (S_ISLNK(sb.st_mode)) what = "symbolic link";
    315       else what = "unknown";
    316     }
    317 
    318     xputs(what);
    319   }
    320 }
    321