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