toybox/toys/posix/file.c
<<
>>
Prefs
   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  off_t len;
  29)
  30
  31// We don't trust elf.h to be there, and two codepaths for 32/64 is awkward
  32// anyway, so calculate struct offsets manually. (It's a fixed ABI.)
  33static void do_elf_file(int fd)
  34{
  35  unsigned endian = toybuf[5], bits = toybuf[4]-1, i, j, dynamic = 0,
  36           stripped = 1, phentsize, phnum, shsize, shnum, bail = 0;
  37  int64_t (*elf_int)(void *ptr, unsigned size) = (endian==2)?peek_be:peek_le;
  38  char *map = MAP_FAILED;
  39  unsigned long phoff, shoff;
  40
  41  printf("ELF ");
  42
  43  // executable type
  44  i = elf_int(toybuf+16, 2);
  45  if (i == 1) printf("relocatable");
  46  else if (i == 2) printf("executable");
  47  else if (i == 3) printf("shared object");
  48  else if (i == 4) printf("core dump");
  49  else {
  50    printf("(bad type %d)", i);
  51    bail++;
  52  }
  53  if (elf_int(toybuf+36+12*!!bits, 4) & 0x8000) printf(" (fdpic)");
  54  printf(", ");
  55
  56  // "64-bit"
  57  if (bits&~1) {
  58    printf("(bad class %d) ", bits);
  59    bail++;
  60  } else printf("%d-bit ", 32<<bits);
  61
  62  // "LSB"
  63  if (endian == 1) printf("LSB ");
  64  else if (endian == 2) printf("MSB ");
  65  else {
  66    printf("(bad endian %d) ", endian);
  67    bail++;
  68  }
  69
  70  // "x86".
  71  printf("%s", elf_arch_name(elf_int(toybuf+18, 2)));
  72
  73  // If what we've seen so far doesn't seem consistent, bail.
  74  if (bail) goto bad;
  75
  76  // Stash what we need from the header; it's okay to reuse toybuf after this.
  77  phentsize = elf_int(toybuf+42+12*bits, 2);
  78  phnum = elf_int(toybuf+44+12*bits, 2);
  79  phoff = elf_int(toybuf+28+4*bits, 4+4*bits);
  80  shsize = elf_int(toybuf+46+12*bits, 2);
  81  shnum = elf_int(toybuf+48+12*bits, 2);
  82  shoff = elf_int(toybuf+32+8*bits, 4+4*bits);
  83
  84  // With binutils, phentsize seems to only be non-zero if phnum is non-zero.
  85  // Such ELF files are rare, but do exist. (Android's crtbegin files, say.)
  86  if (phnum && (phentsize != 32+24*bits)) {
  87    printf(", bad phentsize %d?", phentsize);
  88    goto bad;
  89  }
  90  if (phoff>TT.len || phnum*phentsize>TT.len-phoff) {
  91    printf(", bad phoff %lu?", phoff);
  92    goto bad;
  93  }
  94  if (shoff>TT.len || shnum*shsize>TT.len-shoff) {
  95    printf(", bad shoff %lu?", phoff);
  96    goto bad;
  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    perror_msg("mmap");
 104    goto bad;
 105  }
 106
 107  // Read the phdrs for dynamic vs static. (Note: fields reordered on 64 bit)
 108  for (i = 0; i<phnum; i++) {
 109    char *phdr = map+phoff+i*phentsize;
 110    unsigned p_type = elf_int(phdr, 4);
 111    unsigned long long p_offset, p_filesz;
 112
 113    // TODO: what does PT_DYNAMIC without PT_INTERP mean?
 114    if (p_type-2>2) continue; // 2 = PT_DYNAMIC, 3 = PT_INTERP, 4 = PT_NOTE
 115    dynamic |= p_type==2;
 116    p_offset = elf_int(phdr+(4<<bits), 4<<bits);
 117    p_filesz = elf_int(phdr+(16<<bits), 4<<bits);
 118    if (p_type==3) {
 119      if (p_filesz>TT.len || p_offset>TT.len-p_filesz) {
 120        printf(", bad phdr %d?", i);
 121        goto bad;
 122      }
 123      // TODO: if (int)<0 prints endlessly, could go off end of map?
 124      printf(", dynamic (%.*s)", (int)p_filesz, map+p_offset);
 125    }
 126  }
 127  if (!dynamic) printf(", static");
 128
 129  // We need to read the shdrs for stripped/unstripped and any notes.
 130  // Notes are in program headers *and* section headers, but some files don't
 131  // contain program headers, so check here. (Note: fields reordered on 64 bit)
 132  for (i = 0; i<shnum; i++) {
 133    char *shdr = map+shoff+i*shsize;
 134    unsigned long sh_offset;
 135    int sh_type, sh_size;
 136
 137    if (shdr>map+TT.len-(8+(4<<bits))) {
 138      printf(", bad shdr %d?", i);
 139      goto bad;
 140    }
 141    sh_type = elf_int(shdr+4, 4);
 142    sh_offset = elf_int(shdr+8+(8<<bits), 4<<bits);
 143    sh_size = elf_int(shdr+8+(12<<bits), 4);
 144    if (sh_type == 8 /*SHT_NOBITS*/) sh_size = 0;
 145    if (sh_offset>TT.len || sh_size>TT.len-sh_offset) {
 146      printf(", bad shdr %d?", i);
 147      goto bad;
 148    }
 149
 150    if (sh_type == 2 /*SHT_SYMTAB*/) {
 151      stripped = 0;
 152      break;
 153    } else if (sh_type == 7 /*SHT_NOTE*/) {
 154      char *note = map+sh_offset;
 155
 156      // An ELF note is a sequence of entries, each consisting of an
 157      // ndhr followed by n_namesz+n_descsz bytes of data (each of those
 158      // rounded up to the next 4 bytes, without this being reflected in
 159      // the header byte counts themselves).
 160      while (sh_size >= 3*4) { // Don't try to read a truncated entry.
 161        unsigned n_namesz, n_descsz, n_type, notesz;
 162
 163        if (note>map+TT.len-3*4) {
 164          printf(", bad note %d?", i);
 165          goto bad;
 166        }
 167
 168        n_namesz = elf_int(note, 4);
 169        n_descsz = elf_int(note+4, 4);
 170        n_type = elf_int(note+8, 4);
 171        notesz = 3*4 + ((n_namesz+3)&~3) + ((n_descsz+3)&~3);
 172
 173        // Are the name/desc sizes consistent, and does the claimed size of
 174        // the note actually fit in the section?
 175        if (notesz<n_namesz || notesz<n_descsz || notesz>sh_size) {
 176          printf(", bad note %d size?", i);
 177          goto bad;
 178        }
 179
 180        if (n_namesz==4 && !memcmp(note+12, "GNU", 4) && n_type==3) {
 181          printf(", BuildID=");
 182          for (j = 0; j<n_descsz; j++) printf("%02x", note[16+j]);
 183        } else if (n_namesz==8 && !memcmp(note+12, "Android", 8)) {
 184          if (n_type==1 /*.android.note.ident*/ && n_descsz >= 4) {
 185            printf(", for Android %d", (int)elf_int(note+20, 4));
 186            // NDK r14 and later also include NDK version info. OS binaries
 187            // and binaries built by older NDKs don't have this.
 188            if (n_descsz >= 4+64+64)
 189              printf(", built by NDK %.64s (%.64s)", note+24, note+24+64);
 190          }
 191        }
 192
 193        note += notesz;
 194        sh_size -= notesz;
 195      }
 196    }
 197  }
 198  printf(", %sstripped", stripped ? "" : "not ");
 199bad:
 200  xputc('\n');
 201
 202  if (map != MAP_FAILED) munmap(map, TT.len);
 203}
 204
 205static void do_regular_file(int fd, char *name)
 206{
 207  char *s = toybuf;
 208  unsigned len, magic;
 209  int ii;
 210
 211  // zero through elf shnum, just in case
 212  memset(s, 0, 80);
 213  if ((len = readall(fd, s, sizeof(toybuf)-8))<0) perror_msg("%s", name);
 214
 215  if (!len) xputs("empty");
 216  // 45 bytes: https://www.muppetlabs.com/~breadbox/software/tiny/teensy.html
 217  else if (len>=45 && strstart(&s, "\177ELF")) do_elf_file(fd);
 218  else if (strstart(&s, "!<arch>\n")) xputs("ar archive");
 219  else if (*s=='%' && 2==sscanf(s, "%%PDF%d.%u", &ii, &magic))
 220    xprintf("PDF document, version %d.%u\n", -ii, magic);
 221  else if (len>28 && strstart(&s, "\x89PNG\x0d\x0a\x1a\x0a")) {
 222    // PNG is big-endian: https://www.w3.org/TR/PNG/#7Integers-and-byte-order
 223    int chunk_length = peek_be(s, 4);
 224
 225    xprintf("PNG image data");
 226
 227    // The IHDR chunk comes first: https://www.w3.org/TR/PNG/#11IHDR
 228    s += 4;
 229    if (chunk_length == 13 && strstart(&s, "IHDR")) {
 230      // https://www.w3.org/TR/PNG/#6Colour-values
 231      char *c = 0, *colors[] = {"grayscale", 0, "color RGB", "indexed color",
 232                                "grayscale with alpha", 0, "color RGBA"};
 233
 234      if (s[9]<ARRAY_LEN(colors)) c = colors[s[9]];
 235      xprintf(", %d x %d, %d-bit/%s, %sinterlaced", (int)peek_be(s, 4),
 236        (int)peek_be(s+4, 4), s[8], c ? : "unknown", s[12] ? "" : "non-");
 237    }
 238
 239    xputc('\n');
 240
 241  // https://www.w3.org/Graphics/GIF/spec-gif89a.txt
 242  } else if (len>16 && (strstart(&s, "GIF87a") || strstart(&s, "GIF89a")))
 243    xprintf("GIF image data, version %3.3s, %d x %d\n",
 244      s-3, (int)peek_le(s, 2), (int)peek_le(s+2, 2));
 245
 246  // TODO: parsing JPEG for width/height is harder than GIF or PNG.
 247  else if (len>32 && !memcmp(s, "\xff\xd8", 2)) xputs("JPEG image data");
 248
 249  else if (len>8 && strstart(&s, "\xca\xfe\xba\xbe")) {
 250    unsigned count = peek_be(s, 4), i, arch;
 251
 252    // 0xcafebabe can be a Java class file or a Mach-O universal binary.
 253    // Java major version numbers start with 0x2d for JDK 1.1, and realistically
 254    // you're never going to see more than 2 architectures in a binary anyway...
 255    if (count<0x2d && len>=(count*20)) {
 256      // https://eclecticlight.co/2020/07/28/universal-binaries-inside-fat-headers/
 257      xprintf("Mach-O universal binary with %u architecture%s:",
 258        count, count == 1 ? "" : "s");
 259      for (i = 0, s += 4; i < count; i++, s += 20) {
 260        arch = peek_be(s, 4);
 261        if (arch == 0x00000007) name = "i386";
 262        else if (arch == 0x01000007) name = "x86_64";
 263        else if (arch == 0x0000000c) name = "arm";
 264        else if (arch == 0x0100000c) name = "arm64";
 265        else name = "unknown";
 266        xprintf(" [%s]", name);
 267      }
 268      xprintf("\n");
 269    } else {
 270      // https://en.wikipedia.org/wiki/Java_class_file#General_layout
 271      xprintf("Java class file, version %d.%d (Java 1.%d)\n",
 272        (int)peek_be(s+2, 2), (int)peek_be(s, 2), (int)peek_be(s+2, 2)-44);
 273    }
 274
 275  // https://source.android.com/devices/tech/dalvik/dex-format#dex-file-magic
 276  } else if (len>8 && strstart(&s, "dex\n") && !s[3])
 277    xprintf("Android dex file, version %s\n", s);
 278
 279  // https://people.freebsd.org/~kientzle/libarchive/man/cpio.5.txt
 280  // the lengths for cpio are size of header + 9 bytes, since any valid
 281  // cpio archive ends with a record for "TARGET!!!"
 282  else if (len>6 && strstart(&s, "07070")) {
 283    char *cpioformat = "unknown type";
 284
 285    if (*s == '7') cpioformat = "pre-SVR4 or odc";
 286    else if (*s == '1') cpioformat = "SVR4 with no CRC";
 287    else if (*s == '2') cpioformat = "SVR4 with CRC";
 288    xprintf("ASCII cpio archive (%s)\n", cpioformat);
 289  } else if (len>33 && ((magic=peek(&s,2))==0143561 || magic==070707)) {
 290    if (magic == 0143561) printf("byte-swapped ");
 291    xputs("cpio archive");
 292  // tar archive (old, ustar/pax, or gnu)
 293  } else if (len>500 && is_tar_header(s))
 294    xprintf("%s tar archive%s\n", s[257] ? "POSIX" : "old",
 295      (s[262]!=' ' || s[263]!=' ')?"":" (GNU)");
 296  // zip/jar/apk archive, ODF/OOXML document, or such
 297  else if (len>5 && strstart(&s, "PK\03\04")) {
 298    xprintf("Zip archive data");
 299    if (*s) xprintf(", requires at least v%d.%d to extract", *s/10, *s%10);
 300    xputc('\n');
 301  } else if (len>9 && strstart(&s, "7z\xbc\xaf\x27\x1c")) {
 302    xprintf("7-zip archive data");
 303    if (*s || s[1]) xprintf(", version %d.%d", *s, s[1]);
 304    xputc('\n');
 305  } else if (len>4 && strstart(&s, "BZh") && isdigit(*s))
 306    xprintf("bzip2 compressed data, block size = %c00k\n", *s);
 307  else if (len>31 && peek_be(s, 7) == 0xfd377a585a0000UL)
 308    xputs("xz compressed data");
 309  else if (len>10 && strstart(&s, "\x1f\x8b")) xputs("gzip compressed data");
 310  else if (len>32 && !memcmp(s+1, "\xfa\xed\xfe", 3)) {
 311    int bit = (*s==0xce) ? 32 : 64;
 312    char *what = 0;
 313
 314    xprintf("Mach-O %d-bit ", bit);
 315
 316    if (s[4] == 7) what = (bit==32)?"x86":"x86-";
 317    else if (s[4] == 12) what = "arm";
 318    else if (s[4] == 18) what = "ppc";
 319    if (what) xprintf("%s%s ", what, (bit==32)?"":"64");
 320    else xprintf("(bad arch %d) ", s[4]);
 321
 322    if (s[12] == 1) what = "object";
 323    else if (s[12] == 2) what = "executable";
 324    else if (s[12] == 6) what = "shared library";
 325    else what = NULL;
 326    if (what) xprintf("%s\n", what);
 327    else xprintf("(bad type %d)\n", s[9]);
 328  } else if (len>36 && !memcmp(s, "OggS\x00\x02", 6)) {
 329    xprintf("Ogg data");
 330    // https://wiki.xiph.org/MIMETypesCodecs
 331    if (!memcmp(s+28, "CELT    ", 8)) xprintf(", celt audio");
 332    else if (!memcmp(s+28, "CMML    ", 8)) xprintf(", cmml text");
 333    else if (!memcmp(s+28, "BBCD\0", 5)) xprintf(", dirac video");
 334    else if (!memcmp(s+28, "\177FLAC", 5)) xprintf(", flac audio");
 335    else if (!memcmp(s+28, "\x8bJNG\r\n\x1a\n", 8)) xprintf(", jng video");
 336    else if (!memcmp(s+28, "\x80kate\0\0\0", 8)) xprintf(", kate text");
 337    else if (!memcmp(s+28, "OggMIDI\0", 8)) xprintf(", midi text");
 338    else if (!memcmp(s+28, "\x8aMNG\r\n\x1a\n", 8)) xprintf(", mng video");
 339    else if (!memcmp(s+28, "OpusHead", 8)) xprintf(", opus audio");
 340    else if (!memcmp(s+28, "PCM     ", 8)) xprintf(", pcm audio");
 341    else if (!memcmp(s+28, "\x89PNG\r\n\x1a\n", 8)) xprintf(", png video");
 342    else if (!memcmp(s+28, "Speex   ", 8)) xprintf(", speex audio");
 343    else if (!memcmp(s+28, "\x80theora", 7)) xprintf(", theora video");
 344    else if (!memcmp(s+28, "\x01vorbis", 7)) xprintf(", vorbis audio");
 345    else if (!memcmp(s+28, "YUV4MPEG", 8)) xprintf(", yuv4mpeg video");
 346    xputc('\n');
 347  } else if (len>32 && !memcmp(s, "RIF", 3) && !memcmp(s+8, "WAVEfmt ", 8)) {
 348    // https://en.wikipedia.org/wiki/WAV
 349    int le = (s[3] == 'F');
 350    int format = le ? peek_le(s+20, 2) : peek_be(s+20, 2);
 351    int channels = le ? peek_le(s+22, 2) : peek_be(s+22, 2);
 352    int hz = le ? peek_le(s+24, 4) : peek_be(s+24, 4);
 353    int bits = le ? peek_le(s+34, 2) : peek_be(s+34, 2);
 354
 355    xprintf("WAV audio, %s, ", le ? "LE" : "BE");
 356    if (bits) xprintf("%d-bit, ", bits);
 357    if (channels==1||channels==2) xprintf("%s, ",(channels==1)?"mono":"stereo");
 358    else xprintf("%d-channel, ", channels);
 359    xprintf("%d Hz, ", hz);
 360    // See https://tools.ietf.org/html/rfc2361, though there appear to be bugs
 361    // in the RFC. This assumes wikipedia's example files are more correct.
 362    if (format == 0x01) xprintf("PCM");
 363    else if (format == 0x03) xprintf("IEEE float");
 364    else if (format == 0x06) xprintf("A-law");
 365    else if (format == 0x07) xprintf("ยต-law");
 366    else if (format == 0x11) xprintf("ADPCM");
 367    else if (format == 0x22) xprintf("Truespeech");
 368    else if (format == 0x31) xprintf("GSM");
 369    else if (format == 0x55) xprintf("MP3");
 370    else if (format == 0x70) xprintf("CELP");
 371    else if (format == 0xfffe) xprintf("extensible");
 372    else xprintf("unknown format %d", format);
 373    xputc('\n');
 374  } else if (len>12 && peek_be(s, 4)==0x10000) xputs("TrueType font");
 375  else if (len>12 && !memcmp(s, "ttcf\x00", 5)) {
 376    xprintf("TrueType font collection, version %d, %d fonts\n",
 377            (int)peek_be(s+4, 2), (int)peek_be(s+8, 4));
 378
 379  // https://docs.microsoft.com/en-us/typography/opentype/spec/otff
 380  } else if (len>12 && strstart(&s, "OTTO")) xputs("OpenType font");
 381  else if (strstart(&s, "BC\xc0\xde")) xputs("LLVM IR bitcode");
 382  else if (strstart(&s,"-----BEGIN CERTIFICATE-----")) xputs("PEM certificate");
 383
 384  // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680547(v=vs.85).aspx
 385  else if (len>0x70 && !memcmp(s, "MZ", 2) &&
 386      (magic=peek_le(s+0x3c,4))<len-4 && !memcmp(s+magic, "\x50\x45\0", 4)) {
 387
 388    // Linux kernel images look like PE files.
 389    if (!memcmp(s+0x38, "ARM\x64", 4)) {
 390      // https://www.kernel.org/doc/Documentation/arm64/booting.txt
 391      // I've only ever seen LE, 4KiB pages, so ignore flags for now.
 392      xputs("Linux arm64 kernel image");
 393      return;
 394    } else if (!memcmp(s+0x202, "HdrS", 4)) {
 395      // https://www.kernel.org/doc/Documentation/x86/boot.txt
 396      unsigned ver_off = peek_le(s+0x20e, 2);
 397
 398      xprintf("Linux x86-64 kernel image");
 399      if ((0x200 + ver_off) < len) {
 400        s += 0x200 + ver_off;
 401      } else {
 402        if (lseek(fd, ver_off - len + 0x200, SEEK_CUR)<0 ||
 403            (len = readall(fd, s, sizeof(toybuf)))<0) {
 404          perror_msg("%s", name);
 405          return;
 406        }
 407      }
 408      xprintf(", version %s\n", s);
 409      return;
 410    }
 411
 412    xprintf("MS PE32%s executable %s", (peek_le(s+magic+24, 2)==0x20b)?"+":"",
 413        (peek_le(s+magic+22, 2)&0x2000)?"(DLL) ":"");
 414    if (peek_le(s+magic+20, 2)>70) {
 415      char *types[] = {0, "native", "GUI", "console", "OS/2", "driver", "CE",
 416          "EFI", "EFI boot", "EFI runtime", "EFI ROM", "XBOX", 0, "boot"}, *nn;
 417      unsigned type = peek_le(s+magic+92, 2);
 418
 419      nn = (type<ARRAY_LEN(types)) ? types[type] : 0;
 420      xprintf("(%s) ", nn ? : "unknown");
 421    }
 422    xprintf("x86%s\n", (peek_le(s+magic+4, 2)==0x14c) ? "" : "-64");
 423
 424    // https://en.wikipedia.org/wiki/BMP_file_format
 425  } else if (len>0x32 && !memcmp(s, "BM", 2) && !peek_be(s+6, 4)) {
 426    xprintf("BMP image, %d x %d, %d bpp\n", (int)peek_le(s+18, 4),
 427            (int)peek_le(s+22,4), (int)peek_le(s+28, 2));
 428
 429    // https://github.com/torvalds/linux/blob/master/tools/perf/Documentation/perf.data-file-format.txt
 430  } else if (len>=104 && strstart(&s, "PERFILE2")) xputs("Linux perf data");
 431
 432    // https://android.googlesource.com/platform/system/core/+/master/libsparse/sparse_format.h
 433  else if (len>28 && peek_le(s, 4) == 0xed26ff3a) {
 434    xprintf("Android sparse image v%d.%d, %d %d-byte blocks (%d chunks)\n",
 435        (int)peek_le(s+4, 2), (int)peek_le(s+6, 2), (int)peek_le(s+16, 4),
 436        (int)peek_le(s+12, 4), (int)peek_le(s+20, 4));
 437
 438    // https://android.googlesource.com/platform/system/tools/mkbootimg/+/refs/heads/master/include/bootimg/bootimg.h
 439  } else if (len>1632 && !memcmp(s, "ANDROID!", 8)) {
 440    xprintf("Android boot image v%d\n", (int)peek_le(s+40, 4));
 441
 442    // https://source.android.com/devices/architecture/dto/partitions
 443  } else if (len>32 && peek_be(s, 4) == 0xd7b7ab1e) {
 444    xprintf("Android DTB/DTBO v%d, %d entries\n", (int)peek_be(s+28, 4),
 445            (int)peek_be(s+16, 4));
 446
 447    // frameworks/base/core/java/com/android/internal/util/BinaryXmlSerializer.java
 448  } else if (len>4 && !memcmp(s, "ABX", 3)) {
 449    xprintf("Android Binary XML v%d\n", s[3]);
 450
 451    // Text files, including shell scripts.
 452  } else {
 453    char *what = 0;
 454    int i, bytes;
 455
 456    // If shell script, report which interpreter
 457    if (len>3 && strstart(&s, "#!")) {
 458      // Whitespace is allowed between the #! and the interpreter
 459      while (isspace(*s)) s++;
 460      if (strstart(&s, "/usr/bin/env")) while (isspace(*s)) s++;
 461      for (what = s; *s && !isspace(*s); s++);
 462      strcpy(s, " script");
 463
 464    // Distinguish ASCII text, UTF-8 text, or data
 465    } else for (i = 0; i<len; ++i) {
 466      if (!(isprint(s[i]) || isspace(s[i]))) {
 467        unsigned wc;
 468
 469        if ((bytes = utf8towc(&wc, s+i, len-i))>0 && wcwidth(wc)>=0) {
 470          i += bytes-1;
 471          if (!what) what = "UTF-8 text";
 472        } else {
 473          what = "data";
 474          break;
 475        }
 476      }
 477    }
 478    xputs(what ? what : "ASCII text");
 479  }
 480}
 481
 482void file_main(void)
 483{
 484  char **arg;
 485
 486  for (arg = toys.optargs; *arg; ++arg)
 487    TT.max_name_len = maxof(strlen(*arg), TT.max_name_len);
 488
 489  // Can't use loopfiles here because it doesn't call function when can't open
 490  for (arg = toys.optargs; *arg; arg++) {
 491    char *name = *arg, *what = "unknown";
 492    struct stat sb;
 493    int fd = !strcmp(name, "-");
 494
 495    if (!FLAG(b))
 496      xprintf("%s: %*s", name, (int)(TT.max_name_len - strlen(name)), "");
 497
 498    sb.st_size = 0;
 499    if (!fd && (FLAG(L) ? stat : lstat)(name, &sb)) {
 500      xprintf("cannot open: %s\n", strerror(errno));
 501
 502      continue;
 503    }
 504
 505    if (!fd && !FLAG(s) && (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode))) {
 506      sprintf(what = toybuf, "%s special (%u/%u)",
 507          S_ISBLK(sb.st_mode) ? "block" : "character",
 508          dev_major(sb.st_rdev), dev_minor(sb.st_rdev));
 509    } else if (fd || S_ISREG(sb.st_mode)) {
 510      TT.len = sb.st_size;
 511      // This test identifies an empty file we don't have permission to read
 512      if (!fd && !sb.st_size) what = "empty";
 513      else if ((fd = openro(name, O_RDONLY)) != -1) {
 514        do_regular_file(fd, name);
 515        if (fd) close(fd);
 516
 517        continue;
 518      }
 519    } else if (S_ISFIFO(sb.st_mode)) what = "fifo";
 520    else if (S_ISDIR(sb.st_mode)) what = "directory";
 521    else if (S_ISSOCK(sb.st_mode)) what = "socket";
 522    else if (S_ISLNK(sb.st_mode)) {
 523      char *lnk = xreadlink(name);
 524
 525      sprintf(what = toybuf, "%ssymbolic link to %s",
 526          stat(name, &sb) ? "broken " : "", lnk);
 527      free(lnk);
 528    }
 529    xputs(what);
 530  }
 531}
 532