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  * TODO: ar
8 
9 USE_FILE(NEWTOY(file, "<1", TOYFLAG_USR|TOYFLAG_BIN))
10 
11 config FILE
12   bool "file"
13   default n
14   help
15     usage: file [file...]
16 
17     Examine the given files and describe their content types.
18 */
19 
20 #define FOR_file
21 #include "toys.h"
22 
GLOBALS(int max_name_len;)23 GLOBALS(
24   int max_name_len;
25 )
26 
27 // We don't trust elf.h to be there, and two codepaths for 32/64 is awkward
28 // anyway, so calculate struct offsets manually. (It's a fixed ABI.)
29 static void do_elf_file(int fd)
30 {
31   int endian = toybuf[5], bits = toybuf[4], i, j;
32   int64_t (*elf_int)(void *ptr, unsigned size) = peek_le;
33   // Values from include/linux/elf-em.h (plus arch/*/include/asm/elf.h)
34   // Names are linux/arch/ directory name
35   struct {int val; char *name;} type[] = {{0x9026, "alpha"},
36     {40, "arm"}, {183, "arm"}, {0x18ad, "avr32"}, {106, "blackfin"},
37     {76, "cris"}, {0x5441, "frv"}, {46, "h8300"}, {50, "ia64"},//ia intel ftaghn
38     {88, "m32r"}, {4, "m68k"}, {0xbaab, "microblaze"}, {8, "mips"},
39     {10, "mips"}, {89, "mn10300"}, {15, "parisc"}, {22, "s390"},
40     {135, "score"}, {42, "sh"}, {2, "sparc"}, {18, "sparc"}, {43, "sparc"},
41     {187, "tile"}, {188, "tile"}, {191, "tile"}, {3, "x86"}, {6, "x86"},
42     {62, "x86"}, {94, "xtensa"}, {0xabc7, "xtensa"}};
43 
44   xprintf("ELF ");
45 
46   // "64-bit"
47   if (bits == 1) xprintf("32-bit ");
48   else if (bits == 2) xprintf("64-bit ");
49   else {
50     xprintf("(bad class %d) ", bits);
51     bits = 0;
52   }
53 
54   // e_machine, ala "x86", from big table above
55   j = elf_int(toybuf+18, 2);
56   for (i = 0; i<ARRAY_LEN(type); i++) if (j==type[i].val) break;
57   if (i<ARRAY_LEN(type)) xprintf("%s ", type[i].name);
58   else xprintf("(unknown arch %d) ", j);
59 
60   // "LSB"
61   if (endian == 1) xprintf("LSB ");
62   else if (endian == 2) {
63     xprintf("MSB ");
64     elf_int = peek_be;
65   } else {
66     xprintf("(bad endian %d)\n", endian);
67     endian = 0;
68   }
69 
70   // ", executable"
71   i = elf_int(toybuf+16, 2);
72   if (i == 1) xprintf("relocatable");
73   else if (i == 2) xprintf("executable");
74   else if (i == 3) xprintf("shared object");
75   else if (i == 4) xprintf("core dump");
76   else xprintf("(bad type %d)", i);
77 
78   bits--;
79   // If we know our bits and endianness and phentsize agrees show dynamic linker
80   if ((bits&1)==bits && endian &&
81       (i = elf_int(toybuf+42+12*bits, 2)) == 32+24*bits)
82   {
83     char *map, *phdr;
84     int phsize = i, phnum = elf_int(toybuf+44+12*bits, 2),
85         psz = sysconf(_SC_PAGE_SIZE), lib = 0;
86     off_t phoff = elf_int(toybuf+28+4*bits, 4+4*bits),
87           mapoff = phoff^(phoff&(psz-1));
88 
89     // map e_phentsize*e_phnum bytes at e_phoff
90     map = mmap(0, phsize*phnum, PROT_READ, MAP_SHARED, fd, mapoff);
91     if (map) {
92       // Find PT_INTERP entry. (Not: fields got reordered for 64 bit)
93       for (i = 0; i<phnum; i++) {
94         long long dlpos, dllen;
95 
96         // skip non-PT_INTERP entries
97         j = elf_int(phdr = map+(phoff-mapoff)+i*phsize, 4);
98         if (j==2) lib++;
99         if (j!=3) continue;
100 
101         // Read p_offset and p_filesz
102         j = bits+1;
103         dlpos = elf_int(phdr+4*j, 4*j);
104         dllen = elf_int(phdr+16*j, 4*j);
105         if (dllen<0 || dllen>sizeof(toybuf)-128
106             || dlpos!=lseek(fd, dlpos, SEEK_SET)
107             || dllen!=readall(fd, toybuf+128, dllen)) break;
108         printf(", dynamic (%.*s)", (int)dllen, toybuf+128);
109       }
110       if (!lib) printf(", static");
111       else printf(", needs %d lib%s", lib, lib>1 ? "s" : "");
112       munmap(map, phsize*phnum);
113     }
114   }
115 
116   // TODO: we'd need to actually parse the ELF file to report the rest...
117   // ", dynamically linked"
118   // " (uses shared libs)"
119   // ", for Linux 2.6.24"
120   // ", BuildID[sha1]=SHA"
121   // ", stripped"
122   xputc('\n');
123 }
124 
do_regular_file(int fd,char * name)125 static void do_regular_file(int fd, char *name)
126 {
127   char *s;
128   int len = read(fd, s = toybuf, sizeof(toybuf)-256);
129 
130   if (len<0) perror_msg("%s", name);
131 
132   if (len>40 && strstart(&s, "\177ELF")) do_elf_file(fd);
133   else if (len>28 && strstart(&s, "\x89PNG\x0d\x0a\x1a\x0a")) {
134     // PNG is big-endian: https://www.w3.org/TR/PNG/#7Integers-and-byte-order
135     int chunk_length = peek_be(s, 4);
136 
137     xprintf("PNG image data");
138 
139     // The IHDR chunk comes first: https://www.w3.org/TR/PNG/#11IHDR
140     s += 4;
141     if (chunk_length == 13 && strstart(&s, "IHDR")) {
142       // https://www.w3.org/TR/PNG/#6Colour-values
143       char *c = 0, *colors[] = {"grayscale", 0, "color RGB", "indexed color",
144                                 "grayscale with alpha", 0, "color RGBA"};
145 
146       if (s[9]<ARRAY_LEN(colors)) c = colors[s[9]];
147       if (!c) c = "unknown";
148 
149       xprintf(", %d x %d, %d-bit/%s, %sinterlaced", (int)peek_be(s, 4),
150         (int)peek_be(s+4, 4), s[8], c, s[12] ? "" : "non-");
151     }
152 
153     xputc('\n');
154 
155   // https://www.w3.org/Graphics/GIF/spec-gif89a.txt
156   } else if (len>16 && (strstart(&s, "GIF87a") || strstart(&s, "GIF89a")))
157     xprintf("GIF image data, %d x %d\n",
158       (int)peek_le(s, 2), (int)peek_le(s+8, 2));
159 
160   // TODO: parsing JPEG for width/height is harder than GIF or PNG.
161   else if (len>32 && memcmp(toybuf, "\xff\xd8", 2) == 0)
162     xprintf("JPEG image data\n");
163 
164   // https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html
165   else if (len>8 && strstart(&s, "\xca\xfe\xba\xbe"))
166     xprintf("Java class file, version %d.%d\n",
167       (int)peek_be(s+6, 2), (int)peek_be(s, 2));
168 
169     // TODO: cpio archive.
170     // TODO: tar archive.
171     // TODO: zip/jar/apk archive.
172   else {
173     char *what = 0;
174     int i, bytes;
175 
176     // If shell script, report which interpreter
177     if (len>3 && strstart(&s, "#!")) {
178       for (what = s; (s-toybuf)<len && !isspace(*s); s++);
179       strcpy(s, " script");
180 
181     // Distinguish ASCII text, UTF-8 text, or data
182     } else for (i = 0; i<len; ++i) {
183       if (!(isprint(toybuf[i]) || isspace(toybuf[i]))) {
184         wchar_t wc;
185         if ((bytes = mbrtowc(&wc, s+i, len-i, 0))>0 && wcwidth(wc)>=0) {
186           i += bytes-1;
187           if (!what) what = "UTF-8 text";
188         } else {
189           what = "data";
190           break;
191         }
192       }
193     }
194     xputs(what ? what : "ASCII text");
195   }
196 }
197 
do_file(int fd,char * name)198 static void do_file(int fd, char *name)
199 {
200   struct stat sb;
201   char *what = "unknown";
202 
203   xprintf("%s: %*s", name, (int)(TT.max_name_len - strlen(name)), "");
204 
205   if (!fstat(fd, &sb)) what = "cannot open";
206   if (S_ISREG(sb.st_mode)) {
207     if (sb.st_size == 0) what = "empty";
208     else {
209       do_regular_file(fd, name);
210       return;
211     }
212   } else if (S_ISBLK(sb.st_mode)) what = "block special";
213   else if (S_ISCHR(sb.st_mode)) what = "character special";
214   else if (S_ISDIR(sb.st_mode)) what = "directory";
215   else if (S_ISFIFO(sb.st_mode)) what = "fifo";
216   else if (S_ISSOCK(sb.st_mode)) what = "socket";
217   else if (S_ISLNK(sb.st_mode)) what = "symbolic link";
218   xputs(what);
219 }
220 
file_main(void)221 void file_main(void)
222 {
223   char **name;
224 
225   for (name = toys.optargs; *name; ++name) {
226     int name_len = strlen(*name);
227 
228     if (name_len > TT.max_name_len) TT.max_name_len = name_len;
229   }
230 
231   loopfiles(toys.optargs, do_file);
232 }
233