OSDN Git Service

Don't try to guess the build id type in file(1).
[android-x86/external-toybox.git] / toys / posix / file.c
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 y
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
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, struct stat *sb)
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 (sometimes before 32/64 bit merges)
35   struct {int val; char *name;} type[] = {{0x9026, "alpha"}, {93, "arc"},
36     {195, "arcv2"}, {40, "arm"}, {183, "arm64"}, {0x18ad, "avr32"},
37     {106, "blackfin"}, {140, "c6x"}, {23, "cell"}, {76, "cris"},
38     {0x5441, "frv"}, {46, "h8300"}, {164, "hexagon"}, {50, "ia64"},
39     {88, "m32r"}, {0x9041, "m32r"}, {4, "m68k"}, {174, "metag"},
40     {0xbaab, "microblaze"}, {8, "mips"}, {10, "mips-old"}, {89, "mn10300"},
41     {0xbeef, "mn10300-old"}, {113, "nios2"}, {92, "openrisc"},
42     {0x8472, "openrisc-old"}, {15, "parisc"}, {20, "ppc"}, {21, "ppc64"},
43     {22, "s390"}, {0xa390, "s390-old"}, {135, "score"}, {42, "sh"},
44     {2, "sparc"}, {18, "sparc8+"}, {43, "sparc9"}, {188, "tile"},
45     {191, "tilegx"}, {3, "386"}, {6, "486"}, {62, "x86-64"}, {94, "xtensa"},
46     {0xabc7, "xtensa-old"}
47   };
48   int dynamic = 0;
49   int stripped = 1;
50   char *map;
51   off_t phoff, shoff;
52   int phsize, phnum, shsize, shnum;
53
54   printf("ELF ");
55
56   // executable (ELF says this is short but reality says byte, not MSB swapped)
57   i = toybuf[16];
58   if (i == 1) printf("relocatable");
59   else if (i == 2) printf("executable");
60   else if (i == 3) printf("shared object");
61   else if (i == 4) printf("core dump");
62   else printf("(bad type %d)", i);
63   printf(", ");
64
65   // "64-bit"
66   if (bits == 1) printf("32-bit ");
67   else if (bits == 2) printf("64-bit ");
68   else {
69     printf("(bad class %d) ", bits);
70     bits = 0;
71   }
72
73   // "LSB"
74   if (endian == 1) printf("LSB ");
75   else if (endian == 2) {
76     printf("MSB ");
77     elf_int = peek_be;
78   } else {
79     printf("(bad endian %d) \n", endian);
80     endian = 0;
81   }
82
83   // e_machine, ala "x86", from big table above
84   j = elf_int(toybuf+18, 2);
85   for (i = 0; i<ARRAY_LEN(type); i++) if (j==type[i].val) break;
86   if (i<ARRAY_LEN(type)) printf("%s", type[i].name);
87   else printf("(unknown arch %d)", j);
88
89   bits--;
90   // If what we've seen so far doesn't seem consistent, bail.
91   if (!((bits&1)==bits && endian &&
92        (i = elf_int(toybuf+42+12*bits, 2)) == 32+24*bits)) {
93     printf(", corrupt?\n");
94     return;
95   }
96
97   // Stash what we need from the header; it's okay to reuse toybuf after this.
98   phsize = i;
99   phnum = elf_int(toybuf+44+12*bits, 2);
100   phoff = elf_int(toybuf+28+4*bits, 4+4*bits);
101   shsize = elf_int(toybuf+46+12*bits, 2);
102   shnum = elf_int(toybuf+48+12*bits, 2);
103   shoff = elf_int(toybuf+32+8*bits, 4+4*bits);
104
105   map = mmap(0, sb->st_size, PROT_READ, MAP_SHARED, fd, 0);
106   if (!map) perror_exit("mmap");
107
108   // We need to read the phdrs for dynamic vs static and any notes.
109   // (Note: fields got reordered for 64 bit)
110   for (i = 0; i<phnum; i++) {
111     char *phdr = map+phoff+i*phsize;
112     int p_type = elf_int(phdr, 4);
113     long long p_offset, p_filesz;
114
115     if (p_type==2 /*PT_DYNAMIC*/) dynamic = 1;
116     if (p_type!=3 /*PT_INTERP*/ && p_type!=4 /*PT_NOTE*/) continue;
117
118     j = bits+1;
119     p_offset = elf_int(phdr+4*j, 4*j);
120     p_filesz = elf_int(phdr+16*j, 4*j);
121
122     if (p_type==3 /*PT_INTERP*/)
123       printf(", dynamic (%.*s)", (int)p_filesz, map+p_offset);
124     else {
125       char *note = map+p_offset;
126
127       // A PT_NOTE phdr is a sequence of entries, each consisting of an
128       // ndhr followed by n_namesz+n_descsz bytes of data (each of those
129       // rounded up to the next 4 bytes, without this being reflected in
130       // the header byte counts themselves).
131       while (p_filesz >= 3*4) { // Don't try to read a truncated entry.
132         int n_namesz = elf_int(note, 4);
133         int n_descsz = elf_int(note+4, 4);
134         int n_type = elf_int(note+8, 4);
135         int notesz = 3*4 + ((n_namesz+3)&~3) + ((n_descsz+3)&~3);
136
137         if (n_namesz==4 && !memcmp(note+12, "GNU", 4)) {
138           if (n_type == 3 /*NT_GNU_BUILD_ID*/) {
139             printf(", BuildID=");
140             for (j = 0; j < n_descsz; ++j) printf("%02x", note[16 + j]);
141           }
142         } else if (n_namesz==8 && !memcmp(note+12, "Android", 8)) {
143           if (n_type==1) printf(", for Android %d", (int)elf_int(note+20, 4));
144         }
145
146         note += notesz;
147         p_filesz -= notesz;
148       }
149     }
150   }
151   if (!dynamic) printf(", static");
152
153   // We need to read the shdrs for stripped/unstripped.
154   // (Note: fields got reordered for 64 bit)
155   for (i = 0; i<shnum; i++) {
156     char *shdr = map+shoff+i*shsize;
157     int sh_type = elf_int(shdr+4, 4);
158
159     if (sh_type == 2 /*SHT_SYMTAB*/) {
160       stripped = 0;
161       break;
162     }
163   }
164   printf(", %sstripped", stripped ? "" : "not ");
165   xputc('\n');
166
167   munmap(map, sb->st_size);
168 }
169
170 static void do_regular_file(int fd, char *name, struct stat *sb)
171 {
172   char *s;
173   int len = read(fd, s = toybuf, sizeof(toybuf)-256);
174   int magic;
175
176   if (len<0) perror_msg("%s", name);
177
178   if (len>40 && strstart(&s, "\177ELF")) do_elf_file(fd, sb);
179   else if (len>28 && strstart(&s, "\x89PNG\x0d\x0a\x1a\x0a")) {
180     // PNG is big-endian: https://www.w3.org/TR/PNG/#7Integers-and-byte-order
181     int chunk_length = peek_be(s, 4);
182
183     xprintf("PNG image data");
184
185     // The IHDR chunk comes first: https://www.w3.org/TR/PNG/#11IHDR
186     s += 4;
187     if (chunk_length == 13 && strstart(&s, "IHDR")) {
188       // https://www.w3.org/TR/PNG/#6Colour-values
189       char *c = 0, *colors[] = {"grayscale", 0, "color RGB", "indexed color",
190                                 "grayscale with alpha", 0, "color RGBA"};
191
192       if (s[9]<ARRAY_LEN(colors)) c = colors[s[9]];
193       if (!c) c = "unknown";
194
195       xprintf(", %d x %d, %d-bit/%s, %sinterlaced", (int)peek_be(s, 4),
196         (int)peek_be(s+4, 4), s[8], c, s[12] ? "" : "non-");
197     }
198
199     xputc('\n');
200
201   // https://www.w3.org/Graphics/GIF/spec-gif89a.txt
202   } else if (len>16 && (strstart(&s, "GIF87a") || strstart(&s, "GIF89a")))
203     xprintf("GIF image data, %d x %d\n",
204       (int)peek_le(s, 2), (int)peek_le(s+8, 2));
205
206   // TODO: parsing JPEG for width/height is harder than GIF or PNG.
207   else if (len>32 && memcmp(toybuf, "\xff\xd8", 2) == 0)
208     xprintf("JPEG image data\n");
209
210   // https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html
211   else if (len>8 && strstart(&s, "\xca\xfe\xba\xbe"))
212     xprintf("Java class file, version %d.%d\n",
213       (int)peek_be(s+2, 2), (int)peek_be(s, 2));
214
215   // https://people.freebsd.org/~kientzle/libarchive/man/cpio.5.txt
216   // the lengths for cpio are size of header + 9 bytes, since any valid
217   // cpio archive ends with a record for "TARGET!!!"
218   else if (len>85 && strstart(&s, "07070")) {
219     char *cpioformat = "unknown type";
220     if (toybuf[5] == '7') cpioformat = "pre-SVR4 or odc";
221     else if (toybuf[5] == '1') cpioformat = "SVR4 with no CRC";
222     else if (toybuf[5] == '2') cpioformat = "SVR4 with CRC";
223     xprintf("ASCII cpio archive (%s)\n", cpioformat);
224   }
225   else if (len>33 && (magic=peek(&s,2), magic==0143561 || magic==070707)) {
226     if (magic == 0143561) printf("byte-swapped ");
227     xprintf("cpio archive\n");
228   }
229   // tar archive (ustar/pax or gnu)
230   else if (len>500 && !strncmp(s+257, "ustar", 5)) {
231     xprintf("POSIX tar archive%s\n", strncmp(s+262,"  ",2)?"":" (GNU)");
232   }
233   // zip/jar/apk archive, ODF/OOXML document, or such
234   else if (len>5 && strstart(&s, "PK\03\04")) {
235     int ver = (int)(char)(toybuf[4]);
236     xprintf("Zip archive data");
237     if (ver)
238       xprintf(", requires at least v%d.%d to extract", ver/10, ver%10);
239     xputc('\n');
240   }
241   else {
242     char *what = 0;
243     int i, bytes;
244
245     // If shell script, report which interpreter
246     if (len>3 && strstart(&s, "#!")) {
247       // Whitespace is allowed between the #! and the interpreter
248       while (isspace(*s)) s++;
249       if (strstart(&s, "/usr/bin/env")) while (isspace(*s)) s++;
250       for (what = s; (s-toybuf)<len && !isspace(*s); s++);
251       strcpy(s, " script");
252
253     // Distinguish ASCII text, UTF-8 text, or data
254     } else for (i = 0; i<len; ++i) {
255       if (!(isprint(toybuf[i]) || isspace(toybuf[i]))) {
256         wchar_t wc;
257         if ((bytes = mbrtowc(&wc, s+i, len-i, 0))>0 && wcwidth(wc)>=0) {
258           i += bytes-1;
259           if (!what) what = "UTF-8 text";
260         } else {
261           what = "data";
262           break;
263         }
264       }
265     }
266     xputs(what ? what : "ASCII text");
267   }
268 }
269
270 void file_main(void)
271 {
272   char **arg;
273
274   for (arg = toys.optargs; *arg; ++arg) {
275     int name_len = strlen(*arg);
276
277     if (name_len > TT.max_name_len) TT.max_name_len = name_len;
278   }
279
280   // Can't use loopfiles here because it doesn't call function when can't open
281   for (arg = toys.optargs; *arg; arg++) {
282     struct stat sb;
283     char *name = *arg, *what = "cannot open";
284
285     xprintf("%s: %*s", name, (int)(TT.max_name_len - strlen(name)), "");
286
287     if (!lstat(name, &sb)) {
288       if (S_ISFIFO(sb.st_mode)) what = "fifo";
289       else if (S_ISREG(sb.st_mode)) {
290         int fd = !strcmp(name, "-") ? 0 : open(name, O_RDONLY);
291
292         if (fd!=-1) {
293           if (!sb.st_size) what = "empty";
294           else do_regular_file(fd, name, &sb);
295           if (fd) close(fd);
296           if (sb.st_size) continue;
297         }
298       } else if (S_ISBLK(sb.st_mode)) what = "block special";
299       else if (S_ISCHR(sb.st_mode)) what = "character special";
300       else if (S_ISDIR(sb.st_mode)) what = "directory";
301       else if (S_ISSOCK(sb.st_mode)) what = "socket";
302       else if (S_ISLNK(sb.st_mode)) what = "symbolic link";
303       else what = "unknown";
304     }
305
306     xputs(what);
307   }
308 }