Importing rustc-1.45.2
Change-Id: Idd187dd729f3089d9529753a17db5fbb40bacdeb
diff --git a/src/llvm-project/llvm/tools/llvm-objdump/COFFDump.cpp b/src/llvm-project/llvm/tools/llvm-objdump/COFFDump.cpp
index 1ba0a68..60b0f5a 100644
--- a/src/llvm-project/llvm/tools/llvm-objdump/COFFDump.cpp
+++ b/src/llvm-project/llvm/tools/llvm-objdump/COFFDump.cpp
@@ -234,15 +234,14 @@
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 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 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 @@
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 @@
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 @@
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 @@
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 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 @@
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 @@
, 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 @@
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/src/llvm-project/llvm/tools/llvm-objdump/ELFDump.cpp b/src/llvm-project/llvm/tools/llvm-objdump/ELFDump.cpp
index 9c4d67d..abfe083 100644
--- a/src/llvm-project/llvm/tools/llvm-objdump/ELFDump.cpp
+++ b/src/llvm-project/llvm/tools/llvm-objdump/ELFDump.cpp
@@ -105,9 +105,12 @@
} else {
Fmt << "*ABS*";
}
-
- if (Addend != 0)
- Fmt << (Addend < 0 ? "" : "+") << Addend;
+ if (Addend != 0) {
+ Fmt << (Addend < 0
+ ? "-"
+ : "+") << format("0x%" PRIx64,
+ (Addend < 0 ? -(uint64_t)Addend : (uint64_t)Addend));
+ }
Fmt.flush();
Result.append(FmtBuf.begin(), FmtBuf.end());
return Error::success();
@@ -178,7 +181,7 @@
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);
@@ -201,6 +204,9 @@
case ELF::PT_GNU_RELRO:
outs() << " RELRO ";
break;
+ case ELF::PT_GNU_PROPERTY:
+ outs() << " PROPERTY ";
+ break;
case ELF::PT_GNU_STACK:
outs() << " STACK ";
break;
diff --git a/src/llvm-project/llvm/tools/llvm-objdump/MachODump.cpp b/src/llvm-project/llvm/tools/llvm-objdump/MachODump.cpp
index 58ff7be..87c7a92 100644
--- a/src/llvm-project/llvm/tools/llvm-objdump/MachODump.cpp
+++ b/src/llvm-project/llvm/tools/llvm-objdump/MachODump.cpp
@@ -29,6 +29,7 @@
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
+#include "llvm/MC/MCTargetOptions.h"
#include "llvm/Object/MachO.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Support/Casting.h"
@@ -236,11 +237,11 @@
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 +372,8 @@
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 +391,40 @@
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 +447,11 @@
// 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 +484,14 @@
--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 +534,8 @@
// 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 +583,8 @@
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 +604,8 @@
// 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 +644,8 @@
// 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 +1531,12 @@
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 +1748,12 @@
}
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 +1849,12 @@
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 +1946,16 @@
// 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 +2200,7 @@
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 +2214,14 @@
}
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 +2239,14 @@
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 +2269,17 @@
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 +2288,13 @@
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 +2326,7 @@
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 +2339,13 @@
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 +2355,7 @@
}
}
if (Err)
- report_error(std::move(Err), Filename);
+ reportError(std::move(Err), Filename);
return;
}
if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
@@ -2346,7 +2407,7 @@
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 +2420,15 @@
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 +2436,13 @@
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 +2472,7 @@
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 +2481,14 @@
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 +2496,12 @@
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 +2523,7 @@
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 +2534,14 @@
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 +2552,12 @@
}
}
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 +3154,7 @@
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 +3168,7 @@
}
} 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 +3188,7 @@
} 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 +3288,13 @@
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 +4086,12 @@
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 +4108,12 @@
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 +4162,7 @@
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 +5836,12 @@
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 +5904,12 @@
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 +5955,12 @@
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 +6017,12 @@
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 +6072,12 @@
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 +6112,8 @@
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 +6194,8 @@
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 +6289,8 @@
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 +6447,8 @@
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);
@@ -7110,11 +7209,12 @@
FeaturesStr = Features.getString();
}
+ MCTargetOptions MCOptions;
// Set up disassembler.
std::unique_ptr<const MCRegisterInfo> MRI(
TheTarget->createMCRegInfo(TripleName));
std::unique_ptr<const MCAsmInfo> AsmInfo(
- TheTarget->createMCAsmInfo(*MRI, TripleName));
+ TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
std::unique_ptr<const MCSubtargetInfo> STI(
TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
@@ -7164,7 +7264,7 @@
if (ThumbTarget) {
ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
ThumbAsmInfo.reset(
- ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
+ ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions));
ThumbSTI.reset(
ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
FeaturesStr));
@@ -7203,7 +7303,7 @@
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);
@@ -7226,12 +7326,6 @@
}
array_pod_sort(Dices.begin(), Dices.end());
-#ifndef NDEBUG
- raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
-#else
- raw_ostream &DebugOut = nulls();
-#endif
-
// Try to find debug info and set up the DIContext for it.
std::unique_ptr<DIContext> diContext;
std::unique_ptr<Binary> DSYMBinary;
@@ -7242,10 +7336,24 @@
// 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 +7363,12 @@
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 +7376,7 @@
}
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 +7396,19 @@
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 +7421,12 @@
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 +7607,8 @@
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);
@@ -7521,10 +7616,10 @@
bool gotInst;
if (UseThumbTarget)
gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
- PC, DebugOut, Annotations);
+ PC, Annotations);
else
gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
- DebugOut, Annotations);
+ Annotations);
if (gotInst) {
if (!NoShowRawInsn || Arch == Triple::arm) {
dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
@@ -7532,9 +7627,10 @@
formatted_raw_ostream FormattedOS(outs());
StringRef AnnotationsStr = Annotations.str();
if (UseThumbTarget)
- ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
+ ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI,
+ FormattedOS);
else
- IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
+ IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS);
emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
// Print debug info.
@@ -7548,8 +7644,7 @@
}
outs() << "\n";
} else {
- unsigned int Arch = MachOOF->getArch();
- if (Arch == Triple::x86_64 || Arch == Triple::x86) {
+ if (MachOOF->getArchTriple().isX86()) {
outs() << format("\t.byte 0x%02x #bad opcode\n",
*(Bytes.data() + Index) & 0xff);
Size = 1; // skip exactly one illegible byte and move on.
@@ -7588,10 +7683,14 @@
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,
- DebugOut, Annotations)) {
+ Annotations)) {
if (!NoLeadingAddr) {
if (FullLeadingAddr) {
if (MachOOF->is64Bit())
@@ -7607,11 +7706,10 @@
dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
}
StringRef AnnotationsStr = Annotations.str();
- IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
+ IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs());
outs() << "\n";
} else {
- unsigned int Arch = MachOOF->getArch();
- if (Arch == Triple::x86_64 || Arch == Triple::x86) {
+ if (MachOOF->getArchTriple().isX86()) {
outs() << format("\t.byte 0x%02x #bad opcode\n",
*(Bytes.data() + Index) & 0xff);
InstSize = 1; // skip exactly one illegible byte and move on.
@@ -7625,7 +7723,7 @@
}
}
// The TripleName's need to be reset if we are called again for a different
- // archtecture.
+ // architecture.
TripleName = "";
ThumbTripleName = "";
@@ -7725,7 +7823,11 @@
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);
+ if (Expected<StringRef> NameOrErr = RelocSection.getName())
+ Name = *NameOrErr;
+ else
+ consumeError(NameOrErr.takeError());
+
Addend = Addr - SectionAddr;
return;
}
@@ -7744,7 +7846,11 @@
// 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 +8215,11 @@
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 +10301,7 @@
outs() << "\n";
}
if (Err)
- report_error(std::move(Err), Obj->getFileName());
+ reportError(std::move(Err), Obj->getFileName());
}
//===----------------------------------------------------------------------===//
@@ -10212,7 +10322,7 @@
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 +10374,7 @@
<< Entry.symbolName() << Attr << "\n";
}
if (Err)
- report_error(std::move(Err), Obj->getFileName());
+ reportError(std::move(Err), Obj->getFileName());
}
//===----------------------------------------------------------------------===//
@@ -10289,7 +10399,7 @@
<< Entry.symbolName() << "\n";
}
if (Err)
- report_error(std::move(Err), Obj->getFileName());
+ reportError(std::move(Err), Obj->getFileName());
}
//===----------------------------------------------------------------------===//
@@ -10321,7 +10431,7 @@
<< "\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 +10441,7 @@
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 +10450,7 @@
(*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/src/llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp b/src/llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp
index 5898120..6bd37a1 100644
--- a/src/llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp
+++ b/src/llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp
@@ -37,6 +37,7 @@
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
+#include "llvm/MC/MCTargetOptions.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/COFF.h"
#include "llvm/Object/COFFImportFile.h"
@@ -51,6 +52,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 +343,84 @@
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);
+
+ // 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};
}
-SectionFilter ToolSectionFilter(object::ObjectFile const &O) {
- return SectionFilter([](object::SectionRef S) { return shouldKeep(S); }, O);
+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 error(std::error_code EC) {
- if (!EC)
- return;
- WithColor::error(errs(), ToolName)
- << "reading file: " << EC.message() << ".\n";
- errs().flush();
- exit(1);
+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) + ">";
}
-void error(Error E) {
- if (!E)
- return;
- WithColor::error(errs(), ToolName) << toString(std::move(E));
- exit(1);
-}
-
-LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
- WithColor::error(errs(), ToolName) << Message << ".\n";
- errs().flush();
- exit(1);
-}
-
-void warn(StringRef Message) {
- WithColor::warning(errs(), ToolName) << Message << ".\n";
- errs().flush();
-}
-
-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";
+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 File) {
- assert(E);
- std::string Buf;
- raw_string_ostream OS(Buf);
- logAllUnhandledErrors(std::move(E), OS);
- OS.flush();
- WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
- 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 +437,13 @@
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 +458,29 @@
// 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 +543,22 @@
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 +568,7 @@
virtual ~SourcePrinter() = default;
virtual void printSourceLine(raw_ostream &OS,
object::SectionedAddress Address,
+ StringRef ObjectFilename,
StringRef Delimiter = "; ");
};
@@ -577,8 +578,12 @@
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 +604,33 @@
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 +641,14 @@
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 +670,14 @@
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,31 +688,27 @@
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);
+ IP.printInst(MI, Address.Address, "", STI, OS);
else
OS << "\t<unknown>";
}
@@ -711,9 +732,10 @@
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>";
@@ -722,7 +744,7 @@
std::string Buffer;
{
raw_string_ostream TempStream(Buffer);
- IP.printInst(MI, TempStream, "", STI);
+ IP.printInst(MI, Address.Address, "", STI, TempStream);
}
StringRef Contents(Buffer);
// Split off bundle attributes
@@ -739,7 +761,7 @@
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 +772,7 @@
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,15 +802,16 @@
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;
raw_svector_ostream IS(InstStr);
- IP.printInst(MI, IS, "", STI);
+ IP.printInst(MI, Address.Address, "", STI, IS);
OS << left_justify(IS.str(), 60);
} else {
@@ -831,9 +854,10 @@
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) {
@@ -841,7 +865,7 @@
dumpBytes(Bytes, OS);
}
if (MI)
- IP.printInst(MI, OS, "", STI);
+ IP.printInst(MI, Address.Address, "", STI, OS);
else
OS << "\t<unknown>";
}
@@ -924,10 +948,12 @@
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 +994,18 @@
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())
@@ -1099,6 +1134,7 @@
std::map<SectionRef, SectionSymbolsTy> AllSymbols;
SectionSymbolsTy AbsoluteSymbols;
const StringRef FileName = Obj->getFileName();
+ const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj);
for (const SymbolRef &Symbol : Obj->symbols()) {
uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName);
@@ -1113,6 +1149,18 @@
continue;
}
+ // Don't ask a Mach-O STAB symbol for its section unless you know that
+ // STAB symbol's section field refers to a valid section index. Otherwise
+ // the symbol may error trying to load a section that does not exist.
+ if (MachO) {
+ DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
+ uint8_t NType = (MachO->is64Bit() ?
+ MachO->getSymbol64TableEntry(SymDRI).n_type:
+ MachO->getSymbolTableEntry(SymDRI).n_type);
+ if (NType & MachO::N_STAB)
+ continue;
+ }
+
section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
if (SecI != Obj->section_end())
AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
@@ -1137,11 +1185,14 @@
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(
@@ -1206,13 +1257,12 @@
}
StringRef SegmentName = "";
- if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
+ if (MachO) {
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(
@@ -1303,16 +1353,10 @@
continue;
}
-#ifndef NDEBUG
- raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
-#else
- raw_ostream &DebugOut = nulls();
-#endif
-
// Some targets (like WebAssembly) have a special prelude at the start
// of each symbol.
DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start),
- SectionAddr + Start, DebugOut, CommentStream);
+ SectionAddr + Start, CommentStream);
Start += Size;
Index = Start;
@@ -1376,15 +1420,14 @@
// provided
MCInst Inst;
bool Disassembled = DisAsm->getInstruction(
- Inst, Size, Bytes.slice(Index), SectionAddr + Index, DebugOut,
- CommentStream);
+ Inst, Size, Bytes.slice(Index), SectionAddr + Index, CommentStream);
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 +1513,8 @@
Offset += AdjustVMA;
}
- printRelocation(*RelCur, SectionAddr + Offset, Is64Bits);
+ printRelocation(Obj->getFileName(), *RelCur, SectionAddr + Offset,
+ Is64Bits);
++RelCur;
}
}
@@ -1482,7 +1526,8 @@
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 +1542,25 @@
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.
+ MCTargetOptions MCOptions;
std::unique_ptr<const MCAsmInfo> AsmInfo(
- TheTarget->createMCAsmInfo(*MRI, TripleName));
+ TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
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 +1569,7 @@
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 +1594,8 @@
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 +1603,8 @@
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 +1623,21 @@
// 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 +1648,9 @@
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 +1666,7 @@
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 +1682,8 @@
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 +1701,64 @@
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)
@@ -1739,23 +1810,44 @@
}
const StringRef FileName = O->getFileName();
+ const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(O);
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);
+
+ // Don't ask a Mach-O STAB symbol for its section unless you know that
+ // STAB symbol's section field refers to a valid section index. Otherwise
+ // the symbol may error trying to load a section that does not exist.
+ bool isSTAB = false;
+ if (MachO) {
+ DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
+ uint8_t NType = (MachO->is64Bit() ?
+ MachO->getSymbol64TableEntry(SymDRI).n_type:
+ MachO->getSymbolTableEntry(SymDRI).n_type);
+ if (NType & MachO::N_STAB)
+ isSTAB = true;
+ }
+ section_iterator Section = isSTAB ? O->section_end() :
+ 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 +1893,8 @@
StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
outs() << SegmentName << ",";
}
- StringRef SectionName;
- error(Section->getName(SectionName));
+ StringRef SectionName =
+ unwrapOrError(Section->getName(), O->getFileName());
outs() << SectionName;
}
@@ -1875,7 +1967,11 @@
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 +2003,11 @@
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 +2046,12 @@
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 +2110,43 @@
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 +2159,40 @@
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 +2203,12 @@
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 +2231,13 @@
/// 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 +2245,11 @@
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 +2273,7 @@
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 +2294,7 @@
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/src/llvm-project/llvm/tools/llvm-objdump/llvm-objdump.h b/src/llvm-project/llvm/tools/llvm-objdump/llvm-objdump.h
index e58d4a0..43ce02a 100644
--- a/src/llvm-project/llvm/tools/llvm-objdump/llvm-objdump.h
+++ b/src/llvm-project/llvm/tools/llvm-objdump/llvm-objdump.h
@@ -31,6 +31,8 @@
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 @@
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 @@
};
// 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 @@
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 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