1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This program is a utility that works like binutils "objdump", that is, it 11 // dumps out a plethora of information about an object file depending on the 12 // flags. 13 // 14 // The flags and output of this program should be near identical to those of 15 // binutils objdump. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm-objdump.h" 20 #include "llvm/ADT/Optional.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/StringExtras.h" 23 #include "llvm/ADT/Triple.h" 24 #include "llvm/CodeGen/FaultMaps.h" 25 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 26 #include "llvm/DebugInfo/Symbolize/Symbolize.h" 27 #include "llvm/MC/MCAsmInfo.h" 28 #include "llvm/MC/MCContext.h" 29 #include "llvm/MC/MCDisassembler/MCDisassembler.h" 30 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h" 31 #include "llvm/MC/MCInst.h" 32 #include "llvm/MC/MCInstPrinter.h" 33 #include "llvm/MC/MCInstrAnalysis.h" 34 #include "llvm/MC/MCInstrInfo.h" 35 #include "llvm/MC/MCObjectFileInfo.h" 36 #include "llvm/MC/MCRegisterInfo.h" 37 #include "llvm/MC/MCSubtargetInfo.h" 38 #include "llvm/Object/Archive.h" 39 #include "llvm/Object/COFF.h" 40 #include "llvm/Object/ELFObjectFile.h" 41 #include "llvm/Object/MachO.h" 42 #include "llvm/Object/ObjectFile.h" 43 #include "llvm/Support/Casting.h" 44 #include "llvm/Support/CommandLine.h" 45 #include "llvm/Support/Debug.h" 46 #include "llvm/Support/Errc.h" 47 #include "llvm/Support/FileSystem.h" 48 #include "llvm/Support/Format.h" 49 #include "llvm/Support/GraphWriter.h" 50 #include "llvm/Support/Host.h" 51 #include "llvm/Support/ManagedStatic.h" 52 #include "llvm/Support/MemoryBuffer.h" 53 #include "llvm/Support/PrettyStackTrace.h" 54 #include "llvm/Support/Signals.h" 55 #include "llvm/Support/SourceMgr.h" 56 #include "llvm/Support/TargetRegistry.h" 57 #include "llvm/Support/TargetSelect.h" 58 #include "llvm/Support/raw_ostream.h" 59 #include <algorithm> 60 #include <cctype> 61 #include <cstring> 62 #include <system_error> 63 #include <utility> 64 #include <unordered_map> 65 66 using namespace llvm; 67 using namespace object; 68 69 static cl::list<std::string> 70 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore); 71 72 cl::opt<bool> 73 llvm::Disassemble("disassemble", 74 cl::desc("Display assembler mnemonics for the machine instructions")); 75 static cl::alias 76 Disassembled("d", cl::desc("Alias for --disassemble"), 77 cl::aliasopt(Disassemble)); 78 79 cl::opt<bool> 80 llvm::DisassembleAll("disassemble-all", 81 cl::desc("Display assembler mnemonics for the machine instructions")); 82 static cl::alias 83 DisassembleAlld("D", cl::desc("Alias for --disassemble-all"), 84 cl::aliasopt(DisassembleAll)); 85 86 cl::opt<bool> 87 llvm::Relocations("r", cl::desc("Display the relocation entries in the file")); 88 89 cl::opt<bool> 90 llvm::SectionContents("s", cl::desc("Display the content of each section")); 91 92 cl::opt<bool> 93 llvm::SymbolTable("t", cl::desc("Display the symbol table")); 94 95 cl::opt<bool> 96 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols")); 97 98 cl::opt<bool> 99 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info")); 100 101 cl::opt<bool> 102 llvm::Bind("bind", cl::desc("Display mach-o binding info")); 103 104 cl::opt<bool> 105 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info")); 106 107 cl::opt<bool> 108 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info")); 109 110 cl::opt<bool> 111 llvm::RawClangAST("raw-clang-ast", 112 cl::desc("Dump the raw binary contents of the clang AST section")); 113 114 static cl::opt<bool> 115 MachOOpt("macho", cl::desc("Use MachO specific object file parser")); 116 static cl::alias 117 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt)); 118 119 cl::opt<std::string> 120 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, " 121 "see -version for available targets")); 122 123 cl::opt<std::string> 124 llvm::MCPU("mcpu", 125 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 126 cl::value_desc("cpu-name"), 127 cl::init("")); 128 129 cl::opt<std::string> 130 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, " 131 "see -version for available targets")); 132 133 cl::opt<bool> 134 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the " 135 "headers for each section.")); 136 static cl::alias 137 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"), 138 cl::aliasopt(SectionHeaders)); 139 static cl::alias 140 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"), 141 cl::aliasopt(SectionHeaders)); 142 143 cl::list<std::string> 144 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. " 145 "With -macho dump segment,section")); 146 cl::alias 147 static FilterSectionsj("j", cl::desc("Alias for --section"), 148 cl::aliasopt(llvm::FilterSections)); 149 150 cl::list<std::string> 151 llvm::MAttrs("mattr", 152 cl::CommaSeparated, 153 cl::desc("Target specific attributes"), 154 cl::value_desc("a1,+a2,-a3,...")); 155 156 cl::opt<bool> 157 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling " 158 "instructions, do not print " 159 "the instruction bytes.")); 160 161 cl::opt<bool> 162 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information")); 163 164 static cl::alias 165 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"), 166 cl::aliasopt(UnwindInfo)); 167 168 cl::opt<bool> 169 llvm::PrivateHeaders("private-headers", 170 cl::desc("Display format specific file headers")); 171 172 cl::opt<bool> 173 llvm::FirstPrivateHeader("private-header", 174 cl::desc("Display only the first format specific file " 175 "header")); 176 177 static cl::alias 178 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"), 179 cl::aliasopt(PrivateHeaders)); 180 181 cl::opt<bool> 182 llvm::PrintImmHex("print-imm-hex", 183 cl::desc("Use hex format for immediate values")); 184 185 cl::opt<bool> PrintFaultMaps("fault-map-section", 186 cl::desc("Display contents of faultmap section")); 187 188 cl::opt<DIDumpType> llvm::DwarfDumpType( 189 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"), 190 cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame"), 191 clEnumValEnd)); 192 193 cl::opt<bool> PrintSource( 194 "source", 195 cl::desc( 196 "Display source inlined with disassembly. Implies disassmble object")); 197 198 cl::alias PrintSourceShort("S", cl::desc("Alias for -source"), 199 cl::aliasopt(PrintSource)); 200 201 cl::opt<bool> PrintLines("line-numbers", 202 cl::desc("Display source line numbers with " 203 "disassembly. Implies disassemble object")); 204 205 cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"), 206 cl::aliasopt(PrintLines)); 207 static StringRef ToolName; 208 209 namespace { 210 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate; 211 212 class SectionFilterIterator { 213 public: 214 SectionFilterIterator(FilterPredicate P, 215 llvm::object::section_iterator const &I, 216 llvm::object::section_iterator const &E) 217 : Predicate(std::move(P)), Iterator(I), End(E) { 218 ScanPredicate(); 219 } 220 const llvm::object::SectionRef &operator*() const { return *Iterator; } 221 SectionFilterIterator &operator++() { 222 ++Iterator; 223 ScanPredicate(); 224 return *this; 225 } 226 bool operator!=(SectionFilterIterator const &Other) const { 227 return Iterator != Other.Iterator; 228 } 229 230 private: 231 void ScanPredicate() { 232 while (Iterator != End && !Predicate(*Iterator)) { 233 ++Iterator; 234 } 235 } 236 FilterPredicate Predicate; 237 llvm::object::section_iterator Iterator; 238 llvm::object::section_iterator End; 239 }; 240 241 class SectionFilter { 242 public: 243 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O) 244 : Predicate(std::move(P)), Object(O) {} 245 SectionFilterIterator begin() { 246 return SectionFilterIterator(Predicate, Object.section_begin(), 247 Object.section_end()); 248 } 249 SectionFilterIterator end() { 250 return SectionFilterIterator(Predicate, Object.section_end(), 251 Object.section_end()); 252 } 253 254 private: 255 FilterPredicate Predicate; 256 llvm::object::ObjectFile const &Object; 257 }; 258 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) { 259 return SectionFilter( 260 [](llvm::object::SectionRef const &S) { 261 if (FilterSections.empty()) 262 return true; 263 llvm::StringRef String; 264 std::error_code error = S.getName(String); 265 if (error) 266 return false; 267 return is_contained(FilterSections, String); 268 }, 269 O); 270 } 271 } 272 273 void llvm::error(std::error_code EC) { 274 if (!EC) 275 return; 276 277 errs() << ToolName << ": error reading file: " << EC.message() << ".\n"; 278 errs().flush(); 279 exit(1); 280 } 281 282 LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) { 283 errs() << ToolName << ": " << Message << ".\n"; 284 errs().flush(); 285 exit(1); 286 } 287 288 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File, 289 std::error_code EC) { 290 assert(EC); 291 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n"; 292 exit(1); 293 } 294 295 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File, 296 llvm::Error E) { 297 assert(E); 298 std::string Buf; 299 raw_string_ostream OS(Buf); 300 logAllUnhandledErrors(std::move(E), OS, ""); 301 OS.flush(); 302 errs() << ToolName << ": '" << File << "': " << Buf; 303 exit(1); 304 } 305 306 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName, 307 StringRef FileName, 308 llvm::Error E, 309 StringRef ArchitectureName) { 310 assert(E); 311 errs() << ToolName << ": "; 312 if (ArchiveName != "") 313 errs() << ArchiveName << "(" << FileName << ")"; 314 else 315 errs() << FileName; 316 if (!ArchitectureName.empty()) 317 errs() << " (for architecture " << ArchitectureName << ")"; 318 std::string Buf; 319 raw_string_ostream OS(Buf); 320 logAllUnhandledErrors(std::move(E), OS, ""); 321 OS.flush(); 322 errs() << " " << Buf; 323 exit(1); 324 } 325 326 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName, 327 const object::Archive::Child &C, 328 llvm::Error E, 329 StringRef ArchitectureName) { 330 Expected<StringRef> NameOrErr = C.getName(); 331 // TODO: if we have a error getting the name then it would be nice to print 332 // the index of which archive member this is and or its offset in the 333 // archive instead of "???" as the name. 334 if (!NameOrErr) { 335 consumeError(NameOrErr.takeError()); 336 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName); 337 } else 338 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E), 339 ArchitectureName); 340 } 341 342 static const Target *getTarget(const ObjectFile *Obj = nullptr) { 343 // Figure out the target triple. 344 llvm::Triple TheTriple("unknown-unknown-unknown"); 345 if (TripleName.empty()) { 346 if (Obj) { 347 TheTriple.setArch(Triple::ArchType(Obj->getArch())); 348 // TheTriple defaults to ELF, and COFF doesn't have an environment: 349 // the best we can do here is indicate that it is mach-o. 350 if (Obj->isMachO()) 351 TheTriple.setObjectFormat(Triple::MachO); 352 353 if (Obj->isCOFF()) { 354 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj); 355 if (COFFObj->getArch() == Triple::thumb) 356 TheTriple.setTriple("thumbv7-windows"); 357 } 358 } 359 } else 360 TheTriple.setTriple(Triple::normalize(TripleName)); 361 362 // Get the target specific parser. 363 std::string Error; 364 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, 365 Error); 366 if (!TheTarget) 367 report_fatal_error("can't find target: " + Error); 368 369 // Update the triple name and return the found target. 370 TripleName = TheTriple.getTriple(); 371 return TheTarget; 372 } 373 374 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) { 375 return a.getOffset() < b.getOffset(); 376 } 377 378 namespace { 379 class SourcePrinter { 380 protected: 381 DILineInfo OldLineInfo; 382 const ObjectFile *Obj; 383 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer; 384 // File name to file contents of source 385 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache; 386 // Mark the line endings of the cached source 387 std::unordered_map<std::string, std::vector<StringRef>> LineCache; 388 389 private: 390 bool cacheSource(std::string File); 391 392 public: 393 virtual ~SourcePrinter() {} 394 SourcePrinter() : Obj(nullptr), Symbolizer(nullptr) {} 395 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) { 396 symbolize::LLVMSymbolizer::Options SymbolizerOpts( 397 DILineInfoSpecifier::FunctionNameKind::None, true, false, false, 398 DefaultArch); 399 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts)); 400 } 401 virtual void printSourceLine(raw_ostream &OS, uint64_t Address, 402 StringRef Delimiter = "; "); 403 }; 404 405 bool SourcePrinter::cacheSource(std::string File) { 406 auto BufferOrError = MemoryBuffer::getFile(File); 407 if (!BufferOrError) 408 return false; 409 // Chomp the file to get lines 410 size_t BufferSize = (*BufferOrError)->getBufferSize(); 411 const char *BufferStart = (*BufferOrError)->getBufferStart(); 412 for (const char *Start = BufferStart, *End = BufferStart; 413 End < BufferStart + BufferSize; End++) 414 if (*End == '\n' || End == BufferStart + BufferSize - 1 || 415 (*End == '\r' && *(End + 1) == '\n')) { 416 LineCache[File].push_back(StringRef(Start, End - Start)); 417 if (*End == '\r') 418 End++; 419 Start = End + 1; 420 } 421 SourceCache[File] = std::move(*BufferOrError); 422 return true; 423 } 424 425 void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address, 426 StringRef Delimiter) { 427 if (!Symbolizer) 428 return; 429 DILineInfo LineInfo = DILineInfo(); 430 auto ExpectecLineInfo = 431 Symbolizer->symbolizeCode(Obj->getFileName(), Address); 432 if (!ExpectecLineInfo) 433 consumeError(ExpectecLineInfo.takeError()); 434 else 435 LineInfo = *ExpectecLineInfo; 436 437 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line || 438 LineInfo.Line == 0) 439 return; 440 441 if (PrintLines) 442 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n"; 443 if (PrintSource) { 444 if (SourceCache.find(LineInfo.FileName) == SourceCache.end()) 445 if (!cacheSource(LineInfo.FileName)) 446 return; 447 auto FileBuffer = SourceCache.find(LineInfo.FileName); 448 if (FileBuffer != SourceCache.end()) { 449 auto LineBuffer = LineCache.find(LineInfo.FileName); 450 if (LineBuffer != LineCache.end()) 451 // Vector begins at 0, line numbers are non-zero 452 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim() 453 << "\n"; 454 } 455 } 456 OldLineInfo = LineInfo; 457 } 458 459 class PrettyPrinter { 460 public: 461 virtual ~PrettyPrinter(){} 462 virtual void printInst(MCInstPrinter &IP, const MCInst *MI, 463 ArrayRef<uint8_t> Bytes, uint64_t Address, 464 raw_ostream &OS, StringRef Annot, 465 MCSubtargetInfo const &STI, SourcePrinter *SP) { 466 if (SP && (PrintSource || PrintLines)) 467 SP->printSourceLine(OS, Address); 468 OS << format("%8" PRIx64 ":", Address); 469 if (!NoShowRawInsn) { 470 OS << "\t"; 471 dumpBytes(Bytes, OS); 472 } 473 if (MI) 474 IP.printInst(MI, OS, "", STI); 475 else 476 OS << " <unknown>"; 477 } 478 }; 479 PrettyPrinter PrettyPrinterInst; 480 class HexagonPrettyPrinter : public PrettyPrinter { 481 public: 482 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address, 483 raw_ostream &OS) { 484 uint32_t opcode = 485 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0]; 486 OS << format("%8" PRIx64 ":", Address); 487 if (!NoShowRawInsn) { 488 OS << "\t"; 489 dumpBytes(Bytes.slice(0, 4), OS); 490 OS << format("%08" PRIx32, opcode); 491 } 492 } 493 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 494 uint64_t Address, raw_ostream &OS, StringRef Annot, 495 MCSubtargetInfo const &STI, SourcePrinter *SP) override { 496 if (!MI) { 497 printLead(Bytes, Address, OS); 498 OS << " <unknown>"; 499 return; 500 } 501 std::string Buffer; 502 { 503 raw_string_ostream TempStream(Buffer); 504 IP.printInst(MI, TempStream, "", STI); 505 } 506 StringRef Contents(Buffer); 507 // Split off bundle attributes 508 auto PacketBundle = Contents.rsplit('\n'); 509 // Split off first instruction from the rest 510 auto HeadTail = PacketBundle.first.split('\n'); 511 auto Preamble = " { "; 512 auto Separator = ""; 513 while(!HeadTail.first.empty()) { 514 OS << Separator; 515 Separator = "\n"; 516 printLead(Bytes, Address, OS); 517 OS << Preamble; 518 Preamble = " "; 519 StringRef Inst; 520 auto Duplex = HeadTail.first.split('\v'); 521 if(!Duplex.second.empty()){ 522 OS << Duplex.first; 523 OS << "; "; 524 Inst = Duplex.second; 525 } 526 else 527 Inst = HeadTail.first; 528 OS << Inst; 529 Bytes = Bytes.slice(4); 530 Address += 4; 531 HeadTail = HeadTail.second.split('\n'); 532 } 533 OS << " } " << PacketBundle.second; 534 } 535 }; 536 HexagonPrettyPrinter HexagonPrettyPrinterInst; 537 538 class AMDGCNPrettyPrinter : public PrettyPrinter { 539 public: 540 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 541 uint64_t Address, raw_ostream &OS, StringRef Annot, 542 MCSubtargetInfo const &STI, SourcePrinter *SP) override { 543 if (!MI) { 544 OS << " <unknown>"; 545 return; 546 } 547 548 SmallString<40> InstStr; 549 raw_svector_ostream IS(InstStr); 550 551 IP.printInst(MI, IS, "", STI); 552 553 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address); 554 typedef support::ulittle32_t U32; 555 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()), 556 Bytes.size() / sizeof(U32))) 557 // D should be explicitly casted to uint32_t here as it is passed 558 // by format to snprintf as vararg. 559 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D)); 560 561 if (!Annot.empty()) 562 OS << "// " << Annot; 563 } 564 }; 565 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst; 566 567 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) { 568 switch(Triple.getArch()) { 569 default: 570 return PrettyPrinterInst; 571 case Triple::hexagon: 572 return HexagonPrettyPrinterInst; 573 case Triple::amdgcn: 574 return AMDGCNPrettyPrinterInst; 575 } 576 } 577 } 578 579 template <class ELFT> 580 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj, 581 const RelocationRef &RelRef, 582 SmallVectorImpl<char> &Result) { 583 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 584 585 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym; 586 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr; 587 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela; 588 589 const ELFFile<ELFT> &EF = *Obj->getELFFile(); 590 591 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a); 592 if (std::error_code EC = SecOrErr.getError()) 593 return EC; 594 const Elf_Shdr *Sec = *SecOrErr; 595 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link); 596 if (std::error_code EC = SymTabOrErr.getError()) 597 return EC; 598 const Elf_Shdr *SymTab = *SymTabOrErr; 599 assert(SymTab->sh_type == ELF::SHT_SYMTAB || 600 SymTab->sh_type == ELF::SHT_DYNSYM); 601 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link); 602 if (std::error_code EC = StrTabSec.getError()) 603 return EC; 604 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec); 605 if (std::error_code EC = StrTabOrErr.getError()) 606 return EC; 607 StringRef StrTab = *StrTabOrErr; 608 uint8_t type = RelRef.getType(); 609 StringRef res; 610 int64_t addend = 0; 611 switch (Sec->sh_type) { 612 default: 613 return object_error::parse_failed; 614 case ELF::SHT_REL: { 615 // TODO: Read implicit addend from section data. 616 break; 617 } 618 case ELF::SHT_RELA: { 619 const Elf_Rela *ERela = Obj->getRela(Rel); 620 addend = ERela->r_addend; 621 break; 622 } 623 } 624 symbol_iterator SI = RelRef.getSymbol(); 625 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl()); 626 StringRef Target; 627 if (symb->getType() == ELF::STT_SECTION) { 628 Expected<section_iterator> SymSI = SI->getSection(); 629 if (!SymSI) 630 return errorToErrorCode(SymSI.takeError()); 631 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl()); 632 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec); 633 if (std::error_code EC = SecName.getError()) 634 return EC; 635 Target = *SecName; 636 } else { 637 Expected<StringRef> SymName = symb->getName(StrTab); 638 if (!SymName) 639 return errorToErrorCode(SymName.takeError()); 640 Target = *SymName; 641 } 642 switch (EF.getHeader()->e_machine) { 643 case ELF::EM_X86_64: 644 switch (type) { 645 case ELF::R_X86_64_PC8: 646 case ELF::R_X86_64_PC16: 647 case ELF::R_X86_64_PC32: { 648 std::string fmtbuf; 649 raw_string_ostream fmt(fmtbuf); 650 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P"; 651 fmt.flush(); 652 Result.append(fmtbuf.begin(), fmtbuf.end()); 653 } break; 654 case ELF::R_X86_64_8: 655 case ELF::R_X86_64_16: 656 case ELF::R_X86_64_32: 657 case ELF::R_X86_64_32S: 658 case ELF::R_X86_64_64: { 659 std::string fmtbuf; 660 raw_string_ostream fmt(fmtbuf); 661 fmt << Target << (addend < 0 ? "" : "+") << addend; 662 fmt.flush(); 663 Result.append(fmtbuf.begin(), fmtbuf.end()); 664 } break; 665 default: 666 res = "Unknown"; 667 } 668 break; 669 case ELF::EM_LANAI: 670 case ELF::EM_AARCH64: { 671 std::string fmtbuf; 672 raw_string_ostream fmt(fmtbuf); 673 fmt << Target; 674 if (addend != 0) 675 fmt << (addend < 0 ? "" : "+") << addend; 676 fmt.flush(); 677 Result.append(fmtbuf.begin(), fmtbuf.end()); 678 break; 679 } 680 case ELF::EM_386: 681 case ELF::EM_IAMCU: 682 case ELF::EM_ARM: 683 case ELF::EM_HEXAGON: 684 case ELF::EM_MIPS: 685 case ELF::EM_BPF: 686 res = Target; 687 break; 688 case ELF::EM_WEBASSEMBLY: 689 switch (type) { 690 case ELF::R_WEBASSEMBLY_DATA: { 691 std::string fmtbuf; 692 raw_string_ostream fmt(fmtbuf); 693 fmt << Target << (addend < 0 ? "" : "+") << addend; 694 fmt.flush(); 695 Result.append(fmtbuf.begin(), fmtbuf.end()); 696 break; 697 } 698 case ELF::R_WEBASSEMBLY_FUNCTION: 699 res = Target; 700 break; 701 default: 702 res = "Unknown"; 703 } 704 break; 705 default: 706 res = "Unknown"; 707 } 708 if (Result.empty()) 709 Result.append(res.begin(), res.end()); 710 return std::error_code(); 711 } 712 713 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj, 714 const RelocationRef &Rel, 715 SmallVectorImpl<char> &Result) { 716 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj)) 717 return getRelocationValueString(ELF32LE, Rel, Result); 718 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj)) 719 return getRelocationValueString(ELF64LE, Rel, Result); 720 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj)) 721 return getRelocationValueString(ELF32BE, Rel, Result); 722 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj); 723 return getRelocationValueString(ELF64BE, Rel, Result); 724 } 725 726 static std::error_code getRelocationValueString(const COFFObjectFile *Obj, 727 const RelocationRef &Rel, 728 SmallVectorImpl<char> &Result) { 729 symbol_iterator SymI = Rel.getSymbol(); 730 Expected<StringRef> SymNameOrErr = SymI->getName(); 731 if (!SymNameOrErr) 732 return errorToErrorCode(SymNameOrErr.takeError()); 733 StringRef SymName = *SymNameOrErr; 734 Result.append(SymName.begin(), SymName.end()); 735 return std::error_code(); 736 } 737 738 static void printRelocationTargetName(const MachOObjectFile *O, 739 const MachO::any_relocation_info &RE, 740 raw_string_ostream &fmt) { 741 bool IsScattered = O->isRelocationScattered(RE); 742 743 // Target of a scattered relocation is an address. In the interest of 744 // generating pretty output, scan through the symbol table looking for a 745 // symbol that aligns with that address. If we find one, print it. 746 // Otherwise, we just print the hex address of the target. 747 if (IsScattered) { 748 uint32_t Val = O->getPlainRelocationSymbolNum(RE); 749 750 for (const SymbolRef &Symbol : O->symbols()) { 751 std::error_code ec; 752 Expected<uint64_t> Addr = Symbol.getAddress(); 753 if (!Addr) { 754 std::string Buf; 755 raw_string_ostream OS(Buf); 756 logAllUnhandledErrors(Addr.takeError(), OS, ""); 757 OS.flush(); 758 report_fatal_error(Buf); 759 } 760 if (*Addr != Val) 761 continue; 762 Expected<StringRef> Name = Symbol.getName(); 763 if (!Name) { 764 std::string Buf; 765 raw_string_ostream OS(Buf); 766 logAllUnhandledErrors(Name.takeError(), OS, ""); 767 OS.flush(); 768 report_fatal_error(Buf); 769 } 770 fmt << *Name; 771 return; 772 } 773 774 // If we couldn't find a symbol that this relocation refers to, try 775 // to find a section beginning instead. 776 for (const SectionRef &Section : ToolSectionFilter(*O)) { 777 std::error_code ec; 778 779 StringRef Name; 780 uint64_t Addr = Section.getAddress(); 781 if (Addr != Val) 782 continue; 783 if ((ec = Section.getName(Name))) 784 report_fatal_error(ec.message()); 785 fmt << Name; 786 return; 787 } 788 789 fmt << format("0x%x", Val); 790 return; 791 } 792 793 StringRef S; 794 bool isExtern = O->getPlainRelocationExternal(RE); 795 uint64_t Val = O->getPlainRelocationSymbolNum(RE); 796 797 if (isExtern) { 798 symbol_iterator SI = O->symbol_begin(); 799 advance(SI, Val); 800 Expected<StringRef> SOrErr = SI->getName(); 801 error(errorToErrorCode(SOrErr.takeError())); 802 S = *SOrErr; 803 } else { 804 section_iterator SI = O->section_begin(); 805 // Adjust for the fact that sections are 1-indexed. 806 advance(SI, Val - 1); 807 SI->getName(S); 808 } 809 810 fmt << S; 811 } 812 813 static std::error_code getRelocationValueString(const MachOObjectFile *Obj, 814 const RelocationRef &RelRef, 815 SmallVectorImpl<char> &Result) { 816 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 817 MachO::any_relocation_info RE = Obj->getRelocation(Rel); 818 819 unsigned Arch = Obj->getArch(); 820 821 std::string fmtbuf; 822 raw_string_ostream fmt(fmtbuf); 823 unsigned Type = Obj->getAnyRelocationType(RE); 824 bool IsPCRel = Obj->getAnyRelocationPCRel(RE); 825 826 // Determine any addends that should be displayed with the relocation. 827 // These require decoding the relocation type, which is triple-specific. 828 829 // X86_64 has entirely custom relocation types. 830 if (Arch == Triple::x86_64) { 831 bool isPCRel = Obj->getAnyRelocationPCRel(RE); 832 833 switch (Type) { 834 case MachO::X86_64_RELOC_GOT_LOAD: 835 case MachO::X86_64_RELOC_GOT: { 836 printRelocationTargetName(Obj, RE, fmt); 837 fmt << "@GOT"; 838 if (isPCRel) 839 fmt << "PCREL"; 840 break; 841 } 842 case MachO::X86_64_RELOC_SUBTRACTOR: { 843 DataRefImpl RelNext = Rel; 844 Obj->moveRelocationNext(RelNext); 845 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 846 847 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type 848 // X86_64_RELOC_UNSIGNED. 849 // NOTE: Scattered relocations don't exist on x86_64. 850 unsigned RType = Obj->getAnyRelocationType(RENext); 851 if (RType != MachO::X86_64_RELOC_UNSIGNED) 852 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after " 853 "X86_64_RELOC_SUBTRACTOR."); 854 855 // The X86_64_RELOC_UNSIGNED contains the minuend symbol; 856 // X86_64_RELOC_SUBTRACTOR contains the subtrahend. 857 printRelocationTargetName(Obj, RENext, fmt); 858 fmt << "-"; 859 printRelocationTargetName(Obj, RE, fmt); 860 break; 861 } 862 case MachO::X86_64_RELOC_TLV: 863 printRelocationTargetName(Obj, RE, fmt); 864 fmt << "@TLV"; 865 if (isPCRel) 866 fmt << "P"; 867 break; 868 case MachO::X86_64_RELOC_SIGNED_1: 869 printRelocationTargetName(Obj, RE, fmt); 870 fmt << "-1"; 871 break; 872 case MachO::X86_64_RELOC_SIGNED_2: 873 printRelocationTargetName(Obj, RE, fmt); 874 fmt << "-2"; 875 break; 876 case MachO::X86_64_RELOC_SIGNED_4: 877 printRelocationTargetName(Obj, RE, fmt); 878 fmt << "-4"; 879 break; 880 default: 881 printRelocationTargetName(Obj, RE, fmt); 882 break; 883 } 884 // X86 and ARM share some relocation types in common. 885 } else if (Arch == Triple::x86 || Arch == Triple::arm || 886 Arch == Triple::ppc) { 887 // Generic relocation types... 888 switch (Type) { 889 case MachO::GENERIC_RELOC_PAIR: // prints no info 890 return std::error_code(); 891 case MachO::GENERIC_RELOC_SECTDIFF: { 892 DataRefImpl RelNext = Rel; 893 Obj->moveRelocationNext(RelNext); 894 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 895 896 // X86 sect diff's must be followed by a relocation of type 897 // GENERIC_RELOC_PAIR. 898 unsigned RType = Obj->getAnyRelocationType(RENext); 899 900 if (RType != MachO::GENERIC_RELOC_PAIR) 901 report_fatal_error("Expected GENERIC_RELOC_PAIR after " 902 "GENERIC_RELOC_SECTDIFF."); 903 904 printRelocationTargetName(Obj, RE, fmt); 905 fmt << "-"; 906 printRelocationTargetName(Obj, RENext, fmt); 907 break; 908 } 909 } 910 911 if (Arch == Triple::x86 || Arch == Triple::ppc) { 912 switch (Type) { 913 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: { 914 DataRefImpl RelNext = Rel; 915 Obj->moveRelocationNext(RelNext); 916 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 917 918 // X86 sect diff's must be followed by a relocation of type 919 // GENERIC_RELOC_PAIR. 920 unsigned RType = Obj->getAnyRelocationType(RENext); 921 if (RType != MachO::GENERIC_RELOC_PAIR) 922 report_fatal_error("Expected GENERIC_RELOC_PAIR after " 923 "GENERIC_RELOC_LOCAL_SECTDIFF."); 924 925 printRelocationTargetName(Obj, RE, fmt); 926 fmt << "-"; 927 printRelocationTargetName(Obj, RENext, fmt); 928 break; 929 } 930 case MachO::GENERIC_RELOC_TLV: { 931 printRelocationTargetName(Obj, RE, fmt); 932 fmt << "@TLV"; 933 if (IsPCRel) 934 fmt << "P"; 935 break; 936 } 937 default: 938 printRelocationTargetName(Obj, RE, fmt); 939 } 940 } else { // ARM-specific relocations 941 switch (Type) { 942 case MachO::ARM_RELOC_HALF: 943 case MachO::ARM_RELOC_HALF_SECTDIFF: { 944 // Half relocations steal a bit from the length field to encode 945 // whether this is an upper16 or a lower16 relocation. 946 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1; 947 948 if (isUpper) 949 fmt << ":upper16:("; 950 else 951 fmt << ":lower16:("; 952 printRelocationTargetName(Obj, RE, fmt); 953 954 DataRefImpl RelNext = Rel; 955 Obj->moveRelocationNext(RelNext); 956 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 957 958 // ARM half relocs must be followed by a relocation of type 959 // ARM_RELOC_PAIR. 960 unsigned RType = Obj->getAnyRelocationType(RENext); 961 if (RType != MachO::ARM_RELOC_PAIR) 962 report_fatal_error("Expected ARM_RELOC_PAIR after " 963 "ARM_RELOC_HALF"); 964 965 // NOTE: The half of the target virtual address is stashed in the 966 // address field of the secondary relocation, but we can't reverse 967 // engineer the constant offset from it without decoding the movw/movt 968 // instruction to find the other half in its immediate field. 969 970 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the 971 // symbol/section pointer of the follow-on relocation. 972 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) { 973 fmt << "-"; 974 printRelocationTargetName(Obj, RENext, fmt); 975 } 976 977 fmt << ")"; 978 break; 979 } 980 default: { printRelocationTargetName(Obj, RE, fmt); } 981 } 982 } 983 } else 984 printRelocationTargetName(Obj, RE, fmt); 985 986 fmt.flush(); 987 Result.append(fmtbuf.begin(), fmtbuf.end()); 988 return std::error_code(); 989 } 990 991 static std::error_code getRelocationValueString(const RelocationRef &Rel, 992 SmallVectorImpl<char> &Result) { 993 const ObjectFile *Obj = Rel.getObject(); 994 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj)) 995 return getRelocationValueString(ELF, Rel, Result); 996 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj)) 997 return getRelocationValueString(COFF, Rel, Result); 998 auto *MachO = cast<MachOObjectFile>(Obj); 999 return getRelocationValueString(MachO, Rel, Result); 1000 } 1001 1002 /// @brief Indicates whether this relocation should hidden when listing 1003 /// relocations, usually because it is the trailing part of a multipart 1004 /// relocation that will be printed as part of the leading relocation. 1005 static bool getHidden(RelocationRef RelRef) { 1006 const ObjectFile *Obj = RelRef.getObject(); 1007 auto *MachO = dyn_cast<MachOObjectFile>(Obj); 1008 if (!MachO) 1009 return false; 1010 1011 unsigned Arch = MachO->getArch(); 1012 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 1013 uint64_t Type = MachO->getRelocationType(Rel); 1014 1015 // On arches that use the generic relocations, GENERIC_RELOC_PAIR 1016 // is always hidden. 1017 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) { 1018 if (Type == MachO::GENERIC_RELOC_PAIR) 1019 return true; 1020 } else if (Arch == Triple::x86_64) { 1021 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows 1022 // an X86_64_RELOC_SUBTRACTOR. 1023 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) { 1024 DataRefImpl RelPrev = Rel; 1025 RelPrev.d.a--; 1026 uint64_t PrevType = MachO->getRelocationType(RelPrev); 1027 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR) 1028 return true; 1029 } 1030 } 1031 1032 return false; 1033 } 1034 1035 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) { 1036 const Target *TheTarget = getTarget(Obj); 1037 1038 // Package up features to be passed to target/subtarget 1039 SubtargetFeatures Features = Obj->getFeatures(); 1040 if (MAttrs.size()) { 1041 for (unsigned i = 0; i != MAttrs.size(); ++i) 1042 Features.AddFeature(MAttrs[i]); 1043 } 1044 1045 std::unique_ptr<const MCRegisterInfo> MRI( 1046 TheTarget->createMCRegInfo(TripleName)); 1047 if (!MRI) 1048 report_fatal_error("error: no register info for target " + TripleName); 1049 1050 // Set up disassembler. 1051 std::unique_ptr<const MCAsmInfo> AsmInfo( 1052 TheTarget->createMCAsmInfo(*MRI, TripleName)); 1053 if (!AsmInfo) 1054 report_fatal_error("error: no assembly info for target " + TripleName); 1055 std::unique_ptr<const MCSubtargetInfo> STI( 1056 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString())); 1057 if (!STI) 1058 report_fatal_error("error: no subtarget info for target " + TripleName); 1059 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); 1060 if (!MII) 1061 report_fatal_error("error: no instruction info for target " + TripleName); 1062 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo); 1063 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get()); 1064 1065 std::unique_ptr<MCDisassembler> DisAsm( 1066 TheTarget->createMCDisassembler(*STI, Ctx)); 1067 if (!DisAsm) 1068 report_fatal_error("error: no disassembler for target " + TripleName); 1069 1070 std::unique_ptr<const MCInstrAnalysis> MIA( 1071 TheTarget->createMCInstrAnalysis(MII.get())); 1072 1073 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 1074 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 1075 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI)); 1076 if (!IP) 1077 report_fatal_error("error: no instruction printer for target " + 1078 TripleName); 1079 IP->setPrintImmHex(PrintImmHex); 1080 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName)); 1081 1082 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " : 1083 "\t\t\t%08" PRIx64 ": "; 1084 1085 SourcePrinter SP(Obj, TheTarget->getName()); 1086 1087 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections 1088 // in RelocSecs contain the relocations for section S. 1089 std::error_code EC; 1090 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap; 1091 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1092 section_iterator Sec2 = Section.getRelocatedSection(); 1093 if (Sec2 != Obj->section_end()) 1094 SectionRelocMap[*Sec2].push_back(Section); 1095 } 1096 1097 // Create a mapping from virtual address to symbol name. This is used to 1098 // pretty print the symbols while disassembling. 1099 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy; 1100 std::map<SectionRef, SectionSymbolsTy> AllSymbols; 1101 for (const SymbolRef &Symbol : Obj->symbols()) { 1102 Expected<uint64_t> AddressOrErr = Symbol.getAddress(); 1103 error(errorToErrorCode(AddressOrErr.takeError())); 1104 uint64_t Address = *AddressOrErr; 1105 1106 Expected<StringRef> Name = Symbol.getName(); 1107 error(errorToErrorCode(Name.takeError())); 1108 if (Name->empty()) 1109 continue; 1110 1111 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 1112 error(errorToErrorCode(SectionOrErr.takeError())); 1113 section_iterator SecI = *SectionOrErr; 1114 if (SecI == Obj->section_end()) 1115 continue; 1116 1117 AllSymbols[*SecI].emplace_back(Address, *Name); 1118 } 1119 1120 // Create a mapping from virtual address to section. 1121 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses; 1122 for (SectionRef Sec : Obj->sections()) 1123 SectionAddresses.emplace_back(Sec.getAddress(), Sec); 1124 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end()); 1125 1126 // Linked executables (.exe and .dll files) typically don't include a real 1127 // symbol table but they might contain an export table. 1128 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) { 1129 for (const auto &ExportEntry : COFFObj->export_directories()) { 1130 StringRef Name; 1131 error(ExportEntry.getSymbolName(Name)); 1132 if (Name.empty()) 1133 continue; 1134 uint32_t RVA; 1135 error(ExportEntry.getExportRVA(RVA)); 1136 1137 uint64_t VA = COFFObj->getImageBase() + RVA; 1138 auto Sec = std::upper_bound( 1139 SectionAddresses.begin(), SectionAddresses.end(), VA, 1140 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) { 1141 return LHS < RHS.first; 1142 }); 1143 if (Sec != SectionAddresses.begin()) 1144 --Sec; 1145 else 1146 Sec = SectionAddresses.end(); 1147 1148 if (Sec != SectionAddresses.end()) 1149 AllSymbols[Sec->second].emplace_back(VA, Name); 1150 } 1151 } 1152 1153 // Sort all the symbols, this allows us to use a simple binary search to find 1154 // a symbol near an address. 1155 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols) 1156 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end()); 1157 1158 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1159 if (!DisassembleAll && (!Section.isText() || Section.isVirtual())) 1160 continue; 1161 1162 uint64_t SectionAddr = Section.getAddress(); 1163 uint64_t SectSize = Section.getSize(); 1164 if (!SectSize) 1165 continue; 1166 1167 // Get the list of all the symbols in this section. 1168 SectionSymbolsTy &Symbols = AllSymbols[Section]; 1169 std::vector<uint64_t> DataMappingSymsAddr; 1170 std::vector<uint64_t> TextMappingSymsAddr; 1171 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) { 1172 for (const auto &Symb : Symbols) { 1173 uint64_t Address = Symb.first; 1174 StringRef Name = Symb.second; 1175 if (Name.startswith("$d")) 1176 DataMappingSymsAddr.push_back(Address - SectionAddr); 1177 if (Name.startswith("$x")) 1178 TextMappingSymsAddr.push_back(Address - SectionAddr); 1179 } 1180 } 1181 1182 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end()); 1183 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end()); 1184 1185 // Make a list of all the relocations for this section. 1186 std::vector<RelocationRef> Rels; 1187 if (InlineRelocs) { 1188 for (const SectionRef &RelocSec : SectionRelocMap[Section]) { 1189 for (const RelocationRef &Reloc : RelocSec.relocations()) { 1190 Rels.push_back(Reloc); 1191 } 1192 } 1193 } 1194 1195 // Sort relocations by address. 1196 std::sort(Rels.begin(), Rels.end(), RelocAddressLess); 1197 1198 StringRef SegmentName = ""; 1199 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) { 1200 DataRefImpl DR = Section.getRawDataRefImpl(); 1201 SegmentName = MachO->getSectionFinalSegmentName(DR); 1202 } 1203 StringRef name; 1204 error(Section.getName(name)); 1205 outs() << "Disassembly of section "; 1206 if (!SegmentName.empty()) 1207 outs() << SegmentName << ","; 1208 outs() << name << ':'; 1209 1210 // If the section has no symbol at the start, just insert a dummy one. 1211 if (Symbols.empty() || Symbols[0].first != 0) 1212 Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name)); 1213 1214 SmallString<40> Comments; 1215 raw_svector_ostream CommentStream(Comments); 1216 1217 StringRef BytesStr; 1218 error(Section.getContents(BytesStr)); 1219 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()), 1220 BytesStr.size()); 1221 1222 uint64_t Size; 1223 uint64_t Index; 1224 1225 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin(); 1226 std::vector<RelocationRef>::const_iterator rel_end = Rels.end(); 1227 // Disassemble symbol by symbol. 1228 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) { 1229 1230 uint64_t Start = Symbols[si].first - SectionAddr; 1231 // The end is either the section end or the beginning of the next 1232 // symbol. 1233 uint64_t End = 1234 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr; 1235 // Don't try to disassemble beyond the end of section contents. 1236 if (End > SectSize) 1237 End = SectSize; 1238 // If this symbol has the same address as the next symbol, then skip it. 1239 if (Start >= End) 1240 continue; 1241 1242 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1243 // make size 4 bytes folded 1244 End = Start + ((End - Start) & ~0x3ull); 1245 Start += 256; // add sizeof(amd_kernel_code_t) 1246 // cut trailing zeroes - up to 256 bytes (align) 1247 const uint64_t EndAlign = 256; 1248 const auto Limit = End - (std::min)(EndAlign, End - Start); 1249 while (End > Limit && 1250 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0) 1251 End -= 4; 1252 } 1253 1254 outs() << '\n' << Symbols[si].second << ":\n"; 1255 1256 #ifndef NDEBUG 1257 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); 1258 #else 1259 raw_ostream &DebugOut = nulls(); 1260 #endif 1261 1262 for (Index = Start; Index < End; Index += Size) { 1263 MCInst Inst; 1264 1265 // AArch64 ELF binaries can interleave data and text in the 1266 // same section. We rely on the markers introduced to 1267 // understand what we need to dump. 1268 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) { 1269 uint64_t Stride = 0; 1270 1271 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(), 1272 DataMappingSymsAddr.end(), Index); 1273 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) { 1274 // Switch to data. 1275 while (Index < End) { 1276 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 1277 outs() << "\t"; 1278 if (Index + 4 <= End) { 1279 Stride = 4; 1280 dumpBytes(Bytes.slice(Index, 4), outs()); 1281 outs() << "\t.word"; 1282 } else if (Index + 2 <= End) { 1283 Stride = 2; 1284 dumpBytes(Bytes.slice(Index, 2), outs()); 1285 outs() << "\t.short"; 1286 } else { 1287 Stride = 1; 1288 dumpBytes(Bytes.slice(Index, 1), outs()); 1289 outs() << "\t.byte"; 1290 } 1291 Index += Stride; 1292 outs() << "\n"; 1293 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(), 1294 TextMappingSymsAddr.end(), Index); 1295 if (TAI != TextMappingSymsAddr.end() && *TAI == Index) 1296 break; 1297 } 1298 } 1299 } 1300 1301 if (Index >= End) 1302 break; 1303 1304 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), 1305 SectionAddr + Index, DebugOut, 1306 CommentStream); 1307 if (Size == 0) 1308 Size = 1; 1309 1310 PIP.printInst(*IP, Disassembled ? &Inst : nullptr, 1311 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "", 1312 *STI, &SP); 1313 outs() << CommentStream.str(); 1314 Comments.clear(); 1315 1316 // Try to resolve the target of a call, tail call, etc. to a specific 1317 // symbol. 1318 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) || 1319 MIA->isConditionalBranch(Inst))) { 1320 uint64_t Target; 1321 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) { 1322 // In a relocatable object, the target's section must reside in 1323 // the same section as the call instruction or it is accessed 1324 // through a relocation. 1325 // 1326 // In a non-relocatable object, the target may be in any section. 1327 // 1328 // N.B. We don't walk the relocations in the relocatable case yet. 1329 auto *TargetSectionSymbols = &Symbols; 1330 if (!Obj->isRelocatableObject()) { 1331 auto SectionAddress = std::upper_bound( 1332 SectionAddresses.begin(), SectionAddresses.end(), Target, 1333 [](uint64_t LHS, 1334 const std::pair<uint64_t, SectionRef> &RHS) { 1335 return LHS < RHS.first; 1336 }); 1337 if (SectionAddress != SectionAddresses.begin()) { 1338 --SectionAddress; 1339 TargetSectionSymbols = &AllSymbols[SectionAddress->second]; 1340 } else { 1341 TargetSectionSymbols = nullptr; 1342 } 1343 } 1344 1345 // Find the first symbol in the section whose offset is less than 1346 // or equal to the target. 1347 if (TargetSectionSymbols) { 1348 auto TargetSym = std::upper_bound( 1349 TargetSectionSymbols->begin(), TargetSectionSymbols->end(), 1350 Target, [](uint64_t LHS, 1351 const std::pair<uint64_t, StringRef> &RHS) { 1352 return LHS < RHS.first; 1353 }); 1354 if (TargetSym != TargetSectionSymbols->begin()) { 1355 --TargetSym; 1356 uint64_t TargetAddress = std::get<0>(*TargetSym); 1357 StringRef TargetName = std::get<1>(*TargetSym); 1358 outs() << " <" << TargetName; 1359 uint64_t Disp = Target - TargetAddress; 1360 if (Disp) 1361 outs() << "+0x" << utohexstr(Disp); 1362 outs() << '>'; 1363 } 1364 } 1365 } 1366 } 1367 outs() << "\n"; 1368 1369 // Print relocation for instruction. 1370 while (rel_cur != rel_end) { 1371 bool hidden = getHidden(*rel_cur); 1372 uint64_t addr = rel_cur->getOffset(); 1373 SmallString<16> name; 1374 SmallString<32> val; 1375 1376 // If this relocation is hidden, skip it. 1377 if (hidden) goto skip_print_rel; 1378 1379 // Stop when rel_cur's address is past the current instruction. 1380 if (addr >= Index + Size) break; 1381 rel_cur->getTypeName(name); 1382 error(getRelocationValueString(*rel_cur, val)); 1383 outs() << format(Fmt.data(), SectionAddr + addr) << name 1384 << "\t" << val << "\n"; 1385 1386 skip_print_rel: 1387 ++rel_cur; 1388 } 1389 } 1390 } 1391 } 1392 } 1393 1394 void llvm::PrintRelocations(const ObjectFile *Obj) { 1395 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : 1396 "%08" PRIx64; 1397 // Regular objdump doesn't print relocations in non-relocatable object 1398 // files. 1399 if (!Obj->isRelocatableObject()) 1400 return; 1401 1402 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1403 if (Section.relocation_begin() == Section.relocation_end()) 1404 continue; 1405 StringRef secname; 1406 error(Section.getName(secname)); 1407 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n"; 1408 for (const RelocationRef &Reloc : Section.relocations()) { 1409 bool hidden = getHidden(Reloc); 1410 uint64_t address = Reloc.getOffset(); 1411 SmallString<32> relocname; 1412 SmallString<32> valuestr; 1413 if (hidden) 1414 continue; 1415 Reloc.getTypeName(relocname); 1416 error(getRelocationValueString(Reloc, valuestr)); 1417 outs() << format(Fmt.data(), address) << " " << relocname << " " 1418 << valuestr << "\n"; 1419 } 1420 outs() << "\n"; 1421 } 1422 } 1423 1424 void llvm::PrintSectionHeaders(const ObjectFile *Obj) { 1425 outs() << "Sections:\n" 1426 "Idx Name Size Address Type\n"; 1427 unsigned i = 0; 1428 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1429 StringRef Name; 1430 error(Section.getName(Name)); 1431 uint64_t Address = Section.getAddress(); 1432 uint64_t Size = Section.getSize(); 1433 bool Text = Section.isText(); 1434 bool Data = Section.isData(); 1435 bool BSS = Section.isBSS(); 1436 std::string Type = (std::string(Text ? "TEXT " : "") + 1437 (Data ? "DATA " : "") + (BSS ? "BSS" : "")); 1438 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i, 1439 Name.str().c_str(), Size, Address, Type.c_str()); 1440 ++i; 1441 } 1442 } 1443 1444 void llvm::PrintSectionContents(const ObjectFile *Obj) { 1445 std::error_code EC; 1446 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1447 StringRef Name; 1448 StringRef Contents; 1449 error(Section.getName(Name)); 1450 uint64_t BaseAddr = Section.getAddress(); 1451 uint64_t Size = Section.getSize(); 1452 if (!Size) 1453 continue; 1454 1455 outs() << "Contents of section " << Name << ":\n"; 1456 if (Section.isBSS()) { 1457 outs() << format("<skipping contents of bss section at [%04" PRIx64 1458 ", %04" PRIx64 ")>\n", 1459 BaseAddr, BaseAddr + Size); 1460 continue; 1461 } 1462 1463 error(Section.getContents(Contents)); 1464 1465 // Dump out the content as hex and printable ascii characters. 1466 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) { 1467 outs() << format(" %04" PRIx64 " ", BaseAddr + addr); 1468 // Dump line of hex. 1469 for (std::size_t i = 0; i < 16; ++i) { 1470 if (i != 0 && i % 4 == 0) 1471 outs() << ' '; 1472 if (addr + i < end) 1473 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true) 1474 << hexdigit(Contents[addr + i] & 0xF, true); 1475 else 1476 outs() << " "; 1477 } 1478 // Print ascii. 1479 outs() << " "; 1480 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) { 1481 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF)) 1482 outs() << Contents[addr + i]; 1483 else 1484 outs() << "."; 1485 } 1486 outs() << "\n"; 1487 } 1488 } 1489 } 1490 1491 void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName, 1492 StringRef ArchitectureName) { 1493 outs() << "SYMBOL TABLE:\n"; 1494 1495 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) { 1496 printCOFFSymbolTable(coff); 1497 return; 1498 } 1499 for (const SymbolRef &Symbol : o->symbols()) { 1500 Expected<uint64_t> AddressOrError = Symbol.getAddress(); 1501 if (!AddressOrError) 1502 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError()); 1503 uint64_t Address = *AddressOrError; 1504 Expected<SymbolRef::Type> TypeOrError = Symbol.getType(); 1505 if (!TypeOrError) 1506 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError()); 1507 SymbolRef::Type Type = *TypeOrError; 1508 uint32_t Flags = Symbol.getFlags(); 1509 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 1510 error(errorToErrorCode(SectionOrErr.takeError())); 1511 section_iterator Section = *SectionOrErr; 1512 StringRef Name; 1513 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) { 1514 Section->getName(Name); 1515 } else { 1516 Expected<StringRef> NameOrErr = Symbol.getName(); 1517 if (!NameOrErr) 1518 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(), 1519 ArchitectureName); 1520 Name = *NameOrErr; 1521 } 1522 1523 bool Global = Flags & SymbolRef::SF_Global; 1524 bool Weak = Flags & SymbolRef::SF_Weak; 1525 bool Absolute = Flags & SymbolRef::SF_Absolute; 1526 bool Common = Flags & SymbolRef::SF_Common; 1527 bool Hidden = Flags & SymbolRef::SF_Hidden; 1528 1529 char GlobLoc = ' '; 1530 if (Type != SymbolRef::ST_Unknown) 1531 GlobLoc = Global ? 'g' : 'l'; 1532 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 1533 ? 'd' : ' '; 1534 char FileFunc = ' '; 1535 if (Type == SymbolRef::ST_File) 1536 FileFunc = 'f'; 1537 else if (Type == SymbolRef::ST_Function) 1538 FileFunc = 'F'; 1539 1540 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : 1541 "%08" PRIx64; 1542 1543 outs() << format(Fmt, Address) << " " 1544 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 1545 << (Weak ? 'w' : ' ') // Weak? 1546 << ' ' // Constructor. Not supported yet. 1547 << ' ' // Warning. Not supported yet. 1548 << ' ' // Indirect reference to another symbol. 1549 << Debug // Debugging (d) or dynamic (D) symbol. 1550 << FileFunc // Name of function (F), file (f) or object (O). 1551 << ' '; 1552 if (Absolute) { 1553 outs() << "*ABS*"; 1554 } else if (Common) { 1555 outs() << "*COM*"; 1556 } else if (Section == o->section_end()) { 1557 outs() << "*UND*"; 1558 } else { 1559 if (const MachOObjectFile *MachO = 1560 dyn_cast<const MachOObjectFile>(o)) { 1561 DataRefImpl DR = Section->getRawDataRefImpl(); 1562 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 1563 outs() << SegmentName << ","; 1564 } 1565 StringRef SectionName; 1566 error(Section->getName(SectionName)); 1567 outs() << SectionName; 1568 } 1569 1570 outs() << '\t'; 1571 if (Common || isa<ELFObjectFileBase>(o)) { 1572 uint64_t Val = 1573 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize(); 1574 outs() << format("\t %08" PRIx64 " ", Val); 1575 } 1576 1577 if (Hidden) { 1578 outs() << ".hidden "; 1579 } 1580 outs() << Name 1581 << '\n'; 1582 } 1583 } 1584 1585 static void PrintUnwindInfo(const ObjectFile *o) { 1586 outs() << "Unwind info:\n\n"; 1587 1588 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) { 1589 printCOFFUnwindInfo(coff); 1590 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1591 printMachOUnwindInfo(MachO); 1592 else { 1593 // TODO: Extract DWARF dump tool to objdump. 1594 errs() << "This operation is only currently supported " 1595 "for COFF and MachO object files.\n"; 1596 return; 1597 } 1598 } 1599 1600 void llvm::printExportsTrie(const ObjectFile *o) { 1601 outs() << "Exports trie:\n"; 1602 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1603 printMachOExportsTrie(MachO); 1604 else { 1605 errs() << "This operation is only currently supported " 1606 "for Mach-O executable files.\n"; 1607 return; 1608 } 1609 } 1610 1611 void llvm::printRebaseTable(const ObjectFile *o) { 1612 outs() << "Rebase table:\n"; 1613 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1614 printMachORebaseTable(MachO); 1615 else { 1616 errs() << "This operation is only currently supported " 1617 "for Mach-O executable files.\n"; 1618 return; 1619 } 1620 } 1621 1622 void llvm::printBindTable(const ObjectFile *o) { 1623 outs() << "Bind table:\n"; 1624 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1625 printMachOBindTable(MachO); 1626 else { 1627 errs() << "This operation is only currently supported " 1628 "for Mach-O executable files.\n"; 1629 return; 1630 } 1631 } 1632 1633 void llvm::printLazyBindTable(const ObjectFile *o) { 1634 outs() << "Lazy bind table:\n"; 1635 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1636 printMachOLazyBindTable(MachO); 1637 else { 1638 errs() << "This operation is only currently supported " 1639 "for Mach-O executable files.\n"; 1640 return; 1641 } 1642 } 1643 1644 void llvm::printWeakBindTable(const ObjectFile *o) { 1645 outs() << "Weak bind table:\n"; 1646 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1647 printMachOWeakBindTable(MachO); 1648 else { 1649 errs() << "This operation is only currently supported " 1650 "for Mach-O executable files.\n"; 1651 return; 1652 } 1653 } 1654 1655 /// Dump the raw contents of the __clangast section so the output can be piped 1656 /// into llvm-bcanalyzer. 1657 void llvm::printRawClangAST(const ObjectFile *Obj) { 1658 if (outs().is_displayed()) { 1659 errs() << "The -raw-clang-ast option will dump the raw binary contents of " 1660 "the clang ast section.\n" 1661 "Please redirect the output to a file or another program such as " 1662 "llvm-bcanalyzer.\n"; 1663 return; 1664 } 1665 1666 StringRef ClangASTSectionName("__clangast"); 1667 if (isa<COFFObjectFile>(Obj)) { 1668 ClangASTSectionName = "clangast"; 1669 } 1670 1671 Optional<object::SectionRef> ClangASTSection; 1672 for (auto Sec : ToolSectionFilter(*Obj)) { 1673 StringRef Name; 1674 Sec.getName(Name); 1675 if (Name == ClangASTSectionName) { 1676 ClangASTSection = Sec; 1677 break; 1678 } 1679 } 1680 if (!ClangASTSection) 1681 return; 1682 1683 StringRef ClangASTContents; 1684 error(ClangASTSection.getValue().getContents(ClangASTContents)); 1685 outs().write(ClangASTContents.data(), ClangASTContents.size()); 1686 } 1687 1688 static void printFaultMaps(const ObjectFile *Obj) { 1689 const char *FaultMapSectionName = nullptr; 1690 1691 if (isa<ELFObjectFileBase>(Obj)) { 1692 FaultMapSectionName = ".llvm_faultmaps"; 1693 } else if (isa<MachOObjectFile>(Obj)) { 1694 FaultMapSectionName = "__llvm_faultmaps"; 1695 } else { 1696 errs() << "This operation is only currently supported " 1697 "for ELF and Mach-O executable files.\n"; 1698 return; 1699 } 1700 1701 Optional<object::SectionRef> FaultMapSection; 1702 1703 for (auto Sec : ToolSectionFilter(*Obj)) { 1704 StringRef Name; 1705 Sec.getName(Name); 1706 if (Name == FaultMapSectionName) { 1707 FaultMapSection = Sec; 1708 break; 1709 } 1710 } 1711 1712 outs() << "FaultMap table:\n"; 1713 1714 if (!FaultMapSection.hasValue()) { 1715 outs() << "<not found>\n"; 1716 return; 1717 } 1718 1719 StringRef FaultMapContents; 1720 error(FaultMapSection.getValue().getContents(FaultMapContents)); 1721 1722 FaultMapParser FMP(FaultMapContents.bytes_begin(), 1723 FaultMapContents.bytes_end()); 1724 1725 outs() << FMP; 1726 } 1727 1728 static void printPrivateFileHeaders(const ObjectFile *o) { 1729 if (o->isELF()) 1730 printELFFileHeader(o); 1731 else if (o->isCOFF()) 1732 printCOFFFileHeader(o); 1733 else if (o->isMachO()) { 1734 printMachOFileHeader(o); 1735 printMachOLoadCommands(o); 1736 } else 1737 report_fatal_error("Invalid/Unsupported object file format"); 1738 } 1739 1740 static void printFirstPrivateFileHeader(const ObjectFile *o) { 1741 if (o->isELF()) 1742 printELFFileHeader(o); 1743 else if (o->isCOFF()) 1744 printCOFFFileHeader(o); 1745 else if (o->isMachO()) 1746 printMachOFileHeader(o); 1747 else 1748 report_fatal_error("Invalid/Unsupported object file format"); 1749 } 1750 1751 static void DumpObject(const ObjectFile *o, const Archive *a = nullptr) { 1752 StringRef ArchiveName = a != nullptr ? a->getFileName() : ""; 1753 // Avoid other output when using a raw option. 1754 if (!RawClangAST) { 1755 outs() << '\n'; 1756 if (a) 1757 outs() << a->getFileName() << "(" << o->getFileName() << ")"; 1758 else 1759 outs() << o->getFileName(); 1760 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n"; 1761 } 1762 1763 if (Disassemble) 1764 DisassembleObject(o, Relocations); 1765 if (Relocations && !Disassemble) 1766 PrintRelocations(o); 1767 if (SectionHeaders) 1768 PrintSectionHeaders(o); 1769 if (SectionContents) 1770 PrintSectionContents(o); 1771 if (SymbolTable) 1772 PrintSymbolTable(o, ArchiveName); 1773 if (UnwindInfo) 1774 PrintUnwindInfo(o); 1775 if (PrivateHeaders) 1776 printPrivateFileHeaders(o); 1777 if (FirstPrivateHeader) 1778 printFirstPrivateFileHeader(o); 1779 if (ExportsTrie) 1780 printExportsTrie(o); 1781 if (Rebase) 1782 printRebaseTable(o); 1783 if (Bind) 1784 printBindTable(o); 1785 if (LazyBind) 1786 printLazyBindTable(o); 1787 if (WeakBind) 1788 printWeakBindTable(o); 1789 if (RawClangAST) 1790 printRawClangAST(o); 1791 if (PrintFaultMaps) 1792 printFaultMaps(o); 1793 if (DwarfDumpType != DIDT_Null) { 1794 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o)); 1795 // Dump the complete DWARF structure. 1796 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */); 1797 } 1798 } 1799 1800 /// @brief Dump each object file in \a a; 1801 static void DumpArchive(const Archive *a) { 1802 Error Err; 1803 for (auto &C : a->children(Err)) { 1804 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 1805 if (!ChildOrErr) { 1806 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 1807 report_error(a->getFileName(), C, std::move(E)); 1808 continue; 1809 } 1810 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 1811 DumpObject(o, a); 1812 else 1813 report_error(a->getFileName(), object_error::invalid_file_type); 1814 } 1815 if (Err) 1816 report_error(a->getFileName(), std::move(Err)); 1817 } 1818 1819 /// @brief Open file and figure out how to dump it. 1820 static void DumpInput(StringRef file) { 1821 1822 // If we are using the Mach-O specific object file parser, then let it parse 1823 // the file and process the command line options. So the -arch flags can 1824 // be used to select specific slices, etc. 1825 if (MachOOpt) { 1826 ParseInputMachO(file); 1827 return; 1828 } 1829 1830 // Attempt to open the binary. 1831 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file); 1832 if (!BinaryOrErr) 1833 report_error(file, BinaryOrErr.takeError()); 1834 Binary &Binary = *BinaryOrErr.get().getBinary(); 1835 1836 if (Archive *a = dyn_cast<Archive>(&Binary)) 1837 DumpArchive(a); 1838 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary)) 1839 DumpObject(o); 1840 else 1841 report_error(file, object_error::invalid_file_type); 1842 } 1843 1844 int main(int argc, char **argv) { 1845 // Print a stack trace if we signal out. 1846 sys::PrintStackTraceOnErrorSignal(argv[0]); 1847 PrettyStackTraceProgram X(argc, argv); 1848 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 1849 1850 // Initialize targets and assembly printers/parsers. 1851 llvm::InitializeAllTargetInfos(); 1852 llvm::InitializeAllTargetMCs(); 1853 llvm::InitializeAllDisassemblers(); 1854 1855 // Register the target printer for --version. 1856 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 1857 1858 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 1859 TripleName = Triple::normalize(TripleName); 1860 1861 ToolName = argv[0]; 1862 1863 // Defaults to a.out if no filenames specified. 1864 if (InputFilenames.size() == 0) 1865 InputFilenames.push_back("a.out"); 1866 1867 if (DisassembleAll || PrintSource || PrintLines) 1868 Disassemble = true; 1869 if (!Disassemble 1870 && !Relocations 1871 && !SectionHeaders 1872 && !SectionContents 1873 && !SymbolTable 1874 && !UnwindInfo 1875 && !PrivateHeaders 1876 && !FirstPrivateHeader 1877 && !ExportsTrie 1878 && !Rebase 1879 && !Bind 1880 && !LazyBind 1881 && !WeakBind 1882 && !RawClangAST 1883 && !(UniversalHeaders && MachOOpt) 1884 && !(ArchiveHeaders && MachOOpt) 1885 && !(IndirectSymbols && MachOOpt) 1886 && !(DataInCode && MachOOpt) 1887 && !(LinkOptHints && MachOOpt) 1888 && !(InfoPlist && MachOOpt) 1889 && !(DylibsUsed && MachOOpt) 1890 && !(DylibId && MachOOpt) 1891 && !(ObjcMetaData && MachOOpt) 1892 && !(FilterSections.size() != 0 && MachOOpt) 1893 && !PrintFaultMaps 1894 && DwarfDumpType == DIDT_Null) { 1895 cl::PrintHelpMessage(); 1896 return 2; 1897 } 1898 1899 std::for_each(InputFilenames.begin(), InputFilenames.end(), 1900 DumpInput); 1901 1902 return EXIT_SUCCESS; 1903 } 1904