diff options
Diffstat (limited to 'tools/llvm-objdump')
-rw-r--r-- | tools/llvm-objdump/COFFDump.cpp | 77 | ||||
-rw-r--r-- | tools/llvm-objdump/ELFDump.cpp | 2 | ||||
-rw-r--r-- | tools/llvm-objdump/MachODump.cpp | 375 | ||||
-rw-r--r-- | tools/llvm-objdump/llvm-objdump.cpp | 543 | ||||
-rw-r--r-- | tools/llvm-objdump/llvm-objdump.h | 36 |
5 files changed, 648 insertions, 385 deletions
diff --git a/tools/llvm-objdump/COFFDump.cpp b/tools/llvm-objdump/COFFDump.cpp index 1ba0a68902c9..60b0f5a3cbd1 100644 --- a/tools/llvm-objdump/COFFDump.cpp +++ b/tools/llvm-objdump/COFFDump.cpp @@ -234,15 +234,14 @@ printSEHTable(const COFFObjectFile *Obj, uint32_t TableVA, int Count) { if (Count == 0) return; - const pe32_header *PE32Header; - error(Obj->getPE32Header(PE32Header)); - uint32_t ImageBase = PE32Header->ImageBase; uintptr_t IntPtr = 0; - error(Obj->getVaPtr(TableVA, IntPtr)); + if (std::error_code EC = Obj->getVaPtr(TableVA, IntPtr)) + reportError(errorCodeToError(EC), Obj->getFileName()); + const support::ulittle32_t *P = (const support::ulittle32_t *)IntPtr; outs() << "SEH Table:"; for (int I = 0; I < Count; ++I) - outs() << format(" 0x%x", P[I] + ImageBase); + outs() << format(" 0x%x", P[I] + Obj->getPE32Header()->ImageBase); outs() << "\n\n"; } @@ -268,22 +267,24 @@ static void printTLSDirectoryT(const coff_tls_directory<T> *TLSDir) { } static void printTLSDirectory(const COFFObjectFile *Obj) { - const pe32_header *PE32Header; - error(Obj->getPE32Header(PE32Header)); - - const pe32plus_header *PE32PlusHeader; - error(Obj->getPE32PlusHeader(PE32PlusHeader)); + const pe32_header *PE32Header = Obj->getPE32Header(); + const pe32plus_header *PE32PlusHeader = Obj->getPE32PlusHeader(); // Skip if it's not executable. if (!PE32Header && !PE32PlusHeader) return; const data_directory *DataDir; - error(Obj->getDataDirectory(COFF::TLS_TABLE, DataDir)); - uintptr_t IntPtr = 0; + if (std::error_code EC = Obj->getDataDirectory(COFF::TLS_TABLE, DataDir)) + reportError(errorCodeToError(EC), Obj->getFileName()); + if (DataDir->RelativeVirtualAddress == 0) return; - error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr)); + + uintptr_t IntPtr = 0; + if (std::error_code EC = + Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr)) + reportError(errorCodeToError(EC), Obj->getFileName()); if (PE32Header) { auto *TLSDir = reinterpret_cast<const coff_tls_directory32 *>(IntPtr); @@ -298,9 +299,7 @@ static void printTLSDirectory(const COFFObjectFile *Obj) { static void printLoadConfiguration(const COFFObjectFile *Obj) { // Skip if it's not executable. - const pe32_header *PE32Header; - error(Obj->getPE32Header(PE32Header)); - if (!PE32Header) + if (!Obj->getPE32Header()) return; // Currently only x86 is supported @@ -308,11 +307,18 @@ static void printLoadConfiguration(const COFFObjectFile *Obj) { return; const data_directory *DataDir; - error(Obj->getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataDir)); + + if (std::error_code EC = + Obj->getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataDir)) + reportError(errorCodeToError(EC), Obj->getFileName()); + uintptr_t IntPtr = 0; if (DataDir->RelativeVirtualAddress == 0) return; - error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr)); + + if (std::error_code EC = + Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr)) + reportError(errorCodeToError(EC), Obj->getFileName()); auto *LoadConf = reinterpret_cast<const coff_load_configuration32 *>(IntPtr); outs() << "Load configuration:" @@ -442,8 +448,7 @@ static bool getPDataSection(const COFFObjectFile *Obj, std::vector<RelocationRef> &Rels, const RuntimeFunction *&RFStart, int &NumRFs) { for (const SectionRef &Section : Obj->sections()) { - StringRef Name; - error(Section.getName(Name)); + StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName()); if (Name != ".pdata") continue; @@ -455,7 +460,9 @@ static bool getPDataSection(const COFFObjectFile *Obj, llvm::sort(Rels, isRelocAddressLess); ArrayRef<uint8_t> Contents; - error(Obj->getSectionContents(Pdata, Contents)); + if (Error E = Obj->getSectionContents(Pdata, Contents)) + reportError(std::move(E), Obj->getFileName()); + if (Contents.empty()) continue; @@ -571,10 +578,12 @@ static void printRuntimeFunctionRels(const COFFObjectFile *Obj, ArrayRef<uint8_t> XContents; uint64_t UnwindInfoOffset = 0; - error(getSectionContents( - Obj, Rels, SectionOffset + - /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8, - XContents, UnwindInfoOffset)); + if (Error E = getSectionContents( + Obj, Rels, + SectionOffset + + /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8, + XContents, UnwindInfoOffset)) + reportError(std::move(E), Obj->getFileName()); if (XContents.empty()) return; @@ -650,9 +659,12 @@ void printCOFFSymbolTable(const object::COFFImportFile *i) { void printCOFFSymbolTable(const COFFObjectFile *coff) { for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) { Expected<COFFSymbolRef> Symbol = coff->getSymbol(SI); + if (!Symbol) + reportError(Symbol.takeError(), coff->getFileName()); + StringRef Name; - error(Symbol.takeError()); - error(coff->getSymbolName(*Symbol, Name)); + if (std::error_code EC = coff->getSymbolName(*Symbol, Name)) + reportError(errorCodeToError(EC), coff->getFileName()); outs() << "[" << format("%2d", SI) << "]" << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")" @@ -682,7 +694,9 @@ void printCOFFSymbolTable(const COFFObjectFile *coff) { for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) { if (Symbol->isSectionDefinition()) { const coff_aux_section_definition *asd; - error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)); + if (std::error_code EC = + coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)) + reportError(errorCodeToError(EC), coff->getFileName()); int32_t AuxNumber = asd->getNumber(Symbol->isBigObj()); @@ -697,7 +711,8 @@ void printCOFFSymbolTable(const COFFObjectFile *coff) { , unsigned(asd->Selection)); } else if (Symbol->isFileRecord()) { const char *FileName; - error(coff->getAuxSymbol<char>(SI + 1, FileName)); + if (std::error_code EC = coff->getAuxSymbol<char>(SI + 1, FileName)) + reportError(errorCodeToError(EC), coff->getFileName()); StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() * coff->getSymbolTableEntrySize()); @@ -707,7 +722,9 @@ void printCOFFSymbolTable(const COFFObjectFile *coff) { break; } else if (Symbol->isWeakExternal()) { const coff_aux_weak_external *awe; - error(coff->getAuxSymbol<coff_aux_weak_external>(SI + 1, awe)); + if (std::error_code EC = + coff->getAuxSymbol<coff_aux_weak_external>(SI + 1, awe)) + reportError(errorCodeToError(EC), coff->getFileName()); outs() << "AUX " << format("indx %d srch %d\n", static_cast<uint32_t>(awe->TagIndex), diff --git a/tools/llvm-objdump/ELFDump.cpp b/tools/llvm-objdump/ELFDump.cpp index 9c4d67d0f1bd..93d070eee16c 100644 --- a/tools/llvm-objdump/ELFDump.cpp +++ b/tools/llvm-objdump/ELFDump.cpp @@ -178,7 +178,7 @@ void printDynamicSection(const ELFFile<ELFT> *Elf, StringRef Filename) { outs() << (Data + Dyn.d_un.d_val) << "\n"; continue; } - warn(toString(StrTabOrErr.takeError())); + reportWarning(toString(StrTabOrErr.takeError()), Filename); consumeError(StrTabOrErr.takeError()); } outs() << format(Fmt, (uint64_t)Dyn.d_un.d_val); diff --git a/tools/llvm-objdump/MachODump.cpp b/tools/llvm-objdump/MachODump.cpp index 58ff7be4543c..e4684d0f1601 100644 --- a/tools/llvm-objdump/MachODump.cpp +++ b/tools/llvm-objdump/MachODump.cpp @@ -236,11 +236,11 @@ struct SymbolSorter { bool operator()(const SymbolRef &A, const SymbolRef &B) { Expected<SymbolRef::Type> ATypeOrErr = A.getType(); if (!ATypeOrErr) - report_error(ATypeOrErr.takeError(), A.getObject()->getFileName()); + reportError(ATypeOrErr.takeError(), A.getObject()->getFileName()); SymbolRef::Type AType = *ATypeOrErr; Expected<SymbolRef::Type> BTypeOrErr = B.getType(); if (!BTypeOrErr) - report_error(BTypeOrErr.takeError(), B.getObject()->getFileName()); + reportError(BTypeOrErr.takeError(), B.getObject()->getFileName()); SymbolRef::Type BType = *BTypeOrErr; uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue(); uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue(); @@ -371,11 +371,8 @@ static void getSectionsAndSymbols(MachOObjectFile *MachOObj, Symbols.push_back(Symbol); } - for (const SectionRef &Section : MachOObj->sections()) { - StringRef SectName; - Section.getName(SectName); + for (const SectionRef &Section : MachOObj->sections()) Sections.push_back(Section); - } bool BaseSegmentAddressSet = false; for (const auto &Command : MachOObj->load_commands()) { @@ -393,10 +390,40 @@ static void getSectionsAndSymbols(MachOObjectFile *MachOObj, BaseSegmentAddressSet = true; BaseSegmentAddress = SLC.vmaddr; } + } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { + MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command); + StringRef SegName = SLC.segname; + if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") { + BaseSegmentAddressSet = true; + BaseSegmentAddress = SLC.vmaddr; + } } } } +static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes, + DiceTable &Dices, uint64_t &InstSize) { + // Check the data in code table here to see if this is data not an + // instruction to be disassembled. + DiceTable Dice; + Dice.push_back(std::make_pair(PC, DiceRef())); + dice_table_iterator DTI = + std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(), + compareDiceTableEntries); + if (DTI != Dices.end()) { + uint16_t Length; + DTI->second.getLength(Length); + uint16_t Kind; + DTI->second.getKind(Kind); + InstSize = DumpDataInCode(bytes, Length, Kind); + if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) && + (PC == (DTI->first + Length - 1)) && (Length & 1)) + InstSize++; + return true; + } + return false; +} + static void printRelocationTargetName(const MachOObjectFile *O, const MachO::any_relocation_info &RE, raw_string_ostream &Fmt) { @@ -419,13 +446,11 @@ static void printRelocationTargetName(const MachOObjectFile *O, // If we couldn't find a symbol that this relocation refers to, try // to find a section beginning instead. for (const SectionRef &Section : ToolSectionFilter(*O)) { - StringRef Name; uint64_t Addr = Section.getAddress(); if (Addr != Val) continue; - if (std::error_code EC = Section.getName(Name)) - report_error(errorCodeToError(EC), O->getFileName()); - Fmt << Name; + StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName()); + Fmt << NameOrErr; return; } @@ -458,10 +483,14 @@ static void printRelocationTargetName(const MachOObjectFile *O, --I; advance(SI, 1); } - if (SI == O->section_end()) + if (SI == O->section_end()) { Fmt << Val << " (?,?)"; - else - SI->getName(S); + } else { + if (Expected<StringRef> NameOrErr = SI->getName()) + S = *NameOrErr; + else + consumeError(NameOrErr.takeError()); + } } Fmt << S; @@ -504,8 +533,8 @@ Error getMachORelocationValueString(const MachOObjectFile *Obj, // NOTE: Scattered relocations don't exist on x86_64. unsigned RType = Obj->getAnyRelocationType(RENext); if (RType != MachO::X86_64_RELOC_UNSIGNED) - report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after " - "X86_64_RELOC_SUBTRACTOR."); + reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after " + "X86_64_RELOC_SUBTRACTOR."); // The X86_64_RELOC_UNSIGNED contains the minuend symbol; // X86_64_RELOC_SUBTRACTOR contains the subtrahend. @@ -553,8 +582,8 @@ Error getMachORelocationValueString(const MachOObjectFile *Obj, unsigned RType = Obj->getAnyRelocationType(RENext); if (RType != MachO::GENERIC_RELOC_PAIR) - report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after " - "GENERIC_RELOC_SECTDIFF."); + reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after " + "GENERIC_RELOC_SECTDIFF."); printRelocationTargetName(Obj, RE, Fmt); Fmt << "-"; @@ -574,8 +603,8 @@ Error getMachORelocationValueString(const MachOObjectFile *Obj, // GENERIC_RELOC_PAIR. unsigned RType = Obj->getAnyRelocationType(RENext); if (RType != MachO::GENERIC_RELOC_PAIR) - report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after " - "GENERIC_RELOC_LOCAL_SECTDIFF."); + reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after " + "GENERIC_RELOC_LOCAL_SECTDIFF."); printRelocationTargetName(Obj, RE, Fmt); Fmt << "-"; @@ -614,8 +643,8 @@ Error getMachORelocationValueString(const MachOObjectFile *Obj, // ARM_RELOC_PAIR. unsigned RType = Obj->getAnyRelocationType(RENext); if (RType != MachO::ARM_RELOC_PAIR) - report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after " - "ARM_RELOC_HALF"); + reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after " + "ARM_RELOC_HALF"); // NOTE: The half of the target virtual address is stashed in the // address field of the secondary relocation, but we can't reverse @@ -1501,7 +1530,12 @@ static void DumpLiteralPointerSection(MachOObjectFile *O, uint64_t SectSize = Sect->getSize(); StringRef SectName; - Sect->getName(SectName); + Expected<StringRef> SectNameOrErr = Sect->getName(); + if (SectNameOrErr) + SectName = *SectNameOrErr; + else + consumeError(SectNameOrErr.takeError()); + DataRefImpl Ref = Sect->getRawDataRefImpl(); StringRef SegmentName = O->getSectionFinalSegmentName(Ref); outs() << SegmentName << ":" << SectName << ":"; @@ -1713,7 +1747,12 @@ static void DumpSectionContents(StringRef Filename, MachOObjectFile *O, } for (const SectionRef &Section : O->sections()) { StringRef SectName; - Section.getName(SectName); + Expected<StringRef> SecNameOrErr = Section.getName(); + if (SecNameOrErr) + SectName = *SecNameOrErr; + else + consumeError(SecNameOrErr.takeError()); + DataRefImpl Ref = Section.getRawDataRefImpl(); StringRef SegName = O->getSectionFinalSegmentName(Ref); if ((DumpSegName.empty() || SegName == DumpSegName) && @@ -1809,7 +1848,12 @@ static void DumpInfoPlistSectionContents(StringRef Filename, MachOObjectFile *O) { for (const SectionRef &Section : O->sections()) { StringRef SectName; - Section.getName(SectName); + Expected<StringRef> SecNameOrErr = Section.getName(); + if (SecNameOrErr) + SectName = *SecNameOrErr; + else + consumeError(SecNameOrErr.takeError()); + DataRefImpl Ref = Section.getRawDataRefImpl(); StringRef SegName = O->getSectionFinalSegmentName(Ref); if (SegName == "__TEXT" && SectName == "__info_plist") { @@ -1901,12 +1945,16 @@ static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF, // the error message. if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo) if (Error Err = MachOOF->checkSymbolTable()) - report_error(std::move(Err), ArchiveName, FileName, ArchitectureName); + reportError(std::move(Err), FileName, ArchiveName, ArchitectureName); if (DisassembleAll) { for (const SectionRef &Section : MachOOF->sections()) { StringRef SectName; - Section.getName(SectName); + if (Expected<StringRef> NameOrErr = Section.getName()) + SectName = *NameOrErr; + else + consumeError(NameOrErr.takeError()); + if (SectName.equals("__text")) { DataRefImpl Ref = Section.getRawDataRefImpl(); StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref); @@ -2151,7 +2199,7 @@ static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB, outs() << " offset " << OFA.getOffset(); if (OFA.getOffset() > size) outs() << " (past end of file)"; - if (OFA.getOffset() % (1 << OFA.getAlign()) != 0) + if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0) outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")"; outs() << "\n"; outs() << " size " << OFA.getSize(); @@ -2165,12 +2213,14 @@ static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB, } static void printArchiveChild(StringRef Filename, const Archive::Child &C, - bool verbose, bool print_offset, + size_t ChildIndex, bool verbose, + bool print_offset, StringRef ArchitectureName = StringRef()) { if (print_offset) outs() << C.getChildOffset() << "\t"; sys::fs::perms Mode = - unwrapOrError(C.getAccessMode(), Filename, C, ArchitectureName); + unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex), + Filename, ArchitectureName); if (verbose) { // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG. // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG. @@ -2188,11 +2238,14 @@ static void printArchiveChild(StringRef Filename, const Archive::Child &C, outs() << format("0%o ", Mode); } - outs() << format( - "%3d/%-3d %5" PRId64 " ", - unwrapOrError(C.getUID(), Filename, C, ArchitectureName), - unwrapOrError(C.getGID(), Filename, C, ArchitectureName), - unwrapOrError(C.getRawSize(), Filename, C, ArchitectureName)); + outs() << format("%3d/%-3d %5" PRId64 " ", + unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex), + Filename, ArchitectureName), + unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex), + Filename, ArchitectureName), + unwrapOrError(C.getRawSize(), + getFileNameForError(C, ChildIndex), Filename, + ArchitectureName)); StringRef RawLastModified = C.getRawLastModified(); if (verbose) { @@ -2215,14 +2268,17 @@ static void printArchiveChild(StringRef Filename, const Archive::Child &C, Expected<StringRef> NameOrErr = C.getName(); if (!NameOrErr) { consumeError(NameOrErr.takeError()); - outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName) + outs() << unwrapOrError(C.getRawName(), + getFileNameForError(C, ChildIndex), Filename, + ArchitectureName) << "\n"; } else { StringRef Name = NameOrErr.get(); outs() << Name << "\n"; } } else { - outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName) + outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex), + Filename, ArchitectureName) << "\n"; } } @@ -2231,11 +2287,13 @@ static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose, bool print_offset, StringRef ArchitectureName = StringRef()) { Error Err = Error::success(); + size_t I = 0; for (const auto &C : A->children(Err, false)) - printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName); + printArchiveChild(Filename, C, I++, verbose, print_offset, + ArchitectureName); if (Err) - report_error(std::move(Err), StringRef(), Filename, ArchitectureName); + reportError(std::move(Err), Filename, "", ArchitectureName); } static bool ValidateArchFlags() { @@ -2267,7 +2325,7 @@ void parseInputMachO(StringRef Filename) { Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename); if (!BinaryOrErr) { if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError())) - report_error(std::move(E), Filename); + reportError(std::move(E), Filename); else outs() << Filename << ": is not an object file\n"; return; @@ -2280,11 +2338,13 @@ void parseInputMachO(StringRef Filename) { printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets); Error Err = Error::success(); + unsigned I = -1; for (auto &C : A->children(Err)) { + ++I; Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); if (!ChildOrErr) { if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) - report_error(std::move(E), Filename, C); + reportError(std::move(E), getFileNameForError(C, I), Filename); continue; } if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) { @@ -2294,7 +2354,7 @@ void parseInputMachO(StringRef Filename) { } } if (Err) - report_error(std::move(Err), Filename); + reportError(std::move(Err), Filename); return; } if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) { @@ -2346,7 +2406,7 @@ void parseInputMachO(MachOUniversalBinary *UB) { ProcessMachO(Filename, MachOOF, "", ArchitectureName); } else if (Error E = isNotObjectErrorInvalidFileType( ObjOrErr.takeError())) { - report_error(std::move(E), Filename, StringRef(), ArchitectureName); + reportError(std::move(E), "", Filename, ArchitectureName); continue; } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { @@ -2359,11 +2419,15 @@ void parseInputMachO(MachOUniversalBinary *UB) { printArchiveHeaders(Filename, A.get(), !NonVerbose, ArchiveMemberOffsets, ArchitectureName); Error Err = Error::success(); + unsigned I = -1; for (auto &C : A->children(Err)) { + ++I; Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); if (!ChildOrErr) { - if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) - report_error(std::move(E), Filename, C, ArchitectureName); + if (Error E = + isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) + reportError(std::move(E), getFileNameForError(C, I), Filename, + ArchitectureName); continue; } if (MachOObjectFile *O = @@ -2371,12 +2435,13 @@ void parseInputMachO(MachOUniversalBinary *UB) { ProcessMachO(Filename, O, O->getFileName(), ArchitectureName); } if (Err) - report_error(std::move(Err), Filename); + reportError(std::move(Err), Filename); } else { consumeError(AOrErr.takeError()); - error("Mach-O universal file: " + Filename + " for " + - "architecture " + StringRef(I->getArchFlagName()) + - " is not a Mach-O file or an archive file"); + reportError(Filename, + "Mach-O universal file for architecture " + + StringRef(I->getArchFlagName()) + + " is not a Mach-O file or an archive file"); } } } @@ -2406,7 +2471,7 @@ void parseInputMachO(MachOUniversalBinary *UB) { ProcessMachO(Filename, MachOOF); } else if (Error E = isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) { - report_error(std::move(E), Filename); + reportError(std::move(E), Filename); } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { std::unique_ptr<Archive> &A = *AOrErr; @@ -2415,12 +2480,14 @@ void parseInputMachO(MachOUniversalBinary *UB) { printArchiveHeaders(Filename, A.get(), !NonVerbose, ArchiveMemberOffsets); Error Err = Error::success(); + unsigned I = -1; for (auto &C : A->children(Err)) { + ++I; Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); if (!ChildOrErr) { if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) - report_error(std::move(E), Filename, C); + reportError(std::move(E), getFileNameForError(C, I), Filename); continue; } if (MachOObjectFile *O = @@ -2428,12 +2495,12 @@ void parseInputMachO(MachOUniversalBinary *UB) { ProcessMachO(Filename, O, O->getFileName()); } if (Err) - report_error(std::move(Err), Filename); + reportError(std::move(Err), Filename); } else { consumeError(AOrErr.takeError()); - error("Mach-O universal file: " + Filename + " for architecture " + - StringRef(I->getArchFlagName()) + - " is not a Mach-O file or an archive file"); + reportError(Filename, "Mach-O universal file for architecture " + + StringRef(I->getArchFlagName()) + + " is not a Mach-O file or an archive file"); } return; } @@ -2455,7 +2522,7 @@ void parseInputMachO(MachOUniversalBinary *UB) { ProcessMachO(Filename, MachOOF, "", ArchitectureName); } else if (Error E = isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) { - report_error(std::move(E), StringRef(), Filename, ArchitectureName); + reportError(std::move(E), Filename, "", ArchitectureName); } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { std::unique_ptr<Archive> &A = *AOrErr; outs() << "Archive : " << Filename; @@ -2466,11 +2533,14 @@ void parseInputMachO(MachOUniversalBinary *UB) { printArchiveHeaders(Filename, A.get(), !NonVerbose, ArchiveMemberOffsets, ArchitectureName); Error Err = Error::success(); + unsigned I = -1; for (auto &C : A->children(Err)) { + ++I; Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); if (!ChildOrErr) { if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) - report_error(std::move(E), Filename, C, ArchitectureName); + reportError(std::move(E), getFileNameForError(C, I), Filename, + ArchitectureName); continue; } if (MachOObjectFile *O = @@ -2481,12 +2551,12 @@ void parseInputMachO(MachOUniversalBinary *UB) { } } if (Err) - report_error(std::move(Err), Filename); + reportError(std::move(Err), Filename); } else { consumeError(AOrErr.takeError()); - error("Mach-O universal file: " + Filename + " for architecture " + - StringRef(I->getArchFlagName()) + - " is not a Mach-O file or an archive file"); + reportError(Filename, "Mach-O universal file for architecture " + + StringRef(I->getArchFlagName()) + + " is not a Mach-O file or an archive file"); } } } @@ -3083,7 +3153,7 @@ static void method_reference(struct DisassembleInfo *info, if (strcmp(*ReferenceName, "_objc_msgSend") == 0) { if (info->selector_name != nullptr) { if (info->class_name != nullptr) { - info->method = llvm::make_unique<char[]>( + info->method = std::make_unique<char[]>( 5 + strlen(info->class_name) + strlen(info->selector_name)); char *method = info->method.get(); if (method != nullptr) { @@ -3097,7 +3167,7 @@ static void method_reference(struct DisassembleInfo *info, } } else { info->method = - llvm::make_unique<char[]>(9 + strlen(info->selector_name)); + std::make_unique<char[]>(9 + strlen(info->selector_name)); char *method = info->method.get(); if (method != nullptr) { if (Arch == Triple::x86_64) @@ -3117,7 +3187,7 @@ static void method_reference(struct DisassembleInfo *info, } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) { if (info->selector_name != nullptr) { info->method = - llvm::make_unique<char[]>(17 + strlen(info->selector_name)); + std::make_unique<char[]>(17 + strlen(info->selector_name)); char *method = info->method.get(); if (method != nullptr) { if (Arch == Triple::x86_64) @@ -3217,7 +3287,13 @@ static const char *get_pointer_64(uint64_t Address, uint32_t &offset, continue; if (objc_only) { StringRef SectName; - ((*(info->Sections))[SectIdx]).getName(SectName); + Expected<StringRef> SecNameOrErr = + ((*(info->Sections))[SectIdx]).getName(); + if (SecNameOrErr) + SectName = *SecNameOrErr; + else + consumeError(SecNameOrErr.takeError()); + DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl(); StringRef SegName = info->O->getSectionFinalSegmentName(Ref); if (SegName != "__OBJC" && SectName != "__cstring") @@ -4009,7 +4085,12 @@ static const SectionRef get_section(MachOObjectFile *O, const char *segname, const char *sectname) { for (const SectionRef &Section : O->sections()) { StringRef SectName; - Section.getName(SectName); + Expected<StringRef> SecNameOrErr = Section.getName(); + if (SecNameOrErr) + SectName = *SecNameOrErr; + else + consumeError(SecNameOrErr.takeError()); + DataRefImpl Ref = Section.getRawDataRefImpl(); StringRef SegName = O->getSectionFinalSegmentName(Ref); if (SegName == segname && SectName == sectname) @@ -4026,7 +4107,12 @@ walk_pointer_list_64(const char *listname, const SectionRef S, return; StringRef SectName; - S.getName(SectName); + Expected<StringRef> SecNameOrErr = S.getName(); + if (SecNameOrErr) + SectName = *SecNameOrErr; + else + consumeError(SecNameOrErr.takeError()); + DataRefImpl Ref = S.getRawDataRefImpl(); StringRef SegName = O->getSectionFinalSegmentName(Ref); outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; @@ -4075,8 +4161,7 @@ walk_pointer_list_32(const char *listname, const SectionRef S, if (S == SectionRef()) return; - StringRef SectName; - S.getName(SectName); + StringRef SectName = unwrapOrError(S.getName(), O->getFileName()); DataRefImpl Ref = S.getRawDataRefImpl(); StringRef SegName = O->getSectionFinalSegmentName(Ref); outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; @@ -5750,7 +5835,12 @@ static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) { return; StringRef SectName; - S.getName(SectName); + Expected<StringRef> SecNameOrErr = S.getName(); + if (SecNameOrErr) + SectName = *SecNameOrErr; + else + consumeError(SecNameOrErr.takeError()); + DataRefImpl Ref = S.getRawDataRefImpl(); StringRef SegName = info->O->getSectionFinalSegmentName(Ref); outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; @@ -5813,7 +5903,12 @@ static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) { return; StringRef SectName; - S.getName(SectName); + Expected<StringRef> SecNameOrErr = S.getName(); + if (SecNameOrErr) + SectName = *SecNameOrErr; + else + consumeError(SecNameOrErr.takeError()); + DataRefImpl Ref = S.getRawDataRefImpl(); StringRef SegName = info->O->getSectionFinalSegmentName(Ref); outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; @@ -5859,7 +5954,12 @@ static void print_image_info64(SectionRef S, struct DisassembleInfo *info) { return; StringRef SectName; - S.getName(SectName); + Expected<StringRef> SecNameOrErr = S.getName(); + if (SecNameOrErr) + SectName = *SecNameOrErr; + else + consumeError(SecNameOrErr.takeError()); + DataRefImpl Ref = S.getRawDataRefImpl(); StringRef SegName = info->O->getSectionFinalSegmentName(Ref); outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; @@ -5916,7 +6016,12 @@ static void print_image_info32(SectionRef S, struct DisassembleInfo *info) { return; StringRef SectName; - S.getName(SectName); + Expected<StringRef> SecNameOrErr = S.getName(); + if (SecNameOrErr) + SectName = *SecNameOrErr; + else + consumeError(SecNameOrErr.takeError()); + DataRefImpl Ref = S.getRawDataRefImpl(); StringRef SegName = info->O->getSectionFinalSegmentName(Ref); outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; @@ -5966,7 +6071,12 @@ static void print_image_info(SectionRef S, struct DisassembleInfo *info) { const char *r; StringRef SectName; - S.getName(SectName); + Expected<StringRef> SecNameOrErr = S.getName(); + if (SecNameOrErr) + SectName = *SecNameOrErr; + else + consumeError(SecNameOrErr.takeError()); + DataRefImpl Ref = S.getRawDataRefImpl(); StringRef SegName = info->O->getSectionFinalSegmentName(Ref); outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; @@ -6001,11 +6111,8 @@ static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) { CreateSymbolAddressMap(O, &AddrMap); std::vector<SectionRef> Sections; - for (const SectionRef &Section : O->sections()) { - StringRef SectName; - Section.getName(SectName); + for (const SectionRef &Section : O->sections()) Sections.push_back(Section); - } struct DisassembleInfo info(O, &AddrMap, &Sections, verbose); @@ -6086,11 +6193,8 @@ static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) { CreateSymbolAddressMap(O, &AddrMap); std::vector<SectionRef> Sections; - for (const SectionRef &Section : O->sections()) { - StringRef SectName; - Section.getName(SectName); + for (const SectionRef &Section : O->sections()) Sections.push_back(Section); - } struct DisassembleInfo info(O, &AddrMap, &Sections, verbose); @@ -6184,11 +6288,8 @@ static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) { CreateSymbolAddressMap(O, &AddrMap); std::vector<SectionRef> Sections; - for (const SectionRef &Section : O->sections()) { - StringRef SectName; - Section.getName(SectName); + for (const SectionRef &Section : O->sections()) Sections.push_back(Section); - } struct DisassembleInfo info(O, &AddrMap, &Sections, verbose); @@ -6345,11 +6446,8 @@ static void DumpProtocolSection(MachOObjectFile *O, const char *sect, CreateSymbolAddressMap(O, &AddrMap); std::vector<SectionRef> Sections; - for (const SectionRef &Section : O->sections()) { - StringRef SectName; - Section.getName(SectName); + for (const SectionRef &Section : O->sections()) Sections.push_back(Section); - } struct DisassembleInfo info(O, &AddrMap, &Sections, true); @@ -7203,7 +7301,7 @@ static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, std::vector<SectionRef> Sections; std::vector<SymbolRef> Symbols; SmallVector<uint64_t, 8> FoundFns; - uint64_t BaseSegmentAddress; + uint64_t BaseSegmentAddress = 0; getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns, BaseSegmentAddress); @@ -7242,10 +7340,24 @@ static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, // A separate DSym file path was specified, parse it as a macho file, // get the sections and supply it to the section name parsing machinery. if (!DSYMFile.empty()) { + std::string DSYMPath(DSYMFile); + + // If DSYMPath is a .dSYM directory, append the Mach-O file. + if (llvm::sys::fs::is_directory(DSYMPath) && + llvm::sys::path::extension(DSYMPath) == ".dSYM") { + SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath)); + llvm::sys::path::replace_extension(ShortName, ""); + SmallString<1024> FullPath(DSYMPath); + llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF", + ShortName); + DSYMPath = FullPath.str(); + } + + // Load the file. ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = - MemoryBuffer::getFileOrSTDIN(DSYMFile); + MemoryBuffer::getFileOrSTDIN(DSYMPath); if (std::error_code EC = BufOrErr.getError()) { - report_error(errorCodeToError(EC), DSYMFile); + reportError(errorCodeToError(EC), DSYMPath); return; } @@ -7255,13 +7367,12 @@ static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, Expected<std::unique_ptr<Binary>> BinaryOrErr = createBinary(DSYMBuf.get()->getMemBufferRef()); if (!BinaryOrErr) { - report_error(BinaryOrErr.takeError(), DSYMFile); + reportError(BinaryOrErr.takeError(), DSYMPath); return; } - // We need to keep the Binary elive with the buffer + // We need to keep the Binary alive with the buffer DSYMBinary = std::move(BinaryOrErr.get()); - if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) { // this is a Mach-O object file, use it if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) { @@ -7269,7 +7380,7 @@ static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, } else { WithColor::error(errs(), "llvm-objdump") - << DSYMFile << " is not a Mach-O file type.\n"; + << DSYMPath << " is not a Mach-O file type.\n"; return; } } @@ -7289,19 +7400,19 @@ static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr, &ArchFlag); Expected<std::unique_ptr<MachOObjectFile>> MachDSYM = - UB->getObjectForArch(ArchFlag); + UB->getMachOObjectForArch(ArchFlag); if (!MachDSYM) { - report_error(MachDSYM.takeError(), DSYMFile); + reportError(MachDSYM.takeError(), DSYMPath); return; } - // We need to keep the Binary elive with the buffer + // We need to keep the Binary alive with the buffer DbgObj = &*MachDSYM.get(); DSYMBinary = std::move(*MachDSYM); } else { WithColor::error(errs(), "llvm-objdump") - << DSYMFile << " is not a Mach-O or Universal file type.\n"; + << DSYMPath << " is not a Mach-O or Universal file type.\n"; return; } } @@ -7314,8 +7425,12 @@ static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, outs() << "(" << DisSegName << "," << DisSectName << ") section\n"; for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) { - StringRef SectName; - if (Sections[SectIdx].getName(SectName) || SectName != DisSectName) + Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName(); + if (!SecNameOrErr) { + consumeError(SecNameOrErr.takeError()); + continue; + } + if (*SecNameOrErr != DisSectName) continue; DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl(); @@ -7496,24 +7611,8 @@ static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, if (!NoShowRawInsn || Arch == Triple::arm) outs() << "\t"; - // Check the data in code table here to see if this is data not an - // instruction to be disassembled. - DiceTable Dice; - Dice.push_back(std::make_pair(PC, DiceRef())); - dice_table_iterator DTI = - std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(), - compareDiceTableEntries); - if (DTI != Dices.end()) { - uint16_t Length; - DTI->second.getLength(Length); - uint16_t Kind; - DTI->second.getKind(Kind); - Size = DumpDataInCode(Bytes.data() + Index, Length, Kind); - if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) && - (PC == (DTI->first + Length - 1)) && (Length & 1)) - Size++; + if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size)) continue; - } SmallVector<char, 64> AnnotationsBytes; raw_svector_ostream Annotations(AnnotationsBytes); @@ -7588,6 +7687,10 @@ static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, MCInst Inst; uint64_t PC = SectAddress + Index; + + if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize)) + continue; + SmallVector<char, 64> AnnotationsBytes; raw_svector_ostream Annotations(AnnotationsBytes); if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC, @@ -7724,8 +7827,12 @@ static void findUnwindRelocNameAddend(const MachOObjectFile *Obj, auto Sym = Symbols.upper_bound(Addr); if (Sym == Symbols.begin()) { // The first symbol in the object is after this reference, the best we can - // do is section-relative notation. - RelocSection.getName(Name); + // do is section-relative notation. + if (Expected<StringRef> NameOrErr = RelocSection.getName()) + Name = *NameOrErr; + else + consumeError(NameOrErr.takeError()); + Addend = Addr - SectionAddr; return; } @@ -7744,7 +7851,11 @@ static void findUnwindRelocNameAddend(const MachOObjectFile *Obj, // There is a symbol before this reference, but it's in a different // section. Probably not helpful to mention it, so use the section name. - RelocSection.getName(Name); + if (Expected<StringRef> NameOrErr = RelocSection.getName()) + Name = *NameOrErr; + else + consumeError(NameOrErr.takeError()); + Addend = Addr - SectionAddr; } @@ -8109,7 +8220,11 @@ void printMachOUnwindInfo(const MachOObjectFile *Obj) { for (const SectionRef &Section : Obj->sections()) { StringRef SectName; - Section.getName(SectName); + if (Expected<StringRef> NameOrErr = Section.getName()) + SectName = *NameOrErr; + else + consumeError(NameOrErr.takeError()); + if (SectName == "__compact_unwind") printMachOCompactUnwindSection(Obj, Symbols, Section); else if (SectName == "__unwind_info") @@ -10191,7 +10306,7 @@ void printMachOExportsTrie(const object::MachOObjectFile *Obj) { outs() << "\n"; } if (Err) - report_error(std::move(Err), Obj->getFileName()); + reportError(std::move(Err), Obj->getFileName()); } //===----------------------------------------------------------------------===// @@ -10212,7 +10327,7 @@ void printMachORebaseTable(object::MachOObjectFile *Obj) { Address, Entry.typeName().str().c_str()); } if (Err) - report_error(std::move(Err), Obj->getFileName()); + reportError(std::move(Err), Obj->getFileName()); } static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) { @@ -10264,7 +10379,7 @@ void printMachOBindTable(object::MachOObjectFile *Obj) { << Entry.symbolName() << Attr << "\n"; } if (Err) - report_error(std::move(Err), Obj->getFileName()); + reportError(std::move(Err), Obj->getFileName()); } //===----------------------------------------------------------------------===// @@ -10289,7 +10404,7 @@ void printMachOLazyBindTable(object::MachOObjectFile *Obj) { << Entry.symbolName() << "\n"; } if (Err) - report_error(std::move(Err), Obj->getFileName()); + reportError(std::move(Err), Obj->getFileName()); } //===----------------------------------------------------------------------===// @@ -10321,7 +10436,7 @@ void printMachOWeakBindTable(object::MachOObjectFile *Obj) { << "\n"; } if (Err) - report_error(std::move(Err), Obj->getFileName()); + reportError(std::move(Err), Obj->getFileName()); } // get_dyld_bind_info_symbolname() is used for disassembly and passed an @@ -10331,7 +10446,7 @@ void printMachOWeakBindTable(object::MachOObjectFile *Obj) { static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue, struct DisassembleInfo *info) { if (info->bindtable == nullptr) { - info->bindtable = llvm::make_unique<SymbolAddressMap>(); + info->bindtable = std::make_unique<SymbolAddressMap>(); Error Err = Error::success(); for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) { uint64_t Address = Entry.address(); @@ -10340,7 +10455,7 @@ static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue, (*info->bindtable)[Address] = name; } if (Err) - report_error(std::move(Err), info->O->getFileName()); + reportError(std::move(Err), info->O->getFileName()); } auto name = info->bindtable->lookup(ReferenceValue); return !name.empty() ? name.data() : nullptr; diff --git a/tools/llvm-objdump/llvm-objdump.cpp b/tools/llvm-objdump/llvm-objdump.cpp index 58981203c59e..34a44b3b7fa9 100644 --- a/tools/llvm-objdump/llvm-objdump.cpp +++ b/tools/llvm-objdump/llvm-objdump.cpp @@ -51,6 +51,7 @@ #include "llvm/Support/Errc.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" +#include "llvm/Support/FormatVariadic.h" #include "llvm/Support/GraphWriter.h" #include "llvm/Support/Host.h" #include "llvm/Support/InitLLVM.h" @@ -341,78 +342,84 @@ static StringRef ToolName; typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy; -static bool shouldKeep(object::SectionRef S) { +namespace { +struct FilterResult { + // True if the section should not be skipped. + bool Keep; + + // True if the index counter should be incremented, even if the section should + // be skipped. For example, sections may be skipped if they are not included + // in the --section flag, but we still want those to count toward the section + // count. + bool IncrementIndex; +}; +} // namespace + +static FilterResult checkSectionFilter(object::SectionRef S) { if (FilterSections.empty()) - return true; - StringRef SecName; - std::error_code error = S.getName(SecName); - if (error) - return false; + return {/*Keep=*/true, /*IncrementIndex=*/true}; + + Expected<StringRef> SecNameOrErr = S.getName(); + if (!SecNameOrErr) { + consumeError(SecNameOrErr.takeError()); + return {/*Keep=*/false, /*IncrementIndex=*/false}; + } + StringRef SecName = *SecNameOrErr; + // StringSet does not allow empty key so avoid adding sections with // no name (such as the section with index 0) here. if (!SecName.empty()) FoundSectionSet.insert(SecName); - return is_contained(FilterSections, SecName); -} -SectionFilter ToolSectionFilter(object::ObjectFile const &O) { - return SectionFilter([](object::SectionRef S) { return shouldKeep(S); }, O); -} - -void error(std::error_code EC) { - if (!EC) - return; - WithColor::error(errs(), ToolName) - << "reading file: " << EC.message() << ".\n"; - errs().flush(); - exit(1); -} - -void error(Error E) { - if (!E) - return; - WithColor::error(errs(), ToolName) << toString(std::move(E)); - exit(1); + // Only show the section if it's in the FilterSections list, but always + // increment so the indexing is stable. + return {/*Keep=*/is_contained(FilterSections, SecName), + /*IncrementIndex=*/true}; } -LLVM_ATTRIBUTE_NORETURN void error(Twine Message) { - WithColor::error(errs(), ToolName) << Message << ".\n"; - errs().flush(); - exit(1); +SectionFilter ToolSectionFilter(object::ObjectFile const &O, uint64_t *Idx) { + // Start at UINT64_MAX so that the first index returned after an increment is + // zero (after the unsigned wrap). + if (Idx) + *Idx = UINT64_MAX; + return SectionFilter( + [Idx](object::SectionRef S) { + FilterResult Result = checkSectionFilter(S); + if (Idx != nullptr && Result.IncrementIndex) + *Idx += 1; + return Result.Keep; + }, + O); } -void warn(StringRef Message) { - WithColor::warning(errs(), ToolName) << Message << ".\n"; - errs().flush(); +std::string getFileNameForError(const object::Archive::Child &C, + unsigned Index) { + Expected<StringRef> NameOrErr = C.getName(); + if (NameOrErr) + return NameOrErr.get(); + // If we have an error getting the name then we print the index of the archive + // member. Since we are already in an error state, we just ignore this error. + consumeError(NameOrErr.takeError()); + return "<file index: " + std::to_string(Index) + ">"; } -static void warn(Twine Message) { +void reportWarning(Twine Message, StringRef File) { // Output order between errs() and outs() matters especially for archive // files where the output is per member object. outs().flush(); - WithColor::warning(errs(), ToolName) << Message << "\n"; + WithColor::warning(errs(), ToolName) + << "'" << File << "': " << Message << "\n"; errs().flush(); } -LLVM_ATTRIBUTE_NORETURN void report_error(StringRef File, Twine Message) { - WithColor::error(errs(), ToolName) - << "'" << File << "': " << Message << ".\n"; - exit(1); -} - -LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef File) { - assert(E); - std::string Buf; - raw_string_ostream OS(Buf); - logAllUnhandledErrors(std::move(E), OS); - OS.flush(); - WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf; +LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Twine Message) { + WithColor::error(errs(), ToolName) << "'" << File << "': " << Message << "\n"; exit(1); } -LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef ArchiveName, - StringRef FileName, - StringRef ArchitectureName) { +LLVM_ATTRIBUTE_NORETURN void reportError(Error E, StringRef FileName, + StringRef ArchiveName, + StringRef ArchitectureName) { assert(E); WithColor::error(errs(), ToolName); if (ArchiveName != "") @@ -429,18 +436,13 @@ LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef ArchiveName, exit(1); } -LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef ArchiveName, - const object::Archive::Child &C, - StringRef ArchitectureName) { - Expected<StringRef> NameOrErr = C.getName(); - // TODO: if we have a error getting the name then it would be nice to print - // the index of which archive member this is and or its offset in the - // archive instead of "???" as the name. - if (!NameOrErr) { - consumeError(NameOrErr.takeError()); - report_error(std::move(E), ArchiveName, "???", ArchitectureName); - } else - report_error(std::move(E), ArchiveName, NameOrErr.get(), ArchitectureName); +static void reportCmdLineWarning(Twine Message) { + WithColor::warning(errs(), ToolName) << Message << "\n"; +} + +LLVM_ATTRIBUTE_NORETURN static void reportCmdLineError(Twine Message) { + WithColor::error(errs(), ToolName) << Message << "\n"; + exit(1); } static void warnOnNoMatchForSections() { @@ -455,37 +457,29 @@ static void warnOnNoMatchForSections() { // Warn only if no section in FilterSections is matched. for (StringRef S : MissingSections) - warn("section '" + S + "' mentioned in a -j/--section option, but not " - "found in any input file"); + reportCmdLineWarning("section '" + S + + "' mentioned in a -j/--section option, but not " + "found in any input file"); } -static const Target *getTarget(const ObjectFile *Obj = nullptr) { +static const Target *getTarget(const ObjectFile *Obj) { // Figure out the target triple. Triple TheTriple("unknown-unknown-unknown"); if (TripleName.empty()) { - if (Obj) - TheTriple = Obj->makeTriple(); + 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) - Obj->setARMSubArch(TheTriple); - } + auto Arch = Obj->getArch(); + if (Arch == Triple::arm || Arch == Triple::armeb) + Obj->setARMSubArch(TheTriple); } // Get the target specific parser. std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, Error); - if (!TheTarget) { - if (Obj) - report_error(Obj->getFileName(), "can't find target: " + Error); - else - error("can't find target: " + Error); - } + if (!TheTarget) + reportError(Obj->getFileName(), "can't find target: " + Error); // Update the triple name and return the found target. TripleName = TheTriple.getTriple(); @@ -548,17 +542,22 @@ protected: DILineInfo OldLineInfo; const ObjectFile *Obj = nullptr; std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer; - // File name to file contents of source + // File name to file contents of source. std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache; - // Mark the line endings of the cached source + // Mark the line endings of the cached source. std::unordered_map<std::string, std::vector<StringRef>> LineCache; + // Keep track of missing sources. + StringSet<> MissingSources; + // Only emit 'no debug info' warning once. + bool WarnedNoDebugInfo; private: bool cacheSource(const DILineInfo& LineInfoFile); public: SourcePrinter() = default; - SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) { + SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) + : Obj(Obj), WarnedNoDebugInfo(false) { symbolize::LLVMSymbolizer::Options SymbolizerOpts; SymbolizerOpts.PrintFunctions = DILineInfoSpecifier::FunctionNameKind::None; SymbolizerOpts.Demangle = false; @@ -568,6 +567,7 @@ public: virtual ~SourcePrinter() = default; virtual void printSourceLine(raw_ostream &OS, object::SectionedAddress Address, + StringRef ObjectFilename, StringRef Delimiter = "; "); }; @@ -577,8 +577,12 @@ bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) { Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source); } else { auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName); - if (!BufferOrError) + if (!BufferOrError) { + if (MissingSources.insert(LineInfo.FileName).second) + reportWarning("failed to find source " + LineInfo.FileName, + Obj->getFileName()); return false; + } Buffer = std::move(*BufferOrError); } // Chomp the file to get lines @@ -599,20 +603,33 @@ bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) { void SourcePrinter::printSourceLine(raw_ostream &OS, object::SectionedAddress Address, + StringRef ObjectFilename, StringRef Delimiter) { if (!Symbolizer) return; DILineInfo LineInfo = DILineInfo(); auto ExpectedLineInfo = Symbolizer->symbolizeCode(*Obj, Address); + std::string ErrorMessage; if (!ExpectedLineInfo) - consumeError(ExpectedLineInfo.takeError()); + ErrorMessage = toString(ExpectedLineInfo.takeError()); else LineInfo = *ExpectedLineInfo; - if ((LineInfo.FileName == "<invalid>") || LineInfo.Line == 0 || - ((OldLineInfo.Line == LineInfo.Line) && - (OldLineInfo.FileName == LineInfo.FileName))) + if (LineInfo.FileName == DILineInfo::BadString) { + if (!WarnedNoDebugInfo) { + std::string Warning = + "failed to parse debug information for " + ObjectFilename.str(); + if (!ErrorMessage.empty()) + Warning += ": " + ErrorMessage; + reportWarning(Warning, ObjectFilename); + WarnedNoDebugInfo = true; + } + return; + } + + if (LineInfo.Line == 0 || ((OldLineInfo.Line == LineInfo.Line) && + (OldLineInfo.FileName == LineInfo.FileName))) return; if (PrintLines) @@ -623,8 +640,14 @@ void SourcePrinter::printSourceLine(raw_ostream &OS, return; auto LineBuffer = LineCache.find(LineInfo.FileName); if (LineBuffer != LineCache.end()) { - if (LineInfo.Line > LineBuffer->second.size()) + if (LineInfo.Line > LineBuffer->second.size()) { + reportWarning( + formatv( + "debug info line number {0} exceeds the number of lines in {1}", + LineInfo.Line, LineInfo.FileName), + ObjectFilename); return; + } // Vector begins at 0, line numbers are non-zero OS << Delimiter << LineBuffer->second[LineInfo.Line - 1] << '\n'; } @@ -646,13 +669,14 @@ static bool hasMappingSymbols(const ObjectFile *Obj) { return isArmElf(Obj) || isAArch64Elf(Obj); } -static void printRelocation(const RelocationRef &Rel, uint64_t Address, - bool Is64Bits) { +static void printRelocation(StringRef FileName, const RelocationRef &Rel, + uint64_t Address, bool Is64Bits) { StringRef Fmt = Is64Bits ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": "; SmallString<16> Name; SmallString<32> Val; Rel.getTypeName(Name); - error(getRelocationValueString(Rel, Val)); + if (Error E = getRelocationValueString(Rel, Val)) + reportError(std::move(E), FileName); outs() << format(Fmt.data(), Address) << Name << "\t" << Val << "\n"; } @@ -663,29 +687,25 @@ public: ArrayRef<uint8_t> Bytes, object::SectionedAddress Address, raw_ostream &OS, StringRef Annot, MCSubtargetInfo const &STI, - SourcePrinter *SP, + SourcePrinter *SP, StringRef ObjectFilename, std::vector<RelocationRef> *Rels = nullptr) { if (SP && (PrintSource || PrintLines)) - SP->printSourceLine(OS, Address); + SP->printSourceLine(OS, Address, ObjectFilename); - { - formatted_raw_ostream FOS(OS); - if (!NoLeadingAddr) - FOS << format("%8" PRIx64 ":", Address.Address); - if (!NoShowRawInsn) { - FOS << ' '; - dumpBytes(Bytes, FOS); - } - FOS.flush(); - // The output of printInst starts with a tab. Print some spaces so that - // the tab has 1 column and advances to the target tab stop. - unsigned TabStop = NoShowRawInsn ? 16 : 40; - unsigned Column = FOS.getColumn(); - FOS.indent(Column < TabStop - 1 ? TabStop - 1 - Column : 7 - Column % 8); - - // The dtor calls flush() to ensure the indent comes before printInst(). + size_t Start = OS.tell(); + if (!NoLeadingAddr) + OS << format("%8" PRIx64 ":", Address.Address); + if (!NoShowRawInsn) { + OS << ' '; + dumpBytes(Bytes, OS); } + // The output of printInst starts with a tab. Print some spaces so that + // the tab has 1 column and advances to the target tab stop. + unsigned TabStop = NoShowRawInsn ? 16 : 40; + unsigned Column = OS.tell() - Start; + OS.indent(Column < TabStop - 1 ? TabStop - 1 - Column : 7 - Column % 8); + if (MI) IP.printInst(MI, OS, "", STI); else @@ -711,9 +731,10 @@ public: void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, object::SectionedAddress Address, raw_ostream &OS, StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, + StringRef ObjectFilename, std::vector<RelocationRef> *Rels) override { if (SP && (PrintSource || PrintLines)) - SP->printSourceLine(OS, Address, ""); + SP->printSourceLine(OS, Address, ObjectFilename, ""); if (!MI) { printLead(Bytes, Address.Address, OS); OS << " <unknown>"; @@ -739,7 +760,7 @@ public: auto PrintReloc = [&]() -> void { while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address.Address)) { if (RelCur->getOffset() == Address.Address) { - printRelocation(*RelCur, Address.Address, false); + printRelocation(ObjectFilename, *RelCur, Address.Address, false); return; } ++RelCur; @@ -750,7 +771,7 @@ public: OS << Separator; Separator = "\n"; if (SP && (PrintSource || PrintLines)) - SP->printSourceLine(OS, Address, ""); + SP->printSourceLine(OS, Address, ObjectFilename, ""); printLead(Bytes, Address.Address, OS); OS << Preamble; Preamble = " "; @@ -780,9 +801,10 @@ public: void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, object::SectionedAddress Address, raw_ostream &OS, StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, + StringRef ObjectFilename, std::vector<RelocationRef> *Rels) override { if (SP && (PrintSource || PrintLines)) - SP->printSourceLine(OS, Address); + SP->printSourceLine(OS, Address, ObjectFilename); if (MI) { SmallString<40> InstStr; @@ -831,9 +853,10 @@ public: void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, object::SectionedAddress Address, raw_ostream &OS, StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, + StringRef ObjectFilename, std::vector<RelocationRef> *Rels) override { if (SP && (PrintSource || PrintLines)) - SP->printSourceLine(OS, Address); + SP->printSourceLine(OS, Address, ObjectFilename); if (!NoLeadingAddr) OS << format("%8" PRId64 ":", Address.Address / 8); if (!NoShowRawInsn) { @@ -924,10 +947,12 @@ static void addPltEntries(const ObjectFile *Obj, StringSaver &Saver) { Optional<SectionRef> Plt = None; for (const SectionRef &Section : Obj->sections()) { - StringRef Name; - if (Section.getName(Name)) + Expected<StringRef> SecNameOrErr = Section.getName(); + if (!SecNameOrErr) { + consumeError(SecNameOrErr.takeError()); continue; - if (Name == ".plt") + } + if (*SecNameOrErr == ".plt") Plt = Section; } if (!Plt) @@ -968,9 +993,18 @@ static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) { static std::map<SectionRef, std::vector<RelocationRef>> getRelocsMap(object::ObjectFile const &Obj) { std::map<SectionRef, std::vector<RelocationRef>> Ret; + uint64_t I = (uint64_t)-1; for (SectionRef Sec : Obj.sections()) { - section_iterator Relocated = Sec.getRelocatedSection(); - if (Relocated == Obj.section_end() || !shouldKeep(*Relocated)) + ++I; + Expected<section_iterator> RelocatedOrErr = Sec.getRelocatedSection(); + if (!RelocatedOrErr) + reportError(Obj.getFileName(), + "section (" + Twine(I) + + "): failed to get a relocated section: " + + toString(RelocatedOrErr.takeError())); + + section_iterator Relocated = *RelocatedOrErr; + if (Relocated == Obj.section_end() || !checkSectionFilter(*Relocated).Keep) continue; std::vector<RelocationRef> &V = Ret[*Relocated]; for (const RelocationRef &R : Sec.relocations()) @@ -1137,11 +1171,14 @@ static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj, if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) { for (const auto &ExportEntry : COFFObj->export_directories()) { StringRef Name; - error(ExportEntry.getSymbolName(Name)); + if (std::error_code EC = ExportEntry.getSymbolName(Name)) + reportError(errorCodeToError(EC), Obj->getFileName()); if (Name.empty()) continue; + uint32_t RVA; - error(ExportEntry.getExportRVA(RVA)); + if (std::error_code EC = ExportEntry.getExportRVA(RVA)) + reportError(errorCodeToError(EC), Obj->getFileName()); uint64_t VA = COFFObj->getImageBase() + RVA; auto Sec = partition_point( @@ -1210,9 +1247,8 @@ static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj, DataRefImpl DR = Section.getRawDataRefImpl(); SegmentName = MachO->getSectionFinalSegmentName(DR); } - StringRef SectionName; - error(Section.getName(SectionName)); + StringRef SectionName = unwrapOrError(Section.getName(), Obj->getFileName()); // If the section has no symbol at the start, just insert a dummy one. if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) { Symbols.insert( @@ -1381,10 +1417,10 @@ static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj, if (Size == 0) Size = 1; - PIP.printInst( - *IP, Disassembled ? &Inst : nullptr, Bytes.slice(Index, Size), - {SectionAddr + Index + VMAAdjustment, Section.getIndex()}, outs(), - "", *STI, &SP, &Rels); + PIP.printInst(*IP, Disassembled ? &Inst : nullptr, + Bytes.slice(Index, Size), + {SectionAddr + Index + VMAAdjustment, Section.getIndex()}, + outs(), "", *STI, &SP, Obj->getFileName(), &Rels); outs() << CommentStream.str(); Comments.clear(); @@ -1470,7 +1506,8 @@ static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj, Offset += AdjustVMA; } - printRelocation(*RelCur, SectionAddr + Offset, Is64Bits); + printRelocation(Obj->getFileName(), *RelCur, SectionAddr + Offset, + Is64Bits); ++RelCur; } } @@ -1482,7 +1519,8 @@ static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj, StringSet<> MissingDisasmFuncsSet = set_difference(DisasmFuncsSet, FoundDisasmFuncsSet); for (StringRef MissingDisasmFunc : MissingDisasmFuncsSet.keys()) - warn("failed to disassemble missing function " + MissingDisasmFunc); + reportWarning("failed to disassemble missing function " + MissingDisasmFunc, + FileName); } static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) { @@ -1497,24 +1535,24 @@ static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) { std::unique_ptr<const MCRegisterInfo> MRI( TheTarget->createMCRegInfo(TripleName)); if (!MRI) - report_error(Obj->getFileName(), - "no register info for target " + TripleName); + reportError(Obj->getFileName(), + "no register info for target " + TripleName); // Set up disassembler. std::unique_ptr<const MCAsmInfo> AsmInfo( TheTarget->createMCAsmInfo(*MRI, TripleName)); if (!AsmInfo) - report_error(Obj->getFileName(), - "no assembly info for target " + TripleName); + reportError(Obj->getFileName(), + "no assembly info for target " + TripleName); std::unique_ptr<const MCSubtargetInfo> STI( TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString())); if (!STI) - report_error(Obj->getFileName(), - "no subtarget info for target " + TripleName); + reportError(Obj->getFileName(), + "no subtarget info for target " + TripleName); std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); if (!MII) - report_error(Obj->getFileName(), - "no instruction info for target " + TripleName); + reportError(Obj->getFileName(), + "no instruction info for target " + TripleName); MCObjectFileInfo MOFI; MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI); // FIXME: for now initialize MCObjectFileInfo with default values @@ -1523,8 +1561,7 @@ static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) { std::unique_ptr<MCDisassembler> DisAsm( TheTarget->createMCDisassembler(*STI, Ctx)); if (!DisAsm) - report_error(Obj->getFileName(), - "no disassembler for target " + TripleName); + reportError(Obj->getFileName(), "no disassembler for target " + TripleName); // If we have an ARM object file, we need a second disassembler, because // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode. @@ -1549,8 +1586,8 @@ static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) { std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI)); if (!IP) - report_error(Obj->getFileName(), - "no instruction printer for target " + TripleName); + reportError(Obj->getFileName(), + "no instruction printer for target " + TripleName); IP->setPrintImmHex(PrintImmHex); PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName)); @@ -1558,7 +1595,8 @@ static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) { for (StringRef Opt : DisassemblerOptions) if (!IP->applyTargetSpecificCLOption(Opt)) - error("Unrecognized disassembler option: " + Opt); + reportError(Obj->getFileName(), + "Unrecognized disassembler option: " + Opt); disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), SecondaryDisAsm.get(), MIA.get(), IP.get(), STI.get(), SecondarySTI.get(), PIP, @@ -1577,16 +1615,21 @@ void printRelocations(const ObjectFile *Obj) { // sections. Usually, there is an only one relocation section for // each relocated section. MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec; - for (const SectionRef &Section : ToolSectionFilter(*Obj)) { + uint64_t Ndx; + for (const SectionRef &Section : ToolSectionFilter(*Obj, &Ndx)) { if (Section.relocation_begin() == Section.relocation_end()) continue; - const SectionRef TargetSec = *Section.getRelocatedSection(); - SecToRelSec[TargetSec].push_back(Section); + Expected<section_iterator> SecOrErr = Section.getRelocatedSection(); + if (!SecOrErr) + reportError(Obj->getFileName(), + "section (" + Twine(Ndx) + + "): unable to get a relocation target: " + + toString(SecOrErr.takeError())); + SecToRelSec[**SecOrErr].push_back(Section); } for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) { - StringRef SecName; - error(P.first.getName(SecName)); + StringRef SecName = unwrapOrError(P.first.getName(), Obj->getFileName()); outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n"; for (SectionRef Section : P.second) { @@ -1597,7 +1640,9 @@ void printRelocations(const ObjectFile *Obj) { if (Address < StartAddress || Address > StopAddress || getHidden(Reloc)) continue; Reloc.getTypeName(RelocName); - error(getRelocationValueString(Reloc, ValueStr)); + if (Error E = getRelocationValueString(Reloc, ValueStr)) + reportError(std::move(E), Obj->getFileName()); + outs() << format(Fmt.data(), Address) << " " << RelocName << " " << ValueStr << "\n"; } @@ -1613,7 +1658,7 @@ void printDynamicRelocations(const ObjectFile *Obj) { const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj); if (!Elf || Elf->getEType() != ELF::ET_DYN) { - error("not a dynamic object"); + reportError(Obj->getFileName(), "not a dynamic object"); return; } @@ -1629,7 +1674,8 @@ void printDynamicRelocations(const ObjectFile *Obj) { SmallString<32> RelocName; SmallString<32> ValueStr; Reloc.getTypeName(RelocName); - error(getRelocationValueString(Reloc, ValueStr)); + if (Error E = getRelocationValueString(Reloc, ValueStr)) + reportError(std::move(E), Obj->getFileName()); outs() << format(Fmt.data(), Address) << " " << RelocName << " " << ValueStr << "\n"; } @@ -1647,47 +1693,64 @@ static bool shouldDisplayLMA(const ObjectFile *Obj) { return ShowLMA; } +static size_t getMaxSectionNameWidth(const ObjectFile *Obj) { + // Default column width for names is 13 even if no names are that long. + size_t MaxWidth = 13; + for (const SectionRef &Section : ToolSectionFilter(*Obj)) { + StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName()); + MaxWidth = std::max(MaxWidth, Name.size()); + } + return MaxWidth; +} + void printSectionHeaders(const ObjectFile *Obj) { + size_t NameWidth = getMaxSectionNameWidth(Obj); + size_t AddressWidth = 2 * Obj->getBytesInAddress(); bool HasLMAColumn = shouldDisplayLMA(Obj); if (HasLMAColumn) outs() << "Sections:\n" - "Idx Name Size VMA LMA " - "Type\n"; + "Idx " + << left_justify("Name", NameWidth) << " Size " + << left_justify("VMA", AddressWidth) << " " + << left_justify("LMA", AddressWidth) << " Type\n"; else outs() << "Sections:\n" - "Idx Name Size VMA Type\n"; + "Idx " + << left_justify("Name", NameWidth) << " Size " + << left_justify("VMA", AddressWidth) << " Type\n"; - for (const SectionRef &Section : ToolSectionFilter(*Obj)) { - StringRef Name; - error(Section.getName(Name)); + uint64_t Idx; + for (const SectionRef &Section : ToolSectionFilter(*Obj, &Idx)) { + StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName()); uint64_t VMA = Section.getAddress(); if (shouldAdjustVA(Section)) VMA += AdjustVMA; uint64_t Size = Section.getSize(); - bool Text = Section.isText(); - bool Data = Section.isData(); - bool BSS = Section.isBSS(); - std::string Type = (std::string(Text ? "TEXT " : "") + - (Data ? "DATA " : "") + (BSS ? "BSS" : "")); + + std::string Type = Section.isText() ? "TEXT" : ""; + if (Section.isData()) + Type += Type.empty() ? "DATA" : " DATA"; + if (Section.isBSS()) + Type += Type.empty() ? "BSS" : " BSS"; if (HasLMAColumn) - outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %016" PRIx64 - " %s\n", - (unsigned)Section.getIndex(), Name.str().c_str(), Size, - VMA, getELFSectionLMA(Section), Type.c_str()); + outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth, + Name.str().c_str(), Size) + << format_hex_no_prefix(VMA, AddressWidth) << " " + << format_hex_no_prefix(getELFSectionLMA(Section), AddressWidth) + << " " << Type << "\n"; else - outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", - (unsigned)Section.getIndex(), Name.str().c_str(), Size, - VMA, Type.c_str()); + outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth, + Name.str().c_str(), Size) + << format_hex_no_prefix(VMA, AddressWidth) << " " << Type << "\n"; } outs() << "\n"; } void printSectionContents(const ObjectFile *Obj) { for (const SectionRef &Section : ToolSectionFilter(*Obj)) { - StringRef Name; - error(Section.getName(Name)); + StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName()); uint64_t BaseAddr = Section.getAddress(); uint64_t Size = Section.getSize(); if (!Size) @@ -1741,21 +1804,26 @@ void printSymbolTable(const ObjectFile *O, StringRef ArchiveName, const StringRef FileName = O->getFileName(); for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) { const SymbolRef &Symbol = *I; - uint64_t Address = unwrapOrError(Symbol.getAddress(), ArchiveName, FileName, + uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName, ArchiveName, ArchitectureName); if ((Address < StartAddress) || (Address > StopAddress)) continue; - SymbolRef::Type Type = unwrapOrError(Symbol.getType(), ArchiveName, - FileName, ArchitectureName); + SymbolRef::Type Type = unwrapOrError(Symbol.getType(), FileName, + ArchiveName, ArchitectureName); uint32_t Flags = Symbol.getFlags(); - section_iterator Section = unwrapOrError(Symbol.getSection(), ArchiveName, - FileName, ArchitectureName); + section_iterator Section = unwrapOrError(Symbol.getSection(), FileName, + ArchiveName, ArchitectureName); StringRef Name; - if (Type == SymbolRef::ST_Debug && Section != O->section_end()) - Section->getName(Name); - else - Name = unwrapOrError(Symbol.getName(), ArchiveName, FileName, + if (Type == SymbolRef::ST_Debug && Section != O->section_end()) { + if (Expected<StringRef> NameOrErr = Section->getName()) + Name = *NameOrErr; + else + consumeError(NameOrErr.takeError()); + + } else { + Name = unwrapOrError(Symbol.getName(), FileName, ArchiveName, ArchitectureName); + } bool Global = Flags & SymbolRef::SF_Global; bool Weak = Flags & SymbolRef::SF_Weak; @@ -1801,8 +1869,8 @@ void printSymbolTable(const ObjectFile *O, StringRef ArchiveName, StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); outs() << SegmentName << ","; } - StringRef SectionName; - error(Section->getName(SectionName)); + StringRef SectionName = + unwrapOrError(Section->getName(), O->getFileName()); outs() << SectionName; } @@ -1875,7 +1943,11 @@ void printRawClangAST(const ObjectFile *Obj) { Optional<object::SectionRef> ClangASTSection; for (auto Sec : ToolSectionFilter(*Obj)) { StringRef Name; - Sec.getName(Name); + if (Expected<StringRef> NameOrErr = Sec.getName()) + Name = *NameOrErr; + else + consumeError(NameOrErr.takeError()); + if (Name == ClangASTSectionName) { ClangASTSection = Sec; break; @@ -1907,7 +1979,11 @@ static void printFaultMaps(const ObjectFile *Obj) { for (auto Sec : ToolSectionFilter(*Obj)) { StringRef Name; - Sec.getName(Name); + if (Expected<StringRef> NameOrErr = Sec.getName()) + Name = *NameOrErr; + else + consumeError(NameOrErr.takeError()); + if (Name == FaultMapSectionName) { FaultMapSection = Sec; break; @@ -1946,12 +2022,12 @@ static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) { printMachOLoadCommands(O); return; } - report_error(O->getFileName(), "Invalid/Unsupported object file format"); + reportError(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"); + reportError(O->getFileName(), "Invalid/Unsupported object file format"); Triple::ArchType AT = O->getArch(); outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n"; @@ -2010,6 +2086,43 @@ static void printArchiveChild(StringRef Filename, const Archive::Child &C) { outs() << Name << "\n"; } +// For ELF only now. +static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) { + if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj)) { + if (Elf->getEType() != ELF::ET_REL) + return true; + } + return false; +} + +static void checkForInvalidStartStopAddress(ObjectFile *Obj, + uint64_t Start, uint64_t Stop) { + if (!shouldWarnForInvalidStartStopAddress(Obj)) + return; + + for (const SectionRef &Section : Obj->sections()) + if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) { + uint64_t BaseAddr = Section.getAddress(); + uint64_t Size = Section.getSize(); + if ((Start < BaseAddr + Size) && Stop > BaseAddr) + return; + } + + if (StartAddress.getNumOccurrences() == 0) + reportWarning("no section has address less than 0x" + + Twine::utohexstr(Stop) + " specified by --stop-address", + Obj->getFileName()); + else if (StopAddress.getNumOccurrences() == 0) + reportWarning("no section has address greater than or equal to 0x" + + Twine::utohexstr(Start) + " specified by --start-address", + Obj->getFileName()); + else + reportWarning("no section overlaps the range [0x" + + Twine::utohexstr(Start) + ",0x" + Twine::utohexstr(Stop) + + ") specified by --start-address/--stop-address", + Obj->getFileName()); +} + static void dumpObject(ObjectFile *O, const Archive *A = nullptr, const Archive::Child *C = nullptr) { // Avoid other output when using a raw option. @@ -2022,27 +2135,40 @@ static void dumpObject(ObjectFile *O, const Archive *A = nullptr, outs() << ":\tfile format " << O->getFileFormatName() << "\n\n"; } + if (StartAddress.getNumOccurrences() || StopAddress.getNumOccurrences()) + checkForInvalidStartStopAddress(O, StartAddress, StopAddress); + + // Note: the order here matches GNU objdump for compatability. StringRef ArchiveName = A ? A->getFileName() : ""; - if (FileHeaders) - printFileHeaders(O); if (ArchiveHeaders && !MachOOpt && C) printArchiveChild(ArchiveName, *C); - if (Disassemble) - disassembleObject(O, Relocations); + if (FileHeaders) + printFileHeaders(O); + if (PrivateHeaders || FirstPrivateHeader) + printPrivateFileHeaders(O, FirstPrivateHeader); + if (SectionHeaders) + printSectionHeaders(O); + if (SymbolTable) + printSymbolTable(O, ArchiveName); + if (DwarfDumpType != DIDT_Null) { + std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O); + // Dump the complete DWARF structure. + DIDumpOptions DumpOpts; + DumpOpts.DumpType = DwarfDumpType; + DICtx->dump(outs(), DumpOpts); + } if (Relocations && !Disassemble) printRelocations(O); if (DynamicRelocations) printDynamicRelocations(O); - if (SectionHeaders) - printSectionHeaders(O); if (SectionContents) printSectionContents(O); - if (SymbolTable) - printSymbolTable(O, ArchiveName); + if (Disassemble) + disassembleObject(O, Relocations); if (UnwindInfo) printUnwindInfo(O); - if (PrivateHeaders || FirstPrivateHeader) - printPrivateFileHeaders(O, FirstPrivateHeader); + + // Mach-O specific options: if (ExportsTrie) printExportsTrie(O); if (Rebase) @@ -2053,17 +2179,12 @@ static void dumpObject(ObjectFile *O, const Archive *A = nullptr, printLazyBindTable(O); if (WeakBind) printWeakBindTable(O); + + // Other special sections: if (RawClangAST) printRawClangAST(O); if (FaultMapSection) printFaultMaps(O); - if (DwarfDumpType != DIDT_Null) { - std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O); - // Dump the complete DWARF structure. - DIDumpOptions DumpOpts; - DumpOpts.DumpType = DwarfDumpType; - DICtx->dump(outs(), DumpOpts); - } } static void dumpObject(const COFFImportFile *I, const Archive *A, @@ -2086,11 +2207,13 @@ static void dumpObject(const COFFImportFile *I, const Archive *A, /// Dump each object file in \a a; static void dumpArchive(const Archive *A) { Error Err = Error::success(); + unsigned I = -1; for (auto &C : A->children(Err)) { + ++I; Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); if (!ChildOrErr) { if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) - report_error(std::move(E), A->getFileName(), C); + reportError(std::move(E), getFileNameForError(C, I), A->getFileName()); continue; } if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get())) @@ -2098,11 +2221,11 @@ static void dumpArchive(const Archive *A) { else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get())) dumpObject(I, A, &C); else - report_error(errorCodeToError(object_error::invalid_file_type), - A->getFileName()); + reportError(errorCodeToError(object_error::invalid_file_type), + A->getFileName()); } if (Err) - report_error(std::move(Err), A->getFileName()); + reportError(std::move(Err), A->getFileName()); } /// Open file and figure out how to dump it. @@ -2126,7 +2249,7 @@ static void dumpInput(StringRef file) { else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary)) parseInputMachO(UB); else - report_error(errorCodeToError(object_error::invalid_file_type), file); + reportError(errorCodeToError(object_error::invalid_file_type), file); } } // namespace llvm @@ -2147,7 +2270,7 @@ int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); if (StartAddress >= StopAddress) - error("start address should be less than stop address"); + reportCmdLineError("start address should be less than stop address"); ToolName = argv[0]; diff --git a/tools/llvm-objdump/llvm-objdump.h b/tools/llvm-objdump/llvm-objdump.h index e58d4a05c2e6..43ce02ae0bc2 100644 --- a/tools/llvm-objdump/llvm-objdump.h +++ b/tools/llvm-objdump/llvm-objdump.h @@ -31,6 +31,8 @@ extern cl::opt<bool> Demangle; typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate; +/// A filtered iterator for SectionRefs that skips sections based on some given +/// predicate. class SectionFilterIterator { public: SectionFilterIterator(FilterPredicate P, @@ -60,6 +62,8 @@ private: llvm::object::section_iterator End; }; +/// Creates an iterator range of SectionFilterIterators for a given Object and +/// predicate. class SectionFilter { public: SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O) @@ -79,7 +83,15 @@ private: }; // Various helper functions. -SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O); + +/// Creates a SectionFilter with a standard predicate that conditionally skips +/// sections when the --section objdump flag is provided. +/// +/// Idx is an optional output parameter that keeps track of which section index +/// this is. This may be different than the actual section number, as some +/// sections may be filtered (e.g. symbol tables). +SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O, + uint64_t *Idx = nullptr); Error getELFRelocationValueString(const object::ELFObjectFileBase *Obj, const object::RelocationRef &Rel, @@ -96,8 +108,6 @@ Error getMachORelocationValueString(const object::MachOObjectFile *Obj, uint64_t getELFSectionLMA(const object::ELFSectionRef& Sec); -void error(std::error_code ec); -void error(Error E); bool isRelocAddressLess(object::RelocationRef A, object::RelocationRef B); void parseInputMachO(StringRef Filename); void parseInputMachO(object::MachOUniversalBinary *UB); @@ -129,24 +139,22 @@ void printSectionHeaders(const object::ObjectFile *O); void printSectionContents(const object::ObjectFile *O); void printSymbolTable(const object::ObjectFile *O, StringRef ArchiveName, StringRef ArchitectureName = StringRef()); -void warn(StringRef Message); -LLVM_ATTRIBUTE_NORETURN void error(Twine Message); -LLVM_ATTRIBUTE_NORETURN void report_error(StringRef File, Twine Message); -LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef File); -LLVM_ATTRIBUTE_NORETURN void -report_error(Error E, StringRef FileName, StringRef ArchiveName, - StringRef ArchitectureName = StringRef()); -LLVM_ATTRIBUTE_NORETURN void -report_error(Error E, StringRef ArchiveName, const object::Archive::Child &C, - StringRef ArchitectureName = StringRef()); +LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Twine Message); +LLVM_ATTRIBUTE_NORETURN void reportError(Error E, StringRef FileName, + StringRef ArchiveName = "", + StringRef ArchitectureName = ""); +void reportWarning(Twine Message, StringRef File); template <typename T, typename... Ts> T unwrapOrError(Expected<T> EO, Ts &&... Args) { if (EO) return std::move(*EO); - report_error(EO.takeError(), std::forward<Ts>(Args)...); + reportError(EO.takeError(), std::forward<Ts>(Args)...); } +std::string getFileNameForError(const object::Archive::Child &C, + unsigned Index); + } // end namespace llvm #endif |