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