1 /* readelf.c - display information about ELF files.
2 *
3 * Copyright 2019 The Android Open Source Project
4 *
5 * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/nm.html
6
7 USE_READELF(NEWTOY(readelf, "<1(dyn-syms)Aadehlnp:SsWx:", TOYFLAG_USR|TOYFLAG_BIN))
8
9 config READELF
10 bool "readelf"
11 default y
12 help
13 usage: readelf [-AadehlnSs] [-p SECTION] [-x SECTION] [file...]
14
15 Displays information about ELF files.
16
17 -A Show architecture-specific info
18 -a Equivalent to -AdhlnSs
19 -d Show dynamic section
20 -e Headers (equivalent to -hlS)
21 -h Show ELF header
22 -l Show program headers
23 -n Show notes
24 -p S Dump strings found in named/numbered section
25 -S Show section headers
26 -s Show symbol tables (.dynsym and .symtab)
27 -x S Hex dump of named/numbered section
28
29 --dyn-syms Show just .dynsym symbol table
30 */
31
32 #define FOR_readelf
33 #include "toys.h"
34
35 GLOBALS(
36 char *x, *p;
37
38 char *elf, *shstrtab, *f;
39 unsigned long long shoff, phoff, size, shstrtabsz;
40 int bits, endian, shnum, shentsize, phentsize;
41 )
42
43 // Section header.
44 struct sh {
45 unsigned type, link, info;
46 unsigned long long flags, addr, offset, size, addralign, entsize;
47 char *name;
48 };
49
50 // Program header.
51 struct ph {
52 unsigned type, flags;
53 unsigned long long offset, vaddr, paddr, filesz, memsz, align;
54 };
55
elf_get(char ** p,int len)56 static long long elf_get(char **p, int len)
57 {
58 long long result;
59
60 if (*p+len-TT.elf>TT.size)
61 perror_exit("Access off end: %td[%d] of %lld\n", *p-TT.elf, len, TT.size);
62
63 result = ((TT.endian == 2) ? peek_be : peek_le)(*p, len);
64 *p += len;
65 return result;
66 }
67
elf_long(char ** p)68 static unsigned long long elf_long(char **p)
69 {
70 return elf_get(p, 4*(TT.bits+1));
71 }
72
elf_int(char ** p)73 static unsigned elf_int(char **p)
74 {
75 return elf_get(p, 4);
76 }
77
elf_short(char ** p)78 static unsigned short elf_short(char **p)
79 {
80 return elf_get(p, 2);
81 }
82
fits(char * what,int n,unsigned long long off,unsigned long long size)83 static int fits(char *what, int n, unsigned long long off, unsigned long long size)
84 {
85 if (off > TT.size || size > TT.size || off > TT.size-size) {
86 if (n == -1) *toybuf = 0;
87 else snprintf(toybuf, sizeof(toybuf), " %d", n);
88 printf("%s%s's offset %llu + size %llu > file size %llu\n",
89 what, toybuf, off, size, TT.size);
90 return 0;
91 }
92 return 1;
93 }
94
get_sh(unsigned i,struct sh * s)95 static int get_sh(unsigned i, struct sh *s)
96 {
97 char *shdr = TT.elf+TT.shoff+i*TT.shentsize;
98 unsigned name_offset;
99
100 if (i >= TT.shnum || shdr > TT.elf+TT.size-TT.shentsize) {
101 printf("No shdr %d\n", i);
102 return 0;
103 }
104
105 name_offset = elf_int(&shdr);
106 s->type = elf_int(&shdr);
107 s->flags = elf_long(&shdr);
108 s->addr = elf_long(&shdr);
109 s->offset = elf_long(&shdr);
110 s->size = elf_long(&shdr);
111 s->link = elf_int(&shdr);
112 s->info = elf_int(&shdr);
113 s->addralign = elf_long(&shdr);
114 s->entsize = elf_long(&shdr);
115
116 if (s->type != 8 && !fits("section header", i, s->offset, s->size)) return 0;
117
118 if (!TT.shstrtab) s->name = "?";
119 else {
120 s->name = TT.shstrtab + name_offset;
121 if (name_offset > TT.shstrtabsz || s->name >= TT.elf+TT.size) {
122 printf("Bad name for sh %d\n", i);
123 return 0;
124 }
125 }
126
127 return 1;
128 }
129
find_section(char * spec,struct sh * s)130 static int find_section(char *spec, struct sh *s)
131 {
132 char *end;
133 unsigned i;
134
135 if (!spec) return 0;
136
137 // Valid section number?
138 i = estrtol(spec, &end, 0);
139 if (!errno && !*end && i<TT.shnum) return get_sh(i, s);
140
141 // Search the section names.
142 for (i=0; i<TT.shnum; i++)
143 if (get_sh(i, s) && !strcmp(s->name, spec)) return 1;
144
145 error_msg("%s: no section '%s", TT.f, spec);
146 return 0;
147 }
148
get_ph(int i,struct ph * ph)149 static int get_ph(int i, struct ph *ph)
150 {
151 char *phdr = TT.elf+TT.phoff+i*TT.phentsize;
152
153 if (phdr > TT.elf+TT.size-TT.phentsize) {
154 printf("Bad phdr %d\n", i);
155 return 0;
156 }
157
158 // Elf64_Phdr reordered fields.
159 ph->type = elf_int(&phdr);
160 if (TT.bits) {
161 ph->flags = elf_int(&phdr);
162 ph->offset = elf_long(&phdr);
163 ph->vaddr = elf_long(&phdr);
164 ph->paddr = elf_long(&phdr);
165 ph->filesz = elf_long(&phdr);
166 ph->memsz = elf_long(&phdr);
167 ph->align = elf_long(&phdr);
168 } else {
169 ph->offset = elf_int(&phdr);
170 ph->vaddr = elf_int(&phdr);
171 ph->paddr = elf_int(&phdr);
172 ph->filesz = elf_int(&phdr);
173 ph->memsz = elf_int(&phdr);
174 ph->flags = elf_int(&phdr);
175 ph->align = elf_int(&phdr);
176 }
177
178 if (!fits("program header", i, ph->offset, ph->filesz)) return 0;
179 return 1;
180 }
181
182 #define MAP(...) __VA_ARGS__
183 #define DECODER(name, values) \
184 static char *name(int type) { \
185 static char unknown[20]; \
186 struct {int v; char *s;} a[] = values; \
187 int i; \
188 \
189 for (i=0; i<ARRAY_LEN(a); i++) if (type==a[i].v) return a[i].s; \
190 sprintf(unknown, "0x%x", type); \
191 return unknown; \
192 }
193
194 DECODER(dt_type, MAP({{0,"x(NULL)"},{1,"N(NEEDED)"},{2,"b(PLTRELSZ)"},
195 {3,"x(PLTGOT)"},{4,"x(HASH)"},{5,"x(STRTAB)"},{6,"x(SYMTAB)"},{7,"x(RELA)"},
196 {8,"b(RELASZ)"},{9,"b(RELAENT)"},{10,"b(STRSZ)"},{11,"b(SYMENT)"},
197 {12,"x(INIT)"},{13,"x(FINI)"},{14,"S(SONAME)"},{15,"R(RPATH)"},
198 {16,"x(SYMBOLIC)"},{17,"x(REL)"},{18,"b(RELSZ)"},{19,"b(RELENT)"},
199 {20,"P(PLTREL)"},{21,"x(DEBUG)"},{22,"x(TEXTREL)"},{23,"x(JMPREL)"},
200 {24,"d(BIND_NOW)"},{25,"x(INIT_ARRAY)"},{26,"x(FINI_ARRAY)"},
201 {27,"b(INIT_ARRAYSZ)"},{28,"b(FINI_ARRAYSZ)"},{29,"R(RUNPATH)"},
202 {30,"f(FLAGS)"},{32,"x(PREINIT_ARRAY)"},{33,"x(PREINIT_ARRAYSZ)"},
203 {35,"b(RELRSZ)"},{36,"x(RELR)"},{37,"b(RELRENT)"},
204 {0x6000000f,"x(ANDROID_REL)"},{0x60000010,"b(ANDROID_RELSZ)"},
205 {0x60000011,"x(ANDROID_RELA)"},{0x60000012,"b(ANDROID_RELASZ)"},
206 {0x6fffe000,"x(ANDROID_RELR)"},{0x6fffe001,"b(ANDROID_RELRSZ)"},
207 {0x6fffe003,"x(ANDROID_RELRENT)"},{0x6ffffef5,"x(GNU_HASH)"},
208 {0x6ffffef6,"x(TLSDESC_PLT)"},{0x6ffffef7,"x(TLSDESC_GOT)"},
209 {0x6ffffff0,"x(VERSYM)"},{0x6ffffff9,"d(RELACOUNT)"},
210 {0x6ffffffa,"d(RELCOUNT)"},{0x6ffffffb,"F(FLAGS_1)"},
211 {0x6ffffffc," (VERDEF)"},{0x6ffffffd,"d(VERDEFNUM)"},
212 {0x6ffffffe,"x(VERNEED)"},{0x6fffffff,"d(VERNEEDNUM)"}}))
213
214 DECODER(et_type, MAP({{0,"NONE (None)"},{1,"REL (Relocatable file)"},
215 {2,"EXEC (Executable file)"},{3,"DYN (Shared object file)"},
216 {4,"CORE (Core file)"}}))
217
218 DECODER(nt_type_core, MAP({{1,"NT_PRSTATUS"},{2,"NT_FPREGSET"},
219 {3,"NT_PRPSINFO"},{5,"NT_PLATFORM"},{6,"NT_AUXV"},
220 {0x46494c45,"NT_FILE"},{0x53494749,"NT_SIGINFO"}}))
221
222 DECODER(nt_type_linux, MAP({{0x200,"NT_386_TLS"},{0x202, "NT_X86_XSTATE"},
223 {0x400,"NT_ARM_VFP"},{0x401,"NT_ARM_TLS"},{0x405,"NT_ARM_SVE"}}))
224
225 DECODER(os_abi, MAP({{0,"UNIX - System V"}}))
226
227 DECODER(ph_type, MAP({{0,"NULL"},{1,"LOAD"},{2,"DYNAMIC"},{3,"INTERP"},
228 {4,"NOTE"},{5,"SHLIB"},{6,"PHDR"},{7,"TLS"},{0x6474e550,"GNU_EH_FRAME"},
229 {0x6474e551,"GNU_STACK"},{0x6474e552,"GNU_RELRO"},{0x70000001,"EXIDX"}}))
230
231 DECODER(sh_type, MAP({{0,"NULL"},{1,"PROGBITS"},{2,"SYMTAB"},{3,"STRTAB"},
232 {4,"RELA"},{5,"HASH"},{6,"DYNAMIC"},{7,"NOTE"},{8,"NOBITS"},{9,"REL"},
233 {10,"SHLIB"},{11,"DYNSYM"},{14,"INIT_ARRAY"},{15,"FINI_ARRAY"},
234 {16,"PREINIT_ARRAY"},{17,"GROUP"},{18,"SYMTAB_SHNDX"},{19,"RELR"},
235 {0x60000001,"ANDROID_REL"},{0x60000002,"ANDROID_RELA"},
236 {0x6fffff00,"ANDROID_RELR"},{0x6ffffff6,"GNU_HASH"},
237 {0x6ffffffd,"VERDEF"},{0x6ffffffe,"VERNEED"},
238 {0x6fffffff,"VERSYM"},{0x70000001,"ARM_EXIDX"},
239 {0x70000003,"ATTRIBUTES"}}))
240
241 DECODER(stb_type, MAP({{0,"LOCAL"},{1,"GLOBAL"},{2,"WEAK"}}))
242
243 DECODER(stt_type, MAP({{0,"NOTYPE"},{1,"OBJECT"},{2,"FUNC"},{3,"SECTION"},
244 {4,"FILE"},{5,"COMMON"},{6,"TLS"},{10,"GNU_IFUNC"}}))
245
246 DECODER(stv_type, MAP({{0,"DEFAULT"},{1,"INTERNAL"},{2,"HIDDEN"},
247 {3,"PROTECTED"}}))
248
249 DECODER(riscv_attr_tag, MAP({{4,"stack_align"},{5,"arch"},
250 {6,"unaligned_access"},{8,"priv_spec"},{10,"priv_spec_minor"},
251 {12,"priv_spec_revision"},{14,"atomic_abi"},{16,"x3_reg_usage"}}))
252
show_symbols(struct sh * table,struct sh * strtab)253 static void show_symbols(struct sh *table, struct sh *strtab)
254 {
255 char *symtab = TT.elf+table->offset, *ndx;
256 int numsym = table->size/(TT.bits ? 24 : 16), i;
257
258 if (!numsym) return;
259
260 xputc('\n');
261 printf("Symbol table '%s' contains %d entries:\n"
262 " Num: %*s Size Type Bind Vis Ndx Name\n",
263 table->name, numsym, 5+8*TT.bits, "Value");
264 for (i=0; i<numsym; i++) {
265 unsigned st_name = elf_int(&symtab), st_value, st_shndx, st_info, st_other;
266 unsigned long st_size;
267 char *name, buf[16];
268
269 // The various fields were moved around for 64-bit.
270 if (TT.bits) {
271 st_info = *symtab++;
272 st_other = *symtab++;
273 st_shndx = elf_short(&symtab);
274 st_value = elf_long(&symtab);
275 st_size = elf_long(&symtab);
276 } else {
277 st_value = elf_int(&symtab);
278 st_size = elf_int(&symtab);
279 st_info = *symtab++;
280 st_other = *symtab++;
281 st_shndx = elf_short(&symtab);
282 }
283
284 // TODO: why do we trust name to be null terminated?
285 name = TT.elf + strtab->offset + st_name;
286 if (name >= TT.elf+TT.size) name = "???";
287
288 if (!st_shndx) ndx = "UND";
289 else if (st_shndx==0xfff1) ndx = "ABS";
290 else sprintf(ndx = buf, "%d", st_shndx);
291
292 // TODO: look up and show any symbol versions with @ or @@.
293
294 printf("%6d: %0*x %5lu %-7s %-6s %-9s%3s %s\n", i, 8*(TT.bits+1),
295 st_value, st_size, stt_type(st_info & 0xf), stb_type(st_info >> 4),
296 stv_type(st_other & 3), ndx, name);
297 }
298 }
299
notematch(int namesz,char ** p,char * expected)300 static int notematch(int namesz, char **p, char *expected)
301 {
302 if (namesz!=strlen(expected)+1 || strcmp(*p, expected)) return 0;
303 *p += namesz;
304
305 return 1;
306 }
307
uleb(char ** ptr,char * end)308 static unsigned long long uleb(char **ptr, char *end)
309 {
310 unsigned long long result = 0;
311 int shift = 0;
312 unsigned char b;
313
314 do {
315 if (*ptr >= end) error_exit("EOF in uleb128");
316 b = **ptr;
317 *ptr = *ptr + 1;
318 result |= (b & 0x7f) << shift;
319 shift += 7;
320 if (shift > 56) error_exit("uleb128 too long");
321 } while ((b & 0x80));
322 return result;
323 }
324
show_attributes(unsigned long offset,unsigned long size)325 static void show_attributes(unsigned long offset, unsigned long size)
326 {
327 char *attr = TT.elf + offset, *end = TT.elf + offset + size;
328 unsigned long long tag;
329 unsigned len;
330
331 // Attributes sections start with an 'A'...
332 if (offset == size || *attr++ != 'A')
333 return error_msg("%s: bad attributes @%lu", TT.f, offset);
334
335 // ...followed by vendor-specific subsections.
336 // TODO: there's a loop implied there, but i've never seen >1 subsection.
337
338 // A subsection starts with a uint32 length and ASCII vendor name.
339 len = elf_int(&attr);
340 if (!memchr(attr, 0, 32)) return error_msg("%s: bad vendor name", TT.f);
341 printf("\nAttribute Section: %s\n", attr);
342 attr += strlen(attr) + 1;
343
344 // ...followed by one or more sub-subsections.
345 // TODO: there's a loop implied there, but i've never seen >1 sub-subsection.
346 // A sub-subsection starts with a uleb128 tag and uint32 length.
347 tag = uleb(&attr, end);
348 len = elf_int(&attr);
349 if (tag == 1) {
350 printf("File Attributes\n");
351
352 // ...followed by actual attribute tag/value pairs.
353 while (attr < end) {
354 tag = uleb(&attr, end);
355
356 // TODO: arm tags don't seem to follow any pattern?
357 printf(" Tag_RISCV_%s: ", riscv_attr_tag(tag));
358 // Even riscv tags have uleb128 values, odd ones strings.
359 if (!(tag & 1)) printf("%lld\n", uleb(&attr, end));
360 else {
361 printf("%s\n", attr);
362 attr += strlen(attr) + 1;
363 }
364 }
365 } else {
366 // Do other tags exist?
367 error_msg("%s: unknown attributes tag=%llx (size=%u)\n", TT.f, tag, len);
368 }
369 }
370
show_notes(unsigned long offset,unsigned long size)371 static void show_notes(unsigned long offset, unsigned long size)
372 {
373 char *note = TT.elf + offset, *end = TT.elf + offset + size;
374
375 if (!fits("note", -1, offset, size)) return;
376
377 printf(" %-20s%11s\tDescription\n", "Owner", "Data size");
378 while (note < end) {
379 char *p = note, *desc;
380 unsigned namesz=elf_int(&p),descsz=elf_int(&p),type=elf_int(&p),j=0;
381
382 if (namesz > size || descsz > size)
383 return error_msg("%s: bad note @%lu", TT.f, offset);
384 printf(" %-20.*s 0x%08x\t", namesz, p, descsz);
385 if (notematch(namesz, &p, "GNU")) {
386 if (type == 1) {
387 printf("NT_GNU_ABI_TAG\tOS: %s, ABI: %u.%u.%u",
388 !elf_int(&p)?"Linux":"?", elf_int(&p), elf_int(&p), elf_int(&p)), j=1;
389 } else if (type == 3) {
390 printf("NT_GNU_BUILD_ID\t");
391 for (;j<descsz;j++) printf("%02x", *p++);
392 } else if (type == 4) {
393 printf("NT_GNU_GOLD_VERSION\t%.*s", descsz, p), j=1;
394 } else if (type == 5) {
395 printf("NT_GNU_PROPERTY_TYPE_0\n Properties:");
396 while (descsz - j > 0) {
397 int pr_type = elf_int(&p);
398 int pr_size = elf_int(&p), k, pr_data;
399
400 j += 8;
401 if (p > end) return error_msg("%s: bad property @%lu", TT.f, offset);
402 if (pr_size != 4) {
403 // Just hex dump anything we aren't familiar with.
404 for (k=0;k<pr_size;k++) printf("%02x", *p++);
405 xputc('\n');
406 j += pr_size;
407 } else {
408 pr_data = elf_int(&p);
409 elf_int(&p); // Skip padding.
410 j += 8;
411 if (pr_type == 0xc0000000) {
412 printf("\tarm64 features:");
413 if (pr_data & 1) printf(" bti");
414 if (pr_data & 2) printf(" pac");
415 xputc('\n');
416 } else if (pr_type == 0xc0000002) {
417 printf("\tx86 feature:");
418 if (pr_data & 1) printf(" ibt");
419 if (pr_data & 2) printf(" shstk");
420 xputc('\n');
421 } else if (pr_type == 0xc0008002) {
422 printf("\tx86 isa needed: x86-64v%d", ffs(pr_data));
423 } else {
424 printf("\tother (%#x): %#x", pr_type, pr_data);
425 }
426 }
427 }
428 } else p -= 4;
429 } else if (notematch(namesz, &p, "Android")) {
430 if (type == 1) {
431 printf("NT_VERSION\tAPI level %u", elf_int(&p)), j=1;
432 if (descsz>=132) printf(", NDK %.64s (%.64s)", p, p+64);
433 } else if (type == 5) {
434 printf("NT_PAD_SEGMENT\tpad_segment=%u", elf_int(&p)), j=1;
435 } else p -= 8;
436 } else if (notematch(namesz, &p, "CORE")) {
437 if (*(desc = nt_type_core(type)) != '0') printf("%s", desc), j=1;
438 } else if (notematch(namesz, &p, "LINUX")) {
439 if (*(desc = nt_type_linux(type)) != '0') printf("%s", desc), j=1;
440 }
441
442 // If we didn't do custom output above, show a hex dump.
443 if (!j) {
444 printf("0x%x\t", type);
445 for (;j<descsz;j++) printf("%c%02x", j ? ' ' : '\t', *p++/*note[16+j]*/);
446 }
447 xputc('\n');
448 note += 3*4 + ((namesz+3)&~3) + ((descsz+3)&~3);
449 }
450 }
451
scan_elf()452 static void scan_elf()
453 {
454 struct sh dynamic = {}, dynstr = {}, dynsym = {}, shstr = {}, strtab = {},
455 symtab = {}, s;
456 struct ph ph;
457 char *hdr = TT.elf;
458 int type, machine, version, flags, entry, ehsize, phnum, shstrndx, i, j, w;
459
460 if (TT.size < 45 || smemcmp(hdr, "\177ELF", 4))
461 return error_msg("%s: not ELF", TT.f);
462
463 TT.bits = hdr[4] - 1;
464 TT.endian = hdr[5];
465 if (TT.bits<0 || TT.bits>1 || TT.endian<1 || TT.endian>2 || hdr[6]!=1)
466 return error_msg("%s: bad ELF", TT.f);
467
468 hdr += 16; // EI_NIDENT
469 type = elf_short(&hdr);
470 machine = elf_short(&hdr);
471 version = elf_int(&hdr);
472 entry = elf_long(&hdr);
473 TT.phoff = elf_long(&hdr);
474 TT.shoff = elf_long(&hdr);
475 flags = elf_int(&hdr);
476 ehsize = elf_short(&hdr);
477 TT.phentsize = elf_short(&hdr);
478 phnum = elf_short(&hdr);
479 TT.shentsize = elf_short(&hdr);
480 TT.shnum = elf_short(&hdr);
481 shstrndx = elf_short(&hdr);
482
483 if (toys.optc > 1) printf("\nFile: %s\n", TT.f);
484
485 if (FLAG(h)) {
486 printf("ELF Header:\n");
487 printf(" Magic: ");
488 for (i=0; i<16; i++) printf("%02x%c", TT.elf[i], (i==15) ? '\n' : ' ');
489 printf(" Class: ELF%d\n", TT.bits?64:32);
490 printf(" Data: 2's complement, %s endian\n",
491 (TT.endian==2)?"big":"little");
492 printf(" Version: 1 (current)\n");
493 printf(" OS/ABI: %s\n", os_abi(TT.elf[7]));
494 printf(" ABI Version: %d\n", TT.elf[8]);
495 printf(" Type: %s\n", et_type(type));
496 printf(" Machine: %s\n", elf_arch_name(machine));
497 printf(" Version: 0x%x\n", version);
498 printf(" Entry point address: 0x%x\n", entry);
499 printf(" Start of program headers: %llu (bytes into file)\n",
500 TT.phoff);
501 printf(" Start of section headers: %llu (bytes into file)\n",
502 TT.shoff);
503 printf(" Flags: 0x%x", flags);
504 elf_print_flags(machine, flags); putchar('\n');
505 printf(" Size of this header: %d (bytes)\n", ehsize);
506 printf(" Size of program headers: %d (bytes)\n", TT.phentsize);
507 printf(" Number of program headers: %d\n", phnum);
508 printf(" Size of section headers: %d (bytes)\n", TT.shentsize);
509 printf(" Number of section headers: %d\n", TT.shnum);
510 printf(" Section header string table index: %d\n", shstrndx);
511 }
512 if (TT.phoff > TT.size) return error_msg("%s: bad phoff", TT.f);
513 if (TT.shoff > TT.size) return error_msg("%s: bad shoff", TT.f);
514
515 // Set up the section header string table so we can use section header names.
516 // Core files have shstrndx == 0.
517 TT.shstrtab = 0;
518 TT.shstrtabsz = 0;
519 if (shstrndx) {
520 if (!get_sh(shstrndx, &shstr) || shstr.type != 3 /*SHT_STRTAB*/)
521 return error_msg("%s: bad shstrndx", TT.f);
522 TT.shstrtab = TT.elf+shstr.offset;
523 TT.shstrtabsz = shstr.size;
524 }
525
526 w = 8<<TT.bits;
527 if (FLAG(S)) {
528 if (!TT.shnum) printf("\nThere are no sections in this file.\n");
529 else {
530 if (!FLAG(h))
531 printf("There are %d section headers, starting at offset %#llx:\n",
532 TT.shnum, TT.shoff);
533 printf("\nSection Headers:\n"
534 " [Nr] %-17s %-15s %-*s %-6s %-6s ES Flg Lk Inf Al\n",
535 "Name", "Type", w, "Address", "Off", "Size");
536 }
537 }
538 // We need to iterate through the section headers even if we're not
539 // dumping them, to find specific sections.
540 for (i=0; i<TT.shnum; i++) {
541 if (!get_sh(i, &s)) continue;
542 if (s.type == 2 /*SHT_SYMTAB*/) symtab = s;
543 else if (s.type == 6 /*SHT_DYNAMIC*/) dynamic = s;
544 else if (s.type == 11 /*SHT_DYNSYM*/) dynsym = s;
545 else if (s.type == 3 /*SHT_STRTAB*/) {
546 if (!strcmp(s.name, ".strtab")) strtab = s;
547 else if (!strcmp(s.name, ".dynstr")) dynstr = s;
548 }
549
550 if (FLAG(S)) {
551 char sh_flags[12] = {}, *p = sh_flags;
552
553 for (j=0; j<12; j++) if (s.flags&(1<<j)) *p++ = "WAXxMSILOGTC"[j];
554 printf(" [%2d] %-17s %-15s %0*llx %06llx %06llx %02llx %3s %2d %2d %2lld\n",
555 i, s.name, sh_type(s.type), w, s.addr, s.offset, s.size,
556 s.entsize, sh_flags, s.link, s.info, s.addralign);
557 }
558 }
559 if (FLAG(S) && TT.shnum)
560 printf("Key:\n (W)rite, (A)lloc, e(X)ecute, (M)erge, (S)trings, (I)nfo\n"
561 " (L)ink order, (O)S, (G)roup, (T)LS, (C)ompressed, x=unknown\n");
562
563 if (FLAG(l)) {
564 xputc('\n');
565 if (!phnum) printf("There are no program headers in this file.\n");
566 else {
567 if (!FLAG(h))
568 printf("Elf file type is %s\nEntry point %#x\n"
569 "There are %d program headers, starting at offset %lld\n\n",
570 et_type(type), entry, phnum, TT.phoff);
571 printf("Program Headers:\n"
572 " %-14s %-8s %-*s %-*s %-7s %-7s Flg Align\n", "Type",
573 "Offset", w, "VirtAddr", w, "PhysAddr", "FileSiz", "MemSiz");
574 for (i = 0; i<phnum; i++) {
575 if (!get_ph(i, &ph)) continue;
576 printf(" %-14s 0x%06llx 0x%0*llx 0x%0*llx 0x%05llx 0x%05llx %c%c%c %#llx\n",
577 ph_type(ph.type), ph.offset, w, ph.vaddr, w, ph.paddr,
578 ph.filesz, ph.memsz, (ph.flags&4)?'R':' ', (ph.flags&2)?'W':' ',
579 (ph.flags&1)?'E':' ', ph.align);
580 if (ph.type == 3 /*PH_INTERP*/ && ph.filesz<TT.size &&
581 ph.offset<TT.size && ph.filesz - 1 < TT.size - ph.offset) {
582 // TODO: ph.filesz of 0 prints unlimited length string
583 printf(" [Requesting program interpreter: %*s]\n",
584 (int) ph.filesz-1, TT.elf+ph.offset);
585 }
586 }
587
588 printf("\n Section to Segment mapping:\n Segment Sections...\n");
589 for (i=0; i<phnum; i++) {
590 if (!get_ph(i, &ph)) continue;
591 printf(" %02d ", i);
592 for (j=0; j<TT.shnum; j++) {
593 if (!get_sh(j, &s)) continue;
594 if (!*s.name) continue;
595 if (s.offset >= ph.offset && s.offset+s.size <= ph.offset+ph.filesz)
596 printf("%s ", s.name);
597 }
598 xputc('\n');
599 }
600 }
601 }
602
603 // binutils ld emits a bunch of extra DT_NULL entries, so binutils readelf
604 // uses two passes here! We just tell the truth, which matches -h.
605 if (FLAG(d)) {
606 char *dyn = TT.elf+dynamic.offset, *end = dyn+dynamic.size;
607
608 xputc('\n');
609 if (!dynamic.size) printf("There is no dynamic section in this file.\n");
610 else if (!dynamic.entsize) printf("Bad dynamic entry size 0!\n");
611 else {
612 printf("Dynamic section at offset 0x%llx contains %lld entries:\n"
613 " %-*s %-20s %s\n", dynamic.offset, dynamic.size/dynamic.entsize,
614 w+2, "Tag", "Type", "Name/Value");
615 while (dyn < end) {
616 unsigned long long tag = elf_long(&dyn), val = elf_long(&dyn);
617 char *type = dt_type(tag);
618
619 printf(" 0x%0*llx %-20s ", w, tag, type+(*type!='0'));
620 if (*type == 'd') printf("%lld\n", val);
621 else if (*type == 'b') printf("%lld (bytes)\n", val);
622 // TODO: trusting this %s to be null terminated
623 else if (*type == 's') printf("%s\n", TT.elf+dynstr.offset+val);
624 else if (*type == 'f' || *type == 'F') {
625 struct bitname { int bit; char *s; }
626 df_names[] = {{0, "ORIGIN"},{1,"SYMBOLIC"},{2,"TEXTREL"},
627 {3,"BIND_NOW"},{4,"STATIC_TLS"},{}},
628 df_1_names[]={{0,"NOW"},{1,"GLOBAL"},{2,"GROUP"},{3,"NODELETE"},
629 {5,"INITFIRST"},{27,"PIE"},{}},
630 *names = *type == 'f' ? df_names : df_1_names;
631 int mask;
632
633 if (*type == 'F') printf("Flags: ");
634 for (j=0; names[j].s; j++)
635 if (val & (mask=(1<<names[j].bit)))
636 printf("%s%s", names[j].s, (val &= ~mask) ? " " : "");
637 if (val) printf("0x%llx", val);
638 xputc('\n');
639 } else if (*type == 'N' || *type == 'R' || *type == 'S') {
640 char *s = TT.elf+dynstr.offset+val;
641
642 if (dynstr.offset>TT.size || val>TT.size || dynstr.offset>TT.size-val)
643 s = "???";
644 printf("%s: [%s]\n", *type=='N' ? "Shared library" :
645 (*type=='R' ? "Library runpath" : "Library soname"), s);
646 } else if (*type == 'P') {
647 j = strlen(type = dt_type(val));
648 if (*type != '0') type += 2, j -= 3;
649 printf("%*.*s\n", j, j, type);
650 } else printf("0x%llx\n", val);
651 }
652 }
653 }
654
655 if (FLAG(dyn_syms)) show_symbols(&dynsym, &dynstr);
656 if (FLAG(s)) show_symbols(&symtab, &strtab);
657
658 if (FLAG(n)) {
659 int found = 0;
660
661 for (i=0; i<TT.shnum; i++) {
662 if (!get_sh(i, &s)) continue;
663 if (s.type == 7 /*SHT_NOTE*/) {
664 printf("\nDisplaying notes found in: %s\n", s.name);
665 show_notes(s.offset, s.size);
666 found = 1;
667 }
668 }
669 for (i=0; !found && i<phnum; i++) {
670 if (!get_ph(i, &ph)) continue;
671 if (ph.type == 4 /*PT_NOTE*/) {
672 printf("\n"
673 "Displaying notes found at file offset 0x%llx with length 0x%llx:\n",
674 ph.offset, ph.filesz);
675 show_notes(ph.offset, ph.filesz);
676 }
677 }
678 }
679
680 // TODO: ARC/ARM/CSKY have these too.
681 if (FLAG(A) && machine == 243) { // RISCV
682 for (i=0; i<TT.shnum; i++) {
683 if (!get_sh(i, &s)) continue;
684 if (s.type == 0x70000003 /*SHT_RISCV_ATTRIBUTES*/) {
685 show_attributes(s.offset, s.size);
686 }
687 }
688 }
689
690 if (find_section(TT.x, &s)) {
691 char *p = TT.elf+s.offset;
692 long offset = 0;
693
694 printf("\nHex dump of section '%s':\n", s.name);
695 while (offset < s.size) {
696 int space = 2*16 + 16/4;
697
698 printf(" 0x%08lx ", offset);
699 for (i=0; i<16 && offset < s.size; offset++)
700 space -= printf("%02x%s", *p++, " "+!!(++i%4));
701 printf("%*s", space, "");
702 for (p -= i; i; i--, p++) putchar((*p>=' ' && *p<='~') ? *p : '.');
703 xputc('\n');
704 }
705 xputc('\n');
706 }
707
708 if (find_section(TT.p, &s)) {
709 char *begin = TT.elf+s.offset, *end = begin + s.size, *p = begin;
710 int any = 0;
711
712 printf("\nString dump of section '%s':\n", s.name);
713 for (; p < end; p++) {
714 if (isprint(*p)) {
715 printf(" [%6tx] ", p-begin);
716 while (p < end && isprint(*p)) putchar(*p++);
717 xputc('\n');
718 any=1;
719 }
720 }
721 if (!any) printf(" No strings found in this section.\n");
722 xputc('\n');
723 }
724 }
725
readelf_main(void)726 void readelf_main(void)
727 {
728 char **arg;
729 int all = FLAG_A|FLAG_d|FLAG_h|FLAG_l|FLAG_n|FLAG_S|FLAG_s|FLAG_dyn_syms;
730
731 if (FLAG(a)) toys.optflags |= all;
732 if (FLAG(e)) toys.optflags |= FLAG_h|FLAG_l|FLAG_S;
733 if (FLAG(s)) toys.optflags |= FLAG_dyn_syms;
734 if (!(toys.optflags & (all|FLAG_p|FLAG_x))) help_exit("needs a flag");
735
736 for (arg = toys.optargs; *arg; arg++) {
737 int fd = open(TT.f = *arg, O_RDONLY);
738 struct stat sb;
739
740 if (fd == -1) perror_msg_raw(TT.f);
741 else {
742 if (fstat(fd, &sb)) perror_msg_raw(TT.f);
743 else if (!sb.st_size) error_msg("%s: empty", TT.f);
744 else if (!S_ISREG(sb.st_mode)) error_msg("%s: not a regular file",TT.f);
745 else {
746 TT.elf = xmmap(0, TT.size=sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
747 scan_elf();
748 munmap(TT.elf, TT.size);
749 }
750 close(fd);
751 }
752 }
753 }
754