diff options
| author | Dimitry Andric <dim@FreeBSD.org> | 2019-01-19 10:01:25 +0000 | 
|---|---|---|
| committer | Dimitry Andric <dim@FreeBSD.org> | 2019-01-19 10:01:25 +0000 | 
| commit | d8e91e46262bc44006913e6796843909f1ac7bcd (patch) | |
| tree | 7d0c143d9b38190e0fa0180805389da22cd834c5 /tools/llvm-objdump/llvm-objdump.cpp | |
| parent | b7eb8e35e481a74962664b63dfb09483b200209a (diff) | |
Notes
Diffstat (limited to 'tools/llvm-objdump/llvm-objdump.cpp')
| -rw-r--r-- | tools/llvm-objdump/llvm-objdump.cpp | 786 | 
1 files changed, 438 insertions, 348 deletions
| diff --git a/tools/llvm-objdump/llvm-objdump.cpp b/tools/llvm-objdump/llvm-objdump.cpp index 8041e6f599402..ba8d3c5b8d5c0 100644 --- a/tools/llvm-objdump/llvm-objdump.cpp +++ b/tools/llvm-objdump/llvm-objdump.cpp @@ -42,6 +42,7 @@  #include "llvm/Object/COFFImportFile.h"  #include "llvm/Object/ELFObjectFile.h"  #include "llvm/Object/MachO.h" +#include "llvm/Object/MachOUniversal.h"  #include "llvm/Object/ObjectFile.h"  #include "llvm/Object/Wasm.h"  #include "llvm/Support/Casting.h" @@ -55,8 +56,10 @@  #include "llvm/Support/InitLLVM.h"  #include "llvm/Support/MemoryBuffer.h"  #include "llvm/Support/SourceMgr.h" +#include "llvm/Support/StringSaver.h"  #include "llvm/Support/TargetRegistry.h"  #include "llvm/Support/TargetSelect.h" +#include "llvm/Support/WithColor.h"  #include "llvm/Support/raw_ostream.h"  #include <algorithm>  #include <cctype> @@ -91,12 +94,11 @@ static cl::alias  DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),               cl::aliasopt(DisassembleAll)); -cl::opt<std::string> llvm::Demangle("demangle", -                                    cl::desc("Demangle symbols names"), -                                    cl::ValueOptional, cl::init("none")); +cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"), +                             cl::init(false));  static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"), -                               cl::aliasopt(Demangle)); +                               cl::aliasopt(llvm::Demangle));  static cl::list<std::string>  DisassembleFunctions("df", @@ -105,7 +107,11 @@ DisassembleFunctions("df",  static StringSet<> DisasmFuncsSet;  cl::opt<bool> -llvm::Relocations("r", cl::desc("Display the relocation entries in the file")); +llvm::Relocations("reloc", +                  cl::desc("Display the relocation entries in the file")); +static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"), +                                  cl::NotHidden, +                                  cl::aliasopt(llvm::Relocations));  cl::opt<bool>  llvm::DynamicRelocations("dynamic-reloc", @@ -115,10 +121,16 @@ DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"),               cl::aliasopt(DynamicRelocations));  cl::opt<bool> -llvm::SectionContents("s", cl::desc("Display the content of each section")); +    llvm::SectionContents("full-contents", +                          cl::desc("Display the content of each section")); +static cl::alias SectionContentsShort("s", +                                      cl::desc("Alias for --full-contents"), +                                      cl::aliasopt(SectionContents)); -cl::opt<bool> -llvm::SymbolTable("t", cl::desc("Display the symbol table")); +cl::opt<bool> llvm::SymbolTable("syms", cl::desc("Display the symbol table")); +static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"), +                                  cl::NotHidden, +                                  cl::aliasopt(llvm::SymbolTable));  cl::opt<bool>  llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols")); @@ -253,8 +265,17 @@ cl::opt<unsigned long long>      StartAddress("start-address", cl::desc("Disassemble beginning at address"),                   cl::value_desc("address"), cl::init(0));  cl::opt<unsigned long long> -    StopAddress("stop-address", cl::desc("Stop disassembly at address"), +    StopAddress("stop-address", +                cl::desc("Stop disassembly at address"),                  cl::value_desc("address"), cl::init(UINT64_MAX)); + +cl::opt<bool> DisassembleZeroes( +                "disassemble-zeroes", +                cl::desc("Do not skip blocks of zeroes when disassembling")); +cl::alias DisassembleZeroesShort("z", +                                 cl::desc("Alias for --disassemble-zeroes"), +                                 cl::aliasopt(DisassembleZeroes)); +  static StringRef ToolName;  typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy; @@ -326,33 +347,35 @@ SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {  void llvm::error(std::error_code EC) {    if (!EC)      return; - -  errs() << ToolName << ": error reading file: " << EC.message() << ".\n"; +  WithColor::error(errs(), ToolName) +      << "reading file: " << EC.message() << ".\n";    errs().flush();    exit(1);  }  LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) { -  errs() << ToolName << ": " << Message << ".\n"; +  WithColor::error(errs(), ToolName) << Message << ".\n";    errs().flush();    exit(1);  }  void llvm::warn(StringRef Message) { -  errs() << ToolName << ": warning: " << Message << ".\n"; +  WithColor::warning(errs(), ToolName) << Message << ".\n";    errs().flush();  }  LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,                                                  Twine Message) { -  errs() << ToolName << ": '" << File << "': " << Message << ".\n"; +  WithColor::error(errs(), ToolName) +      << "'" << File << "': " << Message << ".\n";    exit(1);  }  LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,                                                  std::error_code EC) {    assert(EC); -  errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n"; +  WithColor::error(errs(), ToolName) +      << "'" << File << "': " << EC.message() << ".\n";    exit(1);  } @@ -361,9 +384,9 @@ LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,    assert(E);    std::string Buf;    raw_string_ostream OS(Buf); -  logAllUnhandledErrors(std::move(E), OS, ""); +  logAllUnhandledErrors(std::move(E), OS);    OS.flush(); -  errs() << ToolName << ": '" << File << "': " << Buf; +  WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;    exit(1);  } @@ -372,7 +395,7 @@ LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,                                                  llvm::Error E,                                                  StringRef ArchitectureName) {    assert(E); -  errs() << ToolName << ": "; +  WithColor::error(errs(), ToolName);    if (ArchiveName != "")      errs() << ArchiveName << "(" << FileName << ")";    else @@ -381,7 +404,7 @@ LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,      errs() << " (for architecture " << ArchitectureName << ")";    std::string Buf;    raw_string_ostream OS(Buf); -  logAllUnhandledErrors(std::move(E), OS, ""); +  logAllUnhandledErrors(std::move(E), OS);    OS.flush();    errs() << ": " << Buf;    exit(1); @@ -407,18 +430,16 @@ static const Target *getTarget(const ObjectFile *Obj = nullptr) {    // Figure out the target triple.    llvm::Triple TheTriple("unknown-unknown-unknown");    if (TripleName.empty()) { -    if (Obj) { +    if (Obj)        TheTriple = Obj->makeTriple(); -    }    } else {      TheTriple.setTriple(Triple::normalize(TripleName));      // Use the triple, but also try to combine with ARM build attributes.      if (Obj) {        auto Arch = Obj->getArch(); -      if (Arch == Triple::arm || Arch == Triple::armeb) { +      if (Arch == Triple::arm || Arch == Triple::armeb)          Obj->setARMSubArch(TheTriple); -      }      }    } @@ -438,22 +459,35 @@ static const Target *getTarget(const ObjectFile *Obj = nullptr) {    return TheTarget;  } -bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) { -  return a.getOffset() < b.getOffset(); +bool llvm::isRelocAddressLess(RelocationRef A, RelocationRef B) { +  return A.getOffset() < B.getOffset(); +} + +static std::string demangle(StringRef Name) { +  char *Demangled = nullptr; +  if (Name.startswith("_Z")) +    Demangled = itaniumDemangle(Name.data(), Demangled, nullptr, nullptr); +  else if (Name.startswith("?")) +    Demangled = microsoftDemangle(Name.data(), Demangled, nullptr, nullptr); + +  if (!Demangled) +    return Name; + +  std::string Ret = Demangled; +  free(Demangled); +  return Ret;  }  template <class ELFT>  static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,                                                  const RelocationRef &RelRef,                                                  SmallVectorImpl<char> &Result) { -  DataRefImpl Rel = RelRef.getRawDataRefImpl(); -    typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;    typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;    typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;    const ELFFile<ELFT> &EF = *Obj->getELFFile(); - +  DataRefImpl Rel = RelRef.getRawDataRefImpl();    auto SecOrErr = EF.getSection(Rel.d.a);    if (!SecOrErr)      return errorToErrorCode(SecOrErr.takeError()); @@ -471,11 +505,11 @@ static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,    if (!StrTabOrErr)      return errorToErrorCode(StrTabOrErr.takeError());    StringRef StrTab = *StrTabOrErr; -  int64_t addend = 0; +  int64_t Addend = 0;    // If there is no Symbol associated with the relocation, we set the undef    // boolean value to 'true'. This will prevent us from calling functions that    // requires the relocation to be associated with a symbol. -  bool undef = false; +  bool Undef = false;    switch (Sec->sh_type) {    default:      return object_error::parse_failed; @@ -485,13 +519,13 @@ static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,    }    case ELF::SHT_RELA: {      const Elf_Rela *ERela = Obj->getRela(Rel); -    addend = ERela->r_addend; -    undef = ERela->getSymbol(false) == 0; +    Addend = ERela->r_addend; +    Undef = ERela->getSymbol(false) == 0;      break;    }    } -  StringRef Target; -  if (!undef) { +  std::string Target; +  if (!Undef) {      symbol_iterator SI = RelRef.getSymbol();      const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());      if (symb->getType() == ELF::STT_SECTION) { @@ -507,20 +541,23 @@ static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,        Expected<StringRef> SymName = symb->getName(StrTab);        if (!SymName)          return errorToErrorCode(SymName.takeError()); -      Target = *SymName; +      if (Demangle) +        Target = demangle(*SymName); +      else +        Target = *SymName;      }    } else      Target = "*ABS*";    // Default scheme is to print Target, as well as "+ <addend>" for nonzero    // addend. Should be acceptable for all normal purposes. -  std::string fmtbuf; -  raw_string_ostream fmt(fmtbuf); -  fmt << Target; -  if (addend != 0) -    fmt << (addend < 0 ? "" : "+") << addend; -  fmt.flush(); -  Result.append(fmtbuf.begin(), fmtbuf.end()); +  std::string FmtBuf; +  raw_string_ostream Fmt(FmtBuf); +  Fmt << Target; +  if (Addend != 0) +    Fmt << (Addend < 0 ? "" : "+") << Addend; +  Fmt.flush(); +  Result.append(FmtBuf.begin(), FmtBuf.end());    return std::error_code();  } @@ -551,18 +588,15 @@ static std::error_code getRelocationValueString(const COFFObjectFile *Obj,  static void printRelocationTargetName(const MachOObjectFile *O,                                        const MachO::any_relocation_info &RE, -                                      raw_string_ostream &fmt) { -  bool IsScattered = O->isRelocationScattered(RE); - +                                      raw_string_ostream &Fmt) {    // Target of a scattered relocation is an address.  In the interest of    // generating pretty output, scan through the symbol table looking for a    // symbol that aligns with that address.  If we find one, print it.    // Otherwise, we just print the hex address of the target. -  if (IsScattered) { +  if (O->isRelocationScattered(RE)) {      uint32_t Val = O->getPlainRelocationSymbolNum(RE);      for (const SymbolRef &Symbol : O->symbols()) { -      std::error_code ec;        Expected<uint64_t> Addr = Symbol.getAddress();        if (!Addr)          report_error(O->getFileName(), Addr.takeError()); @@ -571,7 +605,7 @@ static void printRelocationTargetName(const MachOObjectFile *O,        Expected<StringRef> Name = Symbol.getName();        if (!Name)          report_error(O->getFileName(), Name.takeError()); -      fmt << *Name; +      Fmt << *Name;        return;      } @@ -586,11 +620,11 @@ static void printRelocationTargetName(const MachOObjectFile *O,          continue;        if ((ec = Section.getName(Name)))          report_error(O->getFileName(), ec); -      fmt << Name; +      Fmt << Name;        return;      } -    fmt << format("0x%x", Val); +    Fmt << format("0x%x", Val);      return;    } @@ -599,9 +633,11 @@ static void printRelocationTargetName(const MachOObjectFile *O,    uint64_t Val = O->getPlainRelocationSymbolNum(RE);    if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) { -    fmt << format("0x%0" PRIx64, Val); +    Fmt << format("0x%0" PRIx64, Val);      return; -  } else if (isExtern) { +  } + +  if (isExtern) {      symbol_iterator SI = O->symbol_begin();      advance(SI, Val);      Expected<StringRef> SOrErr = SI->getName(); @@ -612,21 +648,21 @@ static void printRelocationTargetName(const MachOObjectFile *O,      section_iterator SI = O->section_begin();      // Adjust for the fact that sections are 1-indexed.      if (Val == 0) { -      fmt << "0 (?,?)"; +      Fmt << "0 (?,?)";        return;      } -    uint32_t i = Val - 1; -    while (i != 0 && SI != O->section_end()) { -      i--; +    uint32_t I = Val - 1; +    while (I != 0 && SI != O->section_end()) { +      --I;        advance(SI, 1);      }      if (SI == O->section_end()) -      fmt << Val << " (?,?)"; +      Fmt << Val << " (?,?)";      else        SI->getName(S);    } -  fmt << S; +  Fmt << S;  }  static std::error_code getRelocationValueString(const WasmObjectFile *Obj, @@ -634,12 +670,12 @@ static std::error_code getRelocationValueString(const WasmObjectFile *Obj,                                                  SmallVectorImpl<char> &Result) {    const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);    symbol_iterator SI = RelRef.getSymbol(); -  std::string fmtbuf; -  raw_string_ostream fmt(fmtbuf); +  std::string FmtBuf; +  raw_string_ostream Fmt(FmtBuf);    if (SI == Obj->symbol_end()) {      // Not all wasm relocations have symbols associated with them.      // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB. -    fmt << Rel.Index; +    Fmt << Rel.Index;    } else {      Expected<StringRef> SymNameOrErr = SI->getName();      if (!SymNameOrErr) @@ -647,9 +683,9 @@ static std::error_code getRelocationValueString(const WasmObjectFile *Obj,      StringRef SymName = *SymNameOrErr;      Result.append(SymName.begin(), SymName.end());    } -  fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend; -  fmt.flush(); -  Result.append(fmtbuf.begin(), fmtbuf.end()); +  Fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend; +  Fmt.flush(); +  Result.append(FmtBuf.begin(), FmtBuf.end());    return std::error_code();  } @@ -661,8 +697,8 @@ static std::error_code getRelocationValueString(const MachOObjectFile *Obj,    unsigned Arch = Obj->getArch(); -  std::string fmtbuf; -  raw_string_ostream fmt(fmtbuf); +  std::string FmtBuf; +  raw_string_ostream Fmt(FmtBuf);    unsigned Type = Obj->getAnyRelocationType(RE);    bool IsPCRel = Obj->getAnyRelocationPCRel(RE); @@ -671,15 +707,13 @@ static std::error_code getRelocationValueString(const MachOObjectFile *Obj,    // X86_64 has entirely custom relocation types.    if (Arch == Triple::x86_64) { -    bool isPCRel = Obj->getAnyRelocationPCRel(RE); -      switch (Type) {      case MachO::X86_64_RELOC_GOT_LOAD:      case MachO::X86_64_RELOC_GOT: { -      printRelocationTargetName(Obj, RE, fmt); -      fmt << "@GOT"; -      if (isPCRel) -        fmt << "PCREL"; +      printRelocationTargetName(Obj, RE, Fmt); +      Fmt << "@GOT"; +      if (IsPCRel) +        Fmt << "PCREL";        break;      }      case MachO::X86_64_RELOC_SUBTRACTOR: { @@ -697,31 +731,31 @@ static std::error_code getRelocationValueString(const MachOObjectFile *Obj,        // The X86_64_RELOC_UNSIGNED contains the minuend symbol;        // X86_64_RELOC_SUBTRACTOR contains the subtrahend. -      printRelocationTargetName(Obj, RENext, fmt); -      fmt << "-"; -      printRelocationTargetName(Obj, RE, fmt); +      printRelocationTargetName(Obj, RENext, Fmt); +      Fmt << "-"; +      printRelocationTargetName(Obj, RE, Fmt);        break;      }      case MachO::X86_64_RELOC_TLV: -      printRelocationTargetName(Obj, RE, fmt); -      fmt << "@TLV"; -      if (isPCRel) -        fmt << "P"; +      printRelocationTargetName(Obj, RE, Fmt); +      Fmt << "@TLV"; +      if (IsPCRel) +        Fmt << "P";        break;      case MachO::X86_64_RELOC_SIGNED_1: -      printRelocationTargetName(Obj, RE, fmt); -      fmt << "-1"; +      printRelocationTargetName(Obj, RE, Fmt); +      Fmt << "-1";        break;      case MachO::X86_64_RELOC_SIGNED_2: -      printRelocationTargetName(Obj, RE, fmt); -      fmt << "-2"; +      printRelocationTargetName(Obj, RE, Fmt); +      Fmt << "-2";        break;      case MachO::X86_64_RELOC_SIGNED_4: -      printRelocationTargetName(Obj, RE, fmt); -      fmt << "-4"; +      printRelocationTargetName(Obj, RE, Fmt); +      Fmt << "-4";        break;      default: -      printRelocationTargetName(Obj, RE, fmt); +      printRelocationTargetName(Obj, RE, Fmt);        break;      }      // X86 and ARM share some relocation types in common. @@ -744,9 +778,9 @@ static std::error_code getRelocationValueString(const MachOObjectFile *Obj,          report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "                       "GENERIC_RELOC_SECTDIFF."); -      printRelocationTargetName(Obj, RE, fmt); -      fmt << "-"; -      printRelocationTargetName(Obj, RENext, fmt); +      printRelocationTargetName(Obj, RE, Fmt); +      Fmt << "-"; +      printRelocationTargetName(Obj, RENext, Fmt);        break;      }      } @@ -765,20 +799,20 @@ static std::error_code getRelocationValueString(const MachOObjectFile *Obj,            report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "                         "GENERIC_RELOC_LOCAL_SECTDIFF."); -        printRelocationTargetName(Obj, RE, fmt); -        fmt << "-"; -        printRelocationTargetName(Obj, RENext, fmt); +        printRelocationTargetName(Obj, RE, Fmt); +        Fmt << "-"; +        printRelocationTargetName(Obj, RENext, Fmt);          break;        }        case MachO::GENERIC_RELOC_TLV: { -        printRelocationTargetName(Obj, RE, fmt); -        fmt << "@TLV"; +        printRelocationTargetName(Obj, RE, Fmt); +        Fmt << "@TLV";          if (IsPCRel) -          fmt << "P"; +          Fmt << "P";          break;        }        default: -        printRelocationTargetName(Obj, RE, fmt); +        printRelocationTargetName(Obj, RE, Fmt);        }      } else { // ARM-specific relocations        switch (Type) { @@ -789,10 +823,10 @@ static std::error_code getRelocationValueString(const MachOObjectFile *Obj,          bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;          if (isUpper) -          fmt << ":upper16:("; +          Fmt << ":upper16:(";          else -          fmt << ":lower16:("; -        printRelocationTargetName(Obj, RE, fmt); +          Fmt << ":lower16:("; +        printRelocationTargetName(Obj, RE, Fmt);          DataRefImpl RelNext = Rel;          Obj->moveRelocationNext(RelNext); @@ -813,21 +847,21 @@ static std::error_code getRelocationValueString(const MachOObjectFile *Obj,          // ARM_RELOC_HALF_SECTDIFF encodes the second section in the          // symbol/section pointer of the follow-on relocation.          if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) { -          fmt << "-"; -          printRelocationTargetName(Obj, RENext, fmt); +          Fmt << "-"; +          printRelocationTargetName(Obj, RENext, Fmt);          } -        fmt << ")"; +        Fmt << ")";          break;        } -      default: { printRelocationTargetName(Obj, RE, fmt); } +      default: { printRelocationTargetName(Obj, RE, Fmt); }        }      }    } else -    printRelocationTargetName(Obj, RE, fmt); +    printRelocationTargetName(Obj, RE, Fmt); -  fmt.flush(); -  Result.append(fmtbuf.begin(), fmtbuf.end()); +  Fmt.flush(); +  Result.append(FmtBuf.begin(), FmtBuf.end());    return std::error_code();  } @@ -849,8 +883,7 @@ static std::error_code getRelocationValueString(const RelocationRef &Rel,  /// relocations, usually because it is the trailing part of a multipart  /// relocation that will be printed as part of the leading relocation.  static bool getHidden(RelocationRef RelRef) { -  const ObjectFile *Obj = RelRef.getObject(); -  auto *MachO = dyn_cast<MachOObjectFile>(Obj); +  auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());    if (!MachO)      return false; @@ -860,10 +893,10 @@ static bool getHidden(RelocationRef RelRef) {    // On arches that use the generic relocations, GENERIC_RELOC_PAIR    // is always hidden. -  if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) { -    if (Type == MachO::GENERIC_RELOC_PAIR) -      return true; -  } else if (Arch == Triple::x86_64) { +  if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) +    return Type == MachO::GENERIC_RELOC_PAIR; + +  if (Arch == Triple::x86_64) {      // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows      // an X86_64_RELOC_SUBTRACTOR.      if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) { @@ -1038,27 +1071,27 @@ public:      auto Preamble = " { ";      auto Separator = "";      StringRef Fmt = "\t\t\t%08" PRIx64 ":  "; -    std::vector<RelocationRef>::const_iterator rel_cur = Rels->begin(); -    std::vector<RelocationRef>::const_iterator rel_end = Rels->end(); +    std::vector<RelocationRef>::const_iterator RelCur = Rels->begin(); +    std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();      // Hexagon's packets require relocations to be inline rather than      // clustered at the end of the packet.      auto PrintReloc = [&]() -> void { -      while ((rel_cur != rel_end) && (rel_cur->getOffset() <= Address)) { -        if (rel_cur->getOffset() == Address) { -          SmallString<16> name; -          SmallString<32> val; -          rel_cur->getTypeName(name); -          error(getRelocationValueString(*rel_cur, val)); -          OS << Separator << format(Fmt.data(), Address) << name << "\t" << val +      while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address)) { +        if (RelCur->getOffset() == Address) { +          SmallString<16> Name; +          SmallString<32> Val; +          RelCur->getTypeName(Name); +          error(getRelocationValueString(*RelCur, Val)); +          OS << Separator << format(Fmt.data(), Address) << Name << "\t" << Val                  << "\n";            return;          } -        rel_cur++; +        ++RelCur;        }      }; -    while(!HeadTail.first.empty()) { +    while (!HeadTail.first.empty()) {        OS << Separator;        Separator = "\n";        if (SP && (PrintSource || PrintLines)) @@ -1068,7 +1101,7 @@ public:        Preamble = "   ";        StringRef Inst;        auto Duplex = HeadTail.first.split('\v'); -      if(!Duplex.second.empty()){ +      if (!Duplex.second.empty()) {          OS << Duplex.first;          OS << "; ";          Inst = Duplex.second; @@ -1200,7 +1233,6 @@ addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,      Expected<uint64_t> AddressOrErr = Symbol.getAddress();      if (!AddressOrErr)        report_error(Obj->getFileName(), AddressOrErr.takeError()); -    uint64_t Address = *AddressOrErr;      Expected<StringRef> Name = Symbol.getName();      if (!Name) @@ -1215,7 +1247,7 @@ addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,      if (SecI == Obj->section_end())        continue; -    AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType); +    AllSymbols[*SecI].emplace_back(*AddressOrErr, *Name, SymbolType);    }  } @@ -1235,7 +1267,60 @@ addDynamicElfSymbols(const ObjectFile *Obj,      llvm_unreachable("Unsupported binary format");  } -static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) { +static void addPltEntries(const ObjectFile *Obj, +                          std::map<SectionRef, SectionSymbolsTy> &AllSymbols, +                          StringSaver &Saver) { +  Optional<SectionRef> Plt = None; +  for (const SectionRef &Section : Obj->sections()) { +    StringRef Name; +    if (Section.getName(Name)) +      continue; +    if (Name == ".plt") +      Plt = Section; +  } +  if (!Plt) +    return; +  if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) { +    for (auto PltEntry : ElfObj->getPltAddresses()) { +      SymbolRef Symbol(PltEntry.first, ElfObj); +      uint8_t SymbolType = getElfSymbolType(Obj, Symbol); + +      Expected<StringRef> NameOrErr = Symbol.getName(); +      if (!NameOrErr) +        report_error(Obj->getFileName(), NameOrErr.takeError()); +      if (NameOrErr->empty()) +        continue; +      StringRef Name = Saver.save((*NameOrErr + "@plt").str()); + +      AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType); +    } +  } +} + +// Normally the disassembly output will skip blocks of zeroes. This function +// returns the number of zero bytes that can be skipped when dumping the +// disassembly of the instructions in Buf. +static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) { +  // When -z or --disassemble-zeroes are given we always dissasemble them. +  if (DisassembleZeroes) +    return 0; + +  // Find the number of leading zeroes. +  size_t N = 0; +  while (N < Buf.size() && !Buf[N]) +    ++N; + +  // We may want to skip blocks of zero bytes, but unless we see +  // at least 8 of them in a row. +  if (N < 8) +    return 0; + +  // We skip zeroes in multiples of 4 because do not want to truncate an +  // instruction if it starts with a zero byte. +  return N & ~0x3; +} + +static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {    if (StartAddress > StopAddress)      error("Start address should be less than stop address"); @@ -1243,10 +1328,9 @@ static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {    // Package up features to be passed to target/subtarget    SubtargetFeatures Features = Obj->getFeatures(); -  if (MAttrs.size()) { -    for (unsigned i = 0; i != MAttrs.size(); ++i) -      Features.AddFeature(MAttrs[i]); -  } +  if (!MAttrs.empty()) +    for (unsigned I = 0; I != MAttrs.size(); ++I) +      Features.AddFeature(MAttrs[I]);    std::unique_ptr<const MCRegisterInfo> MRI(        TheTarget->createMCRegInfo(TripleName)); @@ -1342,6 +1426,10 @@ static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {    if (AllSymbols.empty() && Obj->isELF())      addDynamicElfSymbols(Obj, AllSymbols); +  BumpPtrAllocator A; +  StringSaver Saver(A); +  addPltEntries(Obj, AllSymbols, Saver); +    // Create a mapping from virtual address to section.    std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;    for (SectionRef Sec : Obj->sections()) @@ -1411,8 +1499,8 @@ static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {        }      } -    llvm::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end()); -    llvm::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end()); +    llvm::sort(DataMappingSymsAddr); +    llvm::sort(TextMappingSymsAddr);      if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {        // AMDGPU disassembler uses symbolizer for printing labels @@ -1437,7 +1525,7 @@ static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {      }      // Sort relocations by address. -    llvm::sort(Rels.begin(), Rels.end(), RelocAddressLess); +    llvm::sort(Rels, isRelocAddressLess);      StringRef SegmentName = "";      if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) { @@ -1467,15 +1555,16 @@ static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {      uint64_t Index;      bool PrintedSection = false; -    std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin(); -    std::vector<RelocationRef>::const_iterator rel_end = Rels.end(); +    std::vector<RelocationRef>::const_iterator RelCur = Rels.begin(); +    std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();      // Disassemble symbol by symbol. -    for (unsigned si = 0, se = Symbols.size(); si != se; ++si) { -      uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr; +    for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) { +      uint64_t Start = std::get<0>(Symbols[SI]) - SectionAddr;        // The end is either the section end or the beginning of the next        // symbol. -      uint64_t End = -          (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr; +      uint64_t End = (SI == SE - 1) +                         ? SectSize +                         : std::get<0>(Symbols[SI + 1]) - SectionAddr;        // Don't try to disassemble beyond the end of section contents.        if (End > SectSize)          End = SectSize; @@ -1492,7 +1581,7 @@ static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {        /// Skip if user requested specific symbols and this is not in the list        if (!DisasmFuncsSet.empty() && -          !DisasmFuncsSet.count(std::get<1>(Symbols[si]))) +          !DisasmFuncsSet.count(std::get<1>(Symbols[SI])))          continue;        if (!PrintedSection) { @@ -1508,12 +1597,12 @@ static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {          End = StopAddress - SectionAddr;        if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { -        if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) { +        if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) {            // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)            Start += 256;          } -        if (si == se - 1 || -            std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) { +        if (SI == SE - 1 || +            std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {            // cut trailing zeroes at the end of kernel            // cut up to 256 bytes            const uint64_t EndAlign = 256; @@ -1524,25 +1613,15 @@ static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {          }        } -      auto PrintSymbol = [](StringRef Name) { -        outs() << '\n' << Name << ":\n"; -      }; -      StringRef SymbolName = std::get<1>(Symbols[si]); -      if (Demangle.getValue() == "" || Demangle.getValue() == "itanium") { -        char *DemangledSymbol = nullptr; -        size_t Size = 0; -        int Status; -        DemangledSymbol = -            itaniumDemangle(SymbolName.data(), DemangledSymbol, &Size, &Status); -        if (Status == 0) -          PrintSymbol(StringRef(DemangledSymbol)); -        else -          PrintSymbol(SymbolName); +      outs() << '\n'; +      if (!NoLeadingAddr) +        outs() << format("%016" PRIx64 " ", SectionAddr + Start); -        if (Size != 0) -          free(DemangledSymbol); -      } else -        PrintSymbol(SymbolName); +      StringRef SymbolName = std::get<1>(Symbols[SI]); +      if (Demangle) +        outs() << demangle(SymbolName) << ":\n"; +      else +        outs() << SymbolName << ":\n";        // Don't print raw contents of a virtual section. A virtual section        // doesn't have any contents in the file. @@ -1570,7 +1649,7 @@ static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {          // same section. We rely on the markers introduced to          // understand what we need to dump. If the data marker is within a          // function, it is denoted as a word/short etc -        if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT && +        if (isArmElf(Obj) && std::get<2>(Symbols[SI]) != ELF::STT_OBJECT &&              !DisassembleAll) {            uint64_t Stride = 0; @@ -1634,7 +1713,7 @@ static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {          // disassembling text (applicable all architectures),          // we are in a situation where we must print the data and not          // disassemble it. -        if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT && +        if (Obj->isELF() && std::get<2>(Symbols[SI]) == ELF::STT_OBJECT &&              !DisassembleAll && Section.isText()) {            // print out data up to 8 bytes at a time in hex and ascii            uint8_t AsciiData[9] = {'\0'}; @@ -1675,6 +1754,14 @@ static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {          if (Index >= End)            break; +        if (size_t N = +                countSkippableZeroBytes(Bytes.slice(Index, End - Index))) { +          outs() << "\t\t..." << '\n'; +          Index += N; +          if (Index >= End) +            break; +        } +          // Disassemble a real instruction or a data when disassemble all is          // provided          bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), @@ -1753,32 +1840,32 @@ static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {          // Hexagon does this in pretty printer          if (Obj->getArch() != Triple::hexagon)            // Print relocation for instruction. -          while (rel_cur != rel_end) { -            bool hidden = getHidden(*rel_cur); -            uint64_t addr = rel_cur->getOffset(); -            SmallString<16> name; -            SmallString<32> val; +          while (RelCur != RelEnd) { +            uint64_t Addr = RelCur->getOffset(); +            SmallString<16> Name; +            SmallString<32> Val;              // If this relocation is hidden, skip it. -            if (hidden || ((SectionAddr + addr) < StartAddress)) { -              ++rel_cur; +            if (getHidden(*RelCur) || ((SectionAddr + Addr) < StartAddress)) { +              ++RelCur;                continue;              }              // Stop when rel_cur's address is past the current instruction. -            if (addr >= Index + Size) break; -            rel_cur->getTypeName(name); -            error(getRelocationValueString(*rel_cur, val)); -            outs() << format(Fmt.data(), SectionAddr + addr) << name -                   << "\t" << val << "\n"; -            ++rel_cur; +            if (Addr >= Index + Size) +              break; +            RelCur->getTypeName(Name); +            error(getRelocationValueString(*RelCur, Val)); +            outs() << format(Fmt.data(), SectionAddr + Addr) << Name << "\t" +                   << Val << "\n"; +            ++RelCur;            }        }      }    }  } -void llvm::PrintRelocations(const ObjectFile *Obj) { +void llvm::printRelocations(const ObjectFile *Obj) {    StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :                                                   "%08" PRIx64;    // Regular objdump doesn't print relocations in non-relocatable object @@ -1789,61 +1876,57 @@ void llvm::PrintRelocations(const ObjectFile *Obj) {    for (const SectionRef &Section : ToolSectionFilter(*Obj)) {      if (Section.relocation_begin() == Section.relocation_end())        continue; -    StringRef secname; -    error(Section.getName(secname)); -    outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n"; +    StringRef SecName; +    error(Section.getName(SecName)); +    outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";      for (const RelocationRef &Reloc : Section.relocations()) { -      bool hidden = getHidden(Reloc); -      uint64_t address = Reloc.getOffset(); -      SmallString<32> relocname; -      SmallString<32> valuestr; -      if (address < StartAddress || address > StopAddress || hidden) +      uint64_t Address = Reloc.getOffset(); +      SmallString<32> RelocName; +      SmallString<32> ValueStr; +      if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))          continue; -      Reloc.getTypeName(relocname); -      error(getRelocationValueString(Reloc, valuestr)); -      outs() << format(Fmt.data(), address) << " " << relocname << " " -             << valuestr << "\n"; +      Reloc.getTypeName(RelocName); +      error(getRelocationValueString(Reloc, ValueStr)); +      outs() << format(Fmt.data(), Address) << " " << RelocName << " " +             << ValueStr << "\n";      }      outs() << "\n";    }  } -void llvm::PrintDynamicRelocations(const ObjectFile *Obj) { - +void llvm::printDynamicRelocations(const ObjectFile *Obj) {    // For the moment, this option is for ELF only    if (!Obj->isELF())      return;    const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj); -    if (!Elf || Elf->getEType() != ELF::ET_DYN) {      error("not a dynamic object");      return;    } -  StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; -    std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();    if (DynRelSec.empty())      return;    outs() << "DYNAMIC RELOCATION RECORDS\n"; +  StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;    for (const SectionRef &Section : DynRelSec) {      if (Section.relocation_begin() == Section.relocation_end())        continue;      for (const RelocationRef &Reloc : Section.relocations()) { -      uint64_t address = Reloc.getOffset(); -      SmallString<32> relocname; -      SmallString<32> valuestr; -      Reloc.getTypeName(relocname); -      error(getRelocationValueString(Reloc, valuestr)); -      outs() << format(Fmt.data(), address) << " " << relocname << " " -             << valuestr << "\n"; +      uint64_t Address = Reloc.getOffset(); +      SmallString<32> RelocName; +      SmallString<32> ValueStr; +      Reloc.getTypeName(RelocName); +      error(getRelocationValueString(Reloc, ValueStr)); +      outs() << format(Fmt.data(), Address) << " " << RelocName << " " +             << ValueStr << "\n";      }    }  } -void llvm::PrintSectionHeaders(const ObjectFile *Obj) { +void llvm::printSectionHeaders(const ObjectFile *Obj) {    outs() << "Sections:\n"              "Idx Name          Size      Address          Type\n";    for (const SectionRef &Section : ToolSectionFilter(*Obj)) { @@ -1860,9 +1943,10 @@ void llvm::PrintSectionHeaders(const ObjectFile *Obj) {                       (unsigned)Section.getIndex(), Name.str().c_str(), Size,                       Address, Type.c_str());    } +  outs() << "\n";  } -void llvm::PrintSectionContents(const ObjectFile *Obj) { +void llvm::printSectionContents(const ObjectFile *Obj) {    std::error_code EC;    for (const SectionRef &Section : ToolSectionFilter(*Obj)) {      StringRef Name; @@ -1884,23 +1968,23 @@ void llvm::PrintSectionContents(const ObjectFile *Obj) {      error(Section.getContents(Contents));      // Dump out the content as hex and printable ascii characters. -    for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) { -      outs() << format(" %04" PRIx64 " ", BaseAddr + addr); +    for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) { +      outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);        // Dump line of hex. -      for (std::size_t i = 0; i < 16; ++i) { -        if (i != 0 && i % 4 == 0) +      for (std::size_t I = 0; I < 16; ++I) { +        if (I != 0 && I % 4 == 0)            outs() << ' '; -        if (addr + i < end) -          outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true) -                 << hexdigit(Contents[addr + i] & 0xF, true); +        if (Addr + I < End) +          outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true) +                 << hexdigit(Contents[Addr + I] & 0xF, true);          else            outs() << "  ";        }        // Print ascii.        outs() << "  "; -      for (std::size_t i = 0; i < 16 && addr + i < end; ++i) { -        if (isPrint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF)) -          outs() << Contents[addr + i]; +      for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) { +        if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF)) +          outs() << Contents[Addr + I];          else            outs() << ".";        } @@ -1909,40 +1993,47 @@ void llvm::PrintSectionContents(const ObjectFile *Obj) {    }  } -void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName, +void llvm::printSymbolTable(const ObjectFile *O, StringRef ArchiveName,                              StringRef ArchitectureName) {    outs() << "SYMBOL TABLE:\n"; -  if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) { -    printCOFFSymbolTable(coff); +  if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) { +    printCOFFSymbolTable(Coff);      return;    } -  for (const SymbolRef &Symbol : o->symbols()) { + +  for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) { +    // Skip printing the special zero symbol when dumping an ELF file. +    // This makes the output consistent with the GNU objdump. +    if (I == O->symbol_begin() && isa<ELFObjectFileBase>(O)) +      continue; + +    const SymbolRef &Symbol = *I;      Expected<uint64_t> AddressOrError = Symbol.getAddress();      if (!AddressOrError) -      report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(), +      report_error(ArchiveName, O->getFileName(), AddressOrError.takeError(),                     ArchitectureName);      uint64_t Address = *AddressOrError;      if ((Address < StartAddress) || (Address > StopAddress))        continue;      Expected<SymbolRef::Type> TypeOrError = Symbol.getType();      if (!TypeOrError) -      report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(), +      report_error(ArchiveName, O->getFileName(), TypeOrError.takeError(),                     ArchitectureName);      SymbolRef::Type Type = *TypeOrError;      uint32_t Flags = Symbol.getFlags();      Expected<section_iterator> SectionOrErr = Symbol.getSection();      if (!SectionOrErr) -      report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(), +      report_error(ArchiveName, O->getFileName(), SectionOrErr.takeError(),                     ArchitectureName);      section_iterator Section = *SectionOrErr;      StringRef Name; -    if (Type == SymbolRef::ST_Debug && Section != o->section_end()) { +    if (Type == SymbolRef::ST_Debug && Section != O->section_end()) {        Section->getName(Name);      } else {        Expected<StringRef> NameOrErr = Symbol.getName();        if (!NameOrErr) -        report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(), +        report_error(ArchiveName, O->getFileName(), NameOrErr.takeError(),                       ArchitectureName);        Name = *NameOrErr;      } @@ -1963,8 +2054,10 @@ void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,        FileFunc = 'f';      else if (Type == SymbolRef::ST_Function)        FileFunc = 'F'; +    else if (Type == SymbolRef::ST_Data) +      FileFunc = 'O'; -    const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : +    const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :                                                     "%08" PRIx64;      outs() << format(Fmt, Address) << " " @@ -1980,11 +2073,11 @@ void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,        outs() << "*ABS*";      } else if (Common) {        outs() << "*COM*"; -    } else if (Section == o->section_end()) { +    } else if (Section == O->section_end()) {        outs() << "*UND*";      } else {        if (const MachOObjectFile *MachO = -          dyn_cast<const MachOObjectFile>(o)) { +          dyn_cast<const MachOObjectFile>(O)) {          DataRefImpl DR = Section->getRawDataRefImpl();          StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);          outs() << SegmentName << ","; @@ -1995,98 +2088,95 @@ void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,      }      outs() << '\t'; -    if (Common || isa<ELFObjectFileBase>(o)) { +    if (Common || isa<ELFObjectFileBase>(O)) {        uint64_t Val =            Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();        outs() << format("\t %08" PRIx64 " ", Val);      } -    if (Hidden) { +    if (Hidden)        outs() << ".hidden "; -    } -    outs() << Name -           << '\n'; + +    if (Demangle) +      outs() << demangle(Name) << '\n'; +    else +      outs() << Name << '\n';    }  } -static void PrintUnwindInfo(const ObjectFile *o) { +static void printUnwindInfo(const ObjectFile *O) {    outs() << "Unwind info:\n\n"; -  if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) { -    printCOFFUnwindInfo(coff); -  } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) +  if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O)) +    printCOFFUnwindInfo(Coff); +  else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))      printMachOUnwindInfo(MachO); -  else { +  else      // TODO: Extract DWARF dump tool to objdump. -    errs() << "This operation is only currently supported " -              "for COFF and MachO object files.\n"; -    return; -  } +    WithColor::error(errs(), ToolName) +        << "This operation is only currently supported " +           "for COFF and MachO object files.\n";  }  void llvm::printExportsTrie(const ObjectFile *o) {    outs() << "Exports trie:\n";    if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))      printMachOExportsTrie(MachO); -  else { -    errs() << "This operation is only currently supported " -              "for Mach-O executable files.\n"; -    return; -  } +  else +    WithColor::error(errs(), ToolName) +        << "This operation is only currently supported " +           "for Mach-O executable files.\n";  }  void llvm::printRebaseTable(ObjectFile *o) {    outs() << "Rebase table:\n";    if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))      printMachORebaseTable(MachO); -  else { -    errs() << "This operation is only currently supported " -              "for Mach-O executable files.\n"; -    return; -  } +  else +    WithColor::error(errs(), ToolName) +        << "This operation is only currently supported " +           "for Mach-O executable files.\n";  }  void llvm::printBindTable(ObjectFile *o) {    outs() << "Bind table:\n";    if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))      printMachOBindTable(MachO); -  else { -    errs() << "This operation is only currently supported " -              "for Mach-O executable files.\n"; -    return; -  } +  else +    WithColor::error(errs(), ToolName) +        << "This operation is only currently supported " +           "for Mach-O executable files.\n";  }  void llvm::printLazyBindTable(ObjectFile *o) {    outs() << "Lazy bind table:\n";    if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))      printMachOLazyBindTable(MachO); -  else { -    errs() << "This operation is only currently supported " -              "for Mach-O executable files.\n"; -    return; -  } +  else +    WithColor::error(errs(), ToolName) +        << "This operation is only currently supported " +           "for Mach-O executable files.\n";  }  void llvm::printWeakBindTable(ObjectFile *o) {    outs() << "Weak bind table:\n";    if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))      printMachOWeakBindTable(MachO); -  else { -    errs() << "This operation is only currently supported " -              "for Mach-O executable files.\n"; -    return; -  } +  else +    WithColor::error(errs(), ToolName) +        << "This operation is only currently supported " +           "for Mach-O executable files.\n";  }  /// Dump the raw contents of the __clangast section so the output can be piped  /// into llvm-bcanalyzer.  void llvm::printRawClangAST(const ObjectFile *Obj) {    if (outs().is_displayed()) { -    errs() << "The -raw-clang-ast option will dump the raw binary contents of " -              "the clang ast section.\n" -              "Please redirect the output to a file or another program such as " -              "llvm-bcanalyzer.\n"; +    WithColor::error(errs(), ToolName) +        << "The -raw-clang-ast option will dump the raw binary contents of " +           "the clang ast section.\n" +           "Please redirect the output to a file or another program such as " +           "llvm-bcanalyzer.\n";      return;    } @@ -2113,15 +2203,16 @@ void llvm::printRawClangAST(const ObjectFile *Obj) {  }  static void printFaultMaps(const ObjectFile *Obj) { -  const char *FaultMapSectionName = nullptr; +  StringRef FaultMapSectionName;    if (isa<ELFObjectFileBase>(Obj)) {      FaultMapSectionName = ".llvm_faultmaps";    } else if (isa<MachOObjectFile>(Obj)) {      FaultMapSectionName = "__llvm_faultmaps";    } else { -    errs() << "This operation is only currently supported " -              "for ELF and Mach-O executable files.\n"; +    WithColor::error(errs(), ToolName) +        << "This operation is only currently supported " +           "for ELF and Mach-O executable files.\n";      return;    } @@ -2152,42 +2243,44 @@ static void printFaultMaps(const ObjectFile *Obj) {    outs() << FMP;  } -static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) { -  if (o->isELF()) { -    printELFFileHeader(o); -    return printELFDynamicSection(o); +static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) { +  if (O->isELF()) { +    printELFFileHeader(O); +    return printELFDynamicSection(O);    } -  if (o->isCOFF()) -    return printCOFFFileHeader(o); -  if (o->isWasm()) -    return printWasmFileHeader(o); -  if (o->isMachO()) { -    printMachOFileHeader(o); -    if (!onlyFirst) -      printMachOLoadCommands(o); +  if (O->isCOFF()) +    return printCOFFFileHeader(O); +  if (O->isWasm()) +    return printWasmFileHeader(O); +  if (O->isMachO()) { +    printMachOFileHeader(O); +    if (!OnlyFirst) +      printMachOLoadCommands(O);      return;    } -  report_error(o->getFileName(), "Invalid/Unsupported object file format"); +  report_error(O->getFileName(), "Invalid/Unsupported object file format");  } -static void printFileHeaders(const ObjectFile *o) { -  if (!o->isELF() && !o->isCOFF()) -    report_error(o->getFileName(), "Invalid/Unsupported object file format"); +static void printFileHeaders(const ObjectFile *O) { +  if (!O->isELF() && !O->isCOFF()) +    report_error(O->getFileName(), "Invalid/Unsupported object file format"); -  Triple::ArchType AT = o->getArch(); +  Triple::ArchType AT = O->getArch();    outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n"; -  Expected<uint64_t> StartAddrOrErr = o->getStartAddress(); +  Expected<uint64_t> StartAddrOrErr = O->getStartAddress();    if (!StartAddrOrErr) -    report_error(o->getFileName(), StartAddrOrErr.takeError()); +    report_error(O->getFileName(), StartAddrOrErr.takeError()); + +  StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; +  uint64_t Address = StartAddrOrErr.get();    outs() << "start address: " -         << format("0x%0*x", o->getBytesInAddress(), StartAddrOrErr.get()) -         << "\n"; +         << "0x" << format(Fmt.data(), Address) << "\n\n";  }  static void printArchiveChild(StringRef Filename, const Archive::Child &C) {    Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();    if (!ModeOrErr) { -    errs() << "ill-formed archive entry.\n"; +    WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";      consumeError(ModeOrErr.takeError());      return;    } @@ -2248,55 +2341,55 @@ static void printArchiveChild(StringRef Filename, const Archive::Child &C) {    outs() << Name << "\n";  } -static void DumpObject(ObjectFile *o, const Archive *a = nullptr, -                       const Archive::Child *c = nullptr) { -  StringRef ArchiveName = a != nullptr ? a->getFileName() : ""; +static void dumpObject(ObjectFile *O, const Archive *A = nullptr, +                       const Archive::Child *C = nullptr) {    // Avoid other output when using a raw option.    if (!RawClangAST) {      outs() << '\n'; -    if (a) -      outs() << a->getFileName() << "(" << o->getFileName() << ")"; +    if (A) +      outs() << A->getFileName() << "(" << O->getFileName() << ")";      else -      outs() << o->getFileName(); -    outs() << ":\tfile format " << o->getFileFormatName() << "\n\n"; +      outs() << O->getFileName(); +    outs() << ":\tfile format " << O->getFileFormatName() << "\n\n";    } -  if (ArchiveHeaders && !MachOOpt) -    printArchiveChild(a->getFileName(), *c); +  StringRef ArchiveName = A ? A->getFileName() : ""; +  if (FileHeaders) +    printFileHeaders(O); +  if (ArchiveHeaders && !MachOOpt && C) +    printArchiveChild(ArchiveName, *C);    if (Disassemble) -    DisassembleObject(o, Relocations); +    disassembleObject(O, Relocations);    if (Relocations && !Disassemble) -    PrintRelocations(o); +    printRelocations(O);    if (DynamicRelocations) -    PrintDynamicRelocations(o); +    printDynamicRelocations(O);    if (SectionHeaders) -    PrintSectionHeaders(o); +    printSectionHeaders(O);    if (SectionContents) -    PrintSectionContents(o); +    printSectionContents(O);    if (SymbolTable) -    PrintSymbolTable(o, ArchiveName); +    printSymbolTable(O, ArchiveName);    if (UnwindInfo) -    PrintUnwindInfo(o); +    printUnwindInfo(O);    if (PrivateHeaders || FirstPrivateHeader) -    printPrivateFileHeaders(o, FirstPrivateHeader); -  if (FileHeaders) -    printFileHeaders(o); +    printPrivateFileHeaders(O, FirstPrivateHeader);    if (ExportsTrie) -    printExportsTrie(o); +    printExportsTrie(O);    if (Rebase) -    printRebaseTable(o); +    printRebaseTable(O);    if (Bind) -    printBindTable(o); +    printBindTable(O);    if (LazyBind) -    printLazyBindTable(o); +    printLazyBindTable(O);    if (WeakBind) -    printWeakBindTable(o); +    printWeakBindTable(O);    if (RawClangAST) -    printRawClangAST(o); +    printRawClangAST(O);    if (PrintFaultMaps) -    printFaultMaps(o); +    printFaultMaps(O);    if (DwarfDumpType != DIDT_Null) { -    std::unique_ptr<DIContext> DICtx = DWARFContext::create(*o); +    std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);      // Dump the complete DWARF structure.      DIDumpOptions DumpOpts;      DumpOpts.DumpType = DwarfDumpType; @@ -2304,7 +2397,7 @@ static void DumpObject(ObjectFile *o, const Archive *a = nullptr,    }  } -static void DumpObject(const COFFImportFile *I, const Archive *A, +static void dumpObject(const COFFImportFile *I, const Archive *A,                         const Archive::Child *C = nullptr) {    StringRef ArchiveName = A ? A->getFileName() : ""; @@ -2315,41 +2408,40 @@ static void DumpObject(const COFFImportFile *I, const Archive *A,             << ":\tfile format COFF-import-file"             << "\n\n"; -  if (ArchiveHeaders && !MachOOpt) -    printArchiveChild(A->getFileName(), *C); +  if (ArchiveHeaders && !MachOOpt && C) +    printArchiveChild(ArchiveName, *C);    if (SymbolTable)      printCOFFSymbolTable(I);  }  /// Dump each object file in \a a; -static void DumpArchive(const Archive *a) { +static void dumpArchive(const Archive *A) {    Error Err = Error::success(); -  for (auto &C : a->children(Err)) { +  for (auto &C : A->children(Err)) {      Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();      if (!ChildOrErr) {        if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) -        report_error(a->getFileName(), C, std::move(E)); +        report_error(A->getFileName(), C, std::move(E));        continue;      } -    if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) -      DumpObject(o, a, &C); +    if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get())) +      dumpObject(O, A, &C);      else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get())) -      DumpObject(I, a, &C); +      dumpObject(I, A, &C);      else -      report_error(a->getFileName(), object_error::invalid_file_type); +      report_error(A->getFileName(), object_error::invalid_file_type);    }    if (Err) -    report_error(a->getFileName(), std::move(Err)); +    report_error(A->getFileName(), std::move(Err));  }  /// Open file and figure out how to dump it. -static void DumpInput(StringRef file) { - +static void dumpInput(StringRef file) {    // If we are using the Mach-O specific object file parser, then let it parse    // the file and process the command line options.  So the -arch flags can    // be used to select specific slices, etc.    if (MachOOpt) { -    ParseInputMachO(file); +    parseInputMachO(file);      return;    } @@ -2359,10 +2451,12 @@ static void DumpInput(StringRef file) {      report_error(file, BinaryOrErr.takeError());    Binary &Binary = *BinaryOrErr.get().getBinary(); -  if (Archive *a = dyn_cast<Archive>(&Binary)) -    DumpArchive(a); -  else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary)) -    DumpObject(o); +  if (Archive *A = dyn_cast<Archive>(&Binary)) +    dumpArchive(A); +  else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary)) +    dumpObject(O); +  else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary)) +    parseInputMachO(UB);    else      report_error(file, object_error::invalid_file_type);  } @@ -2379,24 +2473,20 @@ int main(int argc, char **argv) {    cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);    cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); -  TripleName = Triple::normalize(TripleName);    ToolName = argv[0];    // Defaults to a.out if no filenames specified. -  if (InputFilenames.size() == 0) +  if (InputFilenames.empty())      InputFilenames.push_back("a.out");    if (AllHeaders) -    PrivateHeaders = Relocations = SectionHeaders = SymbolTable = true; +    FileHeaders = PrivateHeaders = Relocations = SectionHeaders = SymbolTable = +        true;    if (DisassembleAll || PrintSource || PrintLines)      Disassemble = true; -  if (Demangle.getValue() != "none" && Demangle.getValue() != "" && -      Demangle.getValue() != "itanium") -    warn("Unsupported demangling style"); -    if (!Disassemble        && !Relocations        && !DynamicRelocations @@ -2422,7 +2512,7 @@ int main(int argc, char **argv) {        && !(DylibsUsed && MachOOpt)        && !(DylibId && MachOOpt)        && !(ObjcMetaData && MachOOpt) -      && !(FilterSections.size() != 0 && MachOOpt) +      && !(!FilterSections.empty() && MachOOpt)        && !PrintFaultMaps        && DwarfDumpType == DIDT_Null) {      cl::PrintHelpMessage(); @@ -2432,7 +2522,7 @@ int main(int argc, char **argv) {    DisasmFuncsSet.insert(DisassembleFunctions.begin(),                          DisassembleFunctions.end()); -  llvm::for_each(InputFilenames, DumpInput); +  llvm::for_each(InputFilenames, dumpInput);    return EXIT_SUCCESS;  } | 
