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