xref: /aosp_15_r20/external/toybox/toys/posix/file.c (revision cf5a6c84e2b8763fc1a7db14496fd4742913b199)
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, "\x1f\x8b")) xputs("gzip compressed data");
326   else if (len>32 && !smemcmp(s+1, "\xfa\xed\xfe", 3)) {
327     int bit = (*s==0xce) ? 32 : 64;
328     char *what = 0;
329 
330     xprintf("Mach-O %d-bit ", bit);
331 
332     if (s[4] == 7) what = (bit==32)?"x86":"x86-";
333     else if (s[4] == 12) what = "arm";
334     else if (s[4] == 18) what = "ppc";
335     if (what) xprintf("%s%s ", what, (bit==32)?"":"64");
336     else xprintf("(bad arch %d) ", s[4]);
337 
338     if (s[12] == 1) what = "object";
339     else if (s[12] == 2) what = "executable";
340     else if (s[12] == 6) what = "shared library";
341     else what = NULL;
342     if (what) xprintf("%s\n", what);
343     else xprintf("(bad type %d)\n", s[9]);
344   } else if (len>36 && !smemcmp(s, "OggS\x00\x02", 6)) {
345     xprintf("Ogg data");
346     // https://wiki.xiph.org/MIMETypesCodecs
347     if (!smemcmp(s+28, "CELT    ", 8)) xprintf(", celt audio");
348     else if (!smemcmp(s+28, "CMML    ", 8)) xprintf(", cmml text");
349     else if (!smemcmp(s+28, "BBCD", 5)) xprintf(", dirac video");
350     else if (!smemcmp(s+28, "\177FLAC", 5)) xprintf(", flac audio");
351     else if (!smemcmp(s+28, "\x8bJNG\r\n\x1a\n", 8)) xprintf(", jng video");
352     else if (!smemcmp(s+28, "\x80kate\0\0", 8)) xprintf(", kate text");
353     else if (!smemcmp(s+28, "OggMIDI", 8)) xprintf(", midi text");
354     else if (!smemcmp(s+28, "\x8aMNG\r\n\x1a\n", 8)) xprintf(", mng video");
355     else if (!smemcmp(s+28, "OpusHead", 8)) xprintf(", opus audio");
356     else if (!smemcmp(s+28, "PCM     ", 8)) xprintf(", pcm audio");
357     else if (!smemcmp(s+28, "\x89PNG\r\n\x1a\n", 8)) xprintf(", png video");
358     else if (!smemcmp(s+28, "Speex   ", 8)) xprintf(", speex audio");
359     else if (!smemcmp(s+28, "\x80theora", 7)) xprintf(", theora video");
360     else if (!smemcmp(s+28, "\x01vorbis", 7)) xprintf(", vorbis audio");
361     else if (!smemcmp(s+28, "YUV4MPEG", 8)) xprintf(", yuv4mpeg video");
362     xputc('\n');
363   } else if (len>32 && !smemcmp(s, "RIF", 3) && !smemcmp(s+8, "WAVEfmt ", 8)) {
364     // https://en.wikipedia.org/wiki/WAV
365     int le = (s[3] == 'F');
366     int format = le ? peek_le(s+20, 2) : peek_be(s+20, 2);
367     int channels = le ? peek_le(s+22, 2) : peek_be(s+22, 2);
368     int hz = le ? peek_le(s+24, 4) : peek_be(s+24, 4);
369     int bits = le ? peek_le(s+34, 2) : peek_be(s+34, 2);
370 
371     xprintf("WAV audio, %s, ", le ? "LE" : "BE");
372     if (bits) xprintf("%d-bit, ", bits);
373     if (channels==1||channels==2) xprintf("%s, ",(channels==1)?"mono":"stereo");
374     else xprintf("%d-channel, ", channels);
375     xprintf("%d Hz, ", hz);
376     // See https://tools.ietf.org/html/rfc2361, though there appear to be bugs
377     // in the RFC. This assumes wikipedia's example files are more correct.
378     if (format == 0x01) xprintf("PCM");
379     else if (format == 0x03) xprintf("IEEE float");
380     else if (format == 0x06) xprintf("A-law");
381     else if (format == 0x07) xprintf("µ-law");
382     else if (format == 0x11) xprintf("ADPCM");
383     else if (format == 0x22) xprintf("Truespeech");
384     else if (format == 0x31) xprintf("GSM");
385     else if (format == 0x55) xprintf("MP3");
386     else if (format == 0x70) xprintf("CELP");
387     else if (format == 0xfffe) xprintf("extensible");
388     else xprintf("unknown format %d", format);
389     xputc('\n');
390   } else if (len>12 && peek_be(s, 4)==0x10000) xputs("TrueType font");
391   else if (len>12 && !smemcmp(s, "ttcf", 5)) {
392     xprintf("TrueType font collection, version %d, %d fonts\n",
393             (int)peek_be(s+4, 2), (int)peek_be(s+8, 4));
394 
395   // https://docs.microsoft.com/en-us/typography/opentype/spec/otff
396   } else if (len>12 && strstart(&s, "OTTO")) xputs("OpenType font");
397   else if (strstart(&s, "BC\xc0\xde")) xputs("LLVM IR bitcode");
398   else if (strstart(&s,"-----BEGIN CERTIFICATE-----")) xputs("PEM certificate");
399 
400   // https://msdn.microsoft.com/en-us/library/windows/desktop/ms680547(v=vs.85).aspx
401   else if (len>0x70 && !smemcmp(s, "MZ", 2) &&
402       (magic=peek_le(s+0x3c,4))<len-4 && !smemcmp(s+magic, "\x50\x45\0", 4)) {
403 
404     // Linux kernel images look like PE files.
405     // https://www.kernel.org/doc/Documentation/arm64/booting.txt
406     // I've only ever seen LE, 4KiB pages, so ignore flags for now.
407     if (!smemcmp(s+0x38, "ARMd", 4)) return xputs("Linux arm64 kernel image");
408     else if (!smemcmp(s+0x202, "HdrS", 4)) {
409       // https://www.kernel.org/doc/Documentation/x86/boot.txt
410       unsigned ver_off = peek_le(s+0x20e, 2);
411 
412       xprintf("Linux x86-64 kernel image");
413       if ((0x200 + ver_off) < len) {
414         s += 0x200 + ver_off;
415       } else {
416         if (lseek(fd, ver_off - len + 0x200, SEEK_CUR)<0 ||
417             (len = readall(fd, s, sizeof(toybuf)))<0)
418           return perror_msg_raw(name);
419       }
420       xprintf(", version %s\n", s);
421       return;
422     }
423 
424     xprintf("MS PE32%s executable %s", (peek_le(s+magic+24, 2)==0x20b)?"+":"",
425         (peek_le(s+magic+22, 2)&0x2000)?"(DLL) ":"");
426     if (peek_le(s+magic+20, 2)>70) {
427       char *types[] = {0, "native", "GUI", "console", "OS/2", "driver", "CE",
428           "EFI", "EFI boot", "EFI runtime", "EFI ROM", "XBOX", 0, "boot"}, *nn;
429       unsigned type = peek_le(s+magic+92, 2);
430 
431       nn = (type<ARRAY_LEN(types)) ? types[type] : 0;
432       xprintf("(%s) ", nn ? : "unknown");
433     }
434     xprintf("x86%s\n", (peek_le(s+magic+4, 2)==0x14c) ? "" : "-64");
435 
436     // https://en.wikipedia.org/wiki/BMP_file_format
437   } else if (len>0x32 && !smemcmp(s, "BM", 2) && !peek_be(s+6, 4)) {
438     xprintf("BMP image, %d x %d, %d bpp\n", (int)peek_le(s+18, 4),
439             (int)peek_le(s+22,4), (int)peek_le(s+28, 2));
440 
441     // https://github.com/torvalds/linux/blob/master/tools/perf/Documentation/perf.data-file-format.txt
442   } else if (len>=104 && strstart(&s, "PERFILE2")) xputs("Linux perf data");
443 
444     // https://android.googlesource.com/platform/system/core/+/master/libsparse/sparse_format.h
445   else if (len>28 && peek_le(s, 4) == 0xed26ff3a) {
446     xprintf("Android sparse image v%d.%d, %d %d-byte blocks (%d chunks)\n",
447         (int)peek_le(s+4, 2), (int)peek_le(s+6, 2), (int)peek_le(s+16, 4),
448         (int)peek_le(s+12, 4), (int)peek_le(s+20, 4));
449 
450     // https://android.googlesource.com/platform/system/tools/mkbootimg/+/refs/heads/master/include/bootimg/bootimg.h
451   } else if (len>1632 && !smemcmp(s, "ANDROID!", 8)) {
452     xprintf("Android boot image v%d\n", (int)peek_le(s+40, 4));
453 
454     // https://source.android.com/devices/architecture/dto/partitions
455   } else if (len>32 && peek_be(s, 4) == 0xd7b7ab1e) {
456     xprintf("Android DTB/DTBO v%d, %d entries\n", (int)peek_be(s+28, 4),
457             (int)peek_be(s+16, 4));
458 
459     // frameworks/base/core/java/com/android/internal/util/BinaryXmlSerializer.java
460   } else if (len>4 && !smemcmp(s, "ABX", 3)) {
461     xprintf("Android Binary XML v%d\n", s[3]);
462 
463     // https://webassembly.github.io/spec/core/binary/modules.html#binary-module
464   } else if (len>8 && !smemcmp(s, "\0asm", 4)) {
465     xprintf("wasm binary module version %d\n", (int)peek_le(s+4, 4));
466 
467     // Text files, including shell scripts.
468   } else {
469     char *what = 0;
470     int i, bytes;
471 
472     // If shell script, report which interpreter
473     if (len>3 && strstart(&s, "#!")) {
474       // Whitespace is allowed between the #! and the interpreter
475       while (isspace(*s)) s++;
476       if (strstart(&s, "/usr/bin/env")) while (isspace(*s)) s++;
477       for (what = s; *s && !isspace(*s); s++);
478       strcpy(s, " script");
479 
480     // Distinguish ASCII text, UTF-8 text, or data
481     } else for (i = 0; i<len; ++i) {
482       if (!(isprint(s[i]) || isspace(s[i]))) {
483         unsigned wc;
484 
485         if ((bytes = utf8towc(&wc, s+i, len-i))>0 && wcwidth(wc)>=0) {
486           i += bytes-1;
487           if (!what) what = "UTF-8 text";
488         } else {
489           what = "data";
490           break;
491         }
492       }
493     }
494     xputs(what ? what : "ASCII text");
495   }
496 }
497 
file_main(void)498 void file_main(void)
499 {
500   char **arg;
501 
502   for (arg = toys.optargs; *arg; ++arg)
503     TT.max_name_len = maxof(strlen(*arg), TT.max_name_len);
504 
505   // Can't use loopfiles here because it doesn't call function when can't open
506   for (arg = toys.optargs; *arg; arg++) {
507     char *name = *arg, *what = "unknown";
508     struct stat sb;
509     int fd = !strcmp(name, "-");
510 
511     if (!FLAG(b))
512       xprintf("%s: %*s", name, (int)(TT.max_name_len - strlen(name)), "");
513 
514     sb.st_size = 0;
515     if (!fd && (FLAG(L) ? stat : lstat)(name, &sb)) {
516       xprintf("cannot open: %s\n", strerror(errno));
517 
518       continue;
519     }
520 
521     if (!fd && !FLAG(s) && (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode))) {
522       sprintf(what = toybuf, "%s special (%u/%u)",
523           S_ISBLK(sb.st_mode) ? "block" : "character",
524           dev_major(sb.st_rdev), dev_minor(sb.st_rdev));
525     } else if (fd || S_ISREG(sb.st_mode)) {
526       TT.len = sb.st_size;
527       // This test identifies an empty file we don't have permission to read
528       if (!fd && !sb.st_size) what = "empty";
529       else if ((fd = openro(name, O_RDONLY)) != -1) {
530         do_regular_file(fd, name);
531         if (fd) close(fd);
532 
533         continue;
534       }
535     } else if (S_ISFIFO(sb.st_mode)) what = "fifo";
536     else if (S_ISDIR(sb.st_mode)) what = "directory";
537     else if (S_ISSOCK(sb.st_mode)) what = "socket";
538     else if (S_ISLNK(sb.st_mode)) {
539       char *lnk = xreadlink(name);
540 
541       sprintf(what = toybuf, "%ssymbolic link to %s",
542           stat(name, &sb) ? "broken " : "", lnk);
543       free(lnk);
544     }
545     xputs(what);
546   }
547 }
548