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