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 uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) { 1036 assert(Obj->isELF()); 1037 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj)) 1038 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1039 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj)) 1040 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1041 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj)) 1042 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1043 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj)) 1044 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1045 llvm_unreachable("Unsupported binary format"); 1046 } 1047 1048 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) { 1049 const Target *TheTarget = getTarget(Obj); 1050 1051 // Package up features to be passed to target/subtarget 1052 SubtargetFeatures Features = Obj->getFeatures(); 1053 if (MAttrs.size()) { 1054 for (unsigned i = 0; i != MAttrs.size(); ++i) 1055 Features.AddFeature(MAttrs[i]); 1056 } 1057 1058 std::unique_ptr<const MCRegisterInfo> MRI( 1059 TheTarget->createMCRegInfo(TripleName)); 1060 if (!MRI) 1061 report_fatal_error("error: no register info for target " + TripleName); 1062 1063 // Set up disassembler. 1064 std::unique_ptr<const MCAsmInfo> AsmInfo( 1065 TheTarget->createMCAsmInfo(*MRI, TripleName)); 1066 if (!AsmInfo) 1067 report_fatal_error("error: no assembly info for target " + TripleName); 1068 std::unique_ptr<const MCSubtargetInfo> STI( 1069 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString())); 1070 if (!STI) 1071 report_fatal_error("error: no subtarget info for target " + TripleName); 1072 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); 1073 if (!MII) 1074 report_fatal_error("error: no instruction info for target " + TripleName); 1075 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo); 1076 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get()); 1077 1078 std::unique_ptr<MCDisassembler> DisAsm( 1079 TheTarget->createMCDisassembler(*STI, Ctx)); 1080 if (!DisAsm) 1081 report_fatal_error("error: no disassembler for target " + TripleName); 1082 1083 std::unique_ptr<const MCInstrAnalysis> MIA( 1084 TheTarget->createMCInstrAnalysis(MII.get())); 1085 1086 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 1087 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 1088 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI)); 1089 if (!IP) 1090 report_fatal_error("error: no instruction printer for target " + 1091 TripleName); 1092 IP->setPrintImmHex(PrintImmHex); 1093 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName)); 1094 1095 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " : 1096 "\t\t\t%08" PRIx64 ": "; 1097 1098 SourcePrinter SP(Obj, TheTarget->getName()); 1099 1100 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections 1101 // in RelocSecs contain the relocations for section S. 1102 std::error_code EC; 1103 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap; 1104 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1105 section_iterator Sec2 = Section.getRelocatedSection(); 1106 if (Sec2 != Obj->section_end()) 1107 SectionRelocMap[*Sec2].push_back(Section); 1108 } 1109 1110 // Create a mapping from virtual address to symbol name. This is used to 1111 // pretty print the symbols while disassembling. 1112 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy; 1113 std::map<SectionRef, SectionSymbolsTy> AllSymbols; 1114 for (const SymbolRef &Symbol : Obj->symbols()) { 1115 Expected<uint64_t> AddressOrErr = Symbol.getAddress(); 1116 error(errorToErrorCode(AddressOrErr.takeError())); 1117 uint64_t Address = *AddressOrErr; 1118 1119 Expected<StringRef> Name = Symbol.getName(); 1120 error(errorToErrorCode(Name.takeError())); 1121 if (Name->empty()) 1122 continue; 1123 1124 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 1125 error(errorToErrorCode(SectionOrErr.takeError())); 1126 section_iterator SecI = *SectionOrErr; 1127 if (SecI == Obj->section_end()) 1128 continue; 1129 1130 // For AMDGPU we need to track symbol types 1131 uint8_t SymbolType = ELF::STT_NOTYPE; 1132 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1133 SymbolType = getElfSymbolType(Obj, Symbol); 1134 } 1135 1136 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType); 1137 1138 } 1139 1140 // Create a mapping from virtual address to section. 1141 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses; 1142 for (SectionRef Sec : Obj->sections()) 1143 SectionAddresses.emplace_back(Sec.getAddress(), Sec); 1144 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end()); 1145 1146 // Linked executables (.exe and .dll files) typically don't include a real 1147 // symbol table but they might contain an export table. 1148 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) { 1149 for (const auto &ExportEntry : COFFObj->export_directories()) { 1150 StringRef Name; 1151 error(ExportEntry.getSymbolName(Name)); 1152 if (Name.empty()) 1153 continue; 1154 uint32_t RVA; 1155 error(ExportEntry.getExportRVA(RVA)); 1156 1157 uint64_t VA = COFFObj->getImageBase() + RVA; 1158 auto Sec = std::upper_bound( 1159 SectionAddresses.begin(), SectionAddresses.end(), VA, 1160 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) { 1161 return LHS < RHS.first; 1162 }); 1163 if (Sec != SectionAddresses.begin()) 1164 --Sec; 1165 else 1166 Sec = SectionAddresses.end(); 1167 1168 if (Sec != SectionAddresses.end()) 1169 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE); 1170 } 1171 } 1172 1173 // Sort all the symbols, this allows us to use a simple binary search to find 1174 // a symbol near an address. 1175 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols) 1176 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end()); 1177 1178 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1179 if (!DisassembleAll && (!Section.isText() || Section.isVirtual())) 1180 continue; 1181 1182 uint64_t SectionAddr = Section.getAddress(); 1183 uint64_t SectSize = Section.getSize(); 1184 if (!SectSize) 1185 continue; 1186 1187 // Get the list of all the symbols in this section. 1188 SectionSymbolsTy &Symbols = AllSymbols[Section]; 1189 std::vector<uint64_t> DataMappingSymsAddr; 1190 std::vector<uint64_t> TextMappingSymsAddr; 1191 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) { 1192 for (const auto &Symb : Symbols) { 1193 uint64_t Address = std::get<0>(Symb); 1194 StringRef Name = std::get<1>(Symb); 1195 if (Name.startswith("$d")) 1196 DataMappingSymsAddr.push_back(Address - SectionAddr); 1197 if (Name.startswith("$x")) 1198 TextMappingSymsAddr.push_back(Address - SectionAddr); 1199 } 1200 } 1201 1202 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end()); 1203 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end()); 1204 1205 // Make a list of all the relocations for this section. 1206 std::vector<RelocationRef> Rels; 1207 if (InlineRelocs) { 1208 for (const SectionRef &RelocSec : SectionRelocMap[Section]) { 1209 for (const RelocationRef &Reloc : RelocSec.relocations()) { 1210 Rels.push_back(Reloc); 1211 } 1212 } 1213 } 1214 1215 // Sort relocations by address. 1216 std::sort(Rels.begin(), Rels.end(), RelocAddressLess); 1217 1218 StringRef SegmentName = ""; 1219 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) { 1220 DataRefImpl DR = Section.getRawDataRefImpl(); 1221 SegmentName = MachO->getSectionFinalSegmentName(DR); 1222 } 1223 StringRef name; 1224 error(Section.getName(name)); 1225 outs() << "Disassembly of section "; 1226 if (!SegmentName.empty()) 1227 outs() << SegmentName << ","; 1228 outs() << name << ':'; 1229 1230 // If the section has no symbol at the start, just insert a dummy one. 1231 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) { 1232 Symbols.insert(Symbols.begin(), std::make_tuple(SectionAddr, name, ELF::STT_NOTYPE)); 1233 } 1234 1235 SmallString<40> Comments; 1236 raw_svector_ostream CommentStream(Comments); 1237 1238 StringRef BytesStr; 1239 error(Section.getContents(BytesStr)); 1240 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()), 1241 BytesStr.size()); 1242 1243 uint64_t Size; 1244 uint64_t Index; 1245 1246 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin(); 1247 std::vector<RelocationRef>::const_iterator rel_end = Rels.end(); 1248 // Disassemble symbol by symbol. 1249 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) { 1250 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr; 1251 // The end is either the section end or the beginning of the next 1252 // symbol. 1253 uint64_t End = 1254 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr; 1255 // Don't try to disassemble beyond the end of section contents. 1256 if (End > SectSize) 1257 End = SectSize; 1258 // If this symbol has the same address as the next symbol, then skip it. 1259 if (Start >= End) 1260 continue; 1261 1262 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1263 // make size 4 bytes folded 1264 End = Start + ((End - Start) & ~0x3ull); 1265 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) { 1266 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes) 1267 Start += 256; 1268 } 1269 if (si == se - 1 || 1270 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) { 1271 // cut trailing zeroes at the end of kernel 1272 // cut up to 256 bytes 1273 const uint64_t EndAlign = 256; 1274 const auto Limit = End - (std::min)(EndAlign, End - Start); 1275 while (End > Limit && 1276 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0) 1277 End -= 4; 1278 } 1279 } 1280 1281 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n"; 1282 1283 #ifndef NDEBUG 1284 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); 1285 #else 1286 raw_ostream &DebugOut = nulls(); 1287 #endif 1288 1289 for (Index = Start; Index < End; Index += Size) { 1290 MCInst Inst; 1291 1292 // AArch64 ELF binaries can interleave data and text in the 1293 // same section. We rely on the markers introduced to 1294 // understand what we need to dump. 1295 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) { 1296 uint64_t Stride = 0; 1297 1298 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(), 1299 DataMappingSymsAddr.end(), Index); 1300 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) { 1301 // Switch to data. 1302 while (Index < End) { 1303 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 1304 outs() << "\t"; 1305 if (Index + 4 <= End) { 1306 Stride = 4; 1307 dumpBytes(Bytes.slice(Index, 4), outs()); 1308 outs() << "\t.word"; 1309 } else if (Index + 2 <= End) { 1310 Stride = 2; 1311 dumpBytes(Bytes.slice(Index, 2), outs()); 1312 outs() << "\t.short"; 1313 } else { 1314 Stride = 1; 1315 dumpBytes(Bytes.slice(Index, 1), outs()); 1316 outs() << "\t.byte"; 1317 } 1318 Index += Stride; 1319 outs() << "\n"; 1320 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(), 1321 TextMappingSymsAddr.end(), Index); 1322 if (TAI != TextMappingSymsAddr.end() && *TAI == Index) 1323 break; 1324 } 1325 } 1326 } 1327 1328 if (Index >= End) 1329 break; 1330 1331 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), 1332 SectionAddr + Index, DebugOut, 1333 CommentStream); 1334 if (Size == 0) 1335 Size = 1; 1336 1337 PIP.printInst(*IP, Disassembled ? &Inst : nullptr, 1338 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "", 1339 *STI, &SP); 1340 outs() << CommentStream.str(); 1341 Comments.clear(); 1342 1343 // Try to resolve the target of a call, tail call, etc. to a specific 1344 // symbol. 1345 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) || 1346 MIA->isConditionalBranch(Inst))) { 1347 uint64_t Target; 1348 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) { 1349 // In a relocatable object, the target's section must reside in 1350 // the same section as the call instruction or it is accessed 1351 // through a relocation. 1352 // 1353 // In a non-relocatable object, the target may be in any section. 1354 // 1355 // N.B. We don't walk the relocations in the relocatable case yet. 1356 auto *TargetSectionSymbols = &Symbols; 1357 if (!Obj->isRelocatableObject()) { 1358 auto SectionAddress = std::upper_bound( 1359 SectionAddresses.begin(), SectionAddresses.end(), Target, 1360 [](uint64_t LHS, 1361 const std::pair<uint64_t, SectionRef> &RHS) { 1362 return LHS < RHS.first; 1363 }); 1364 if (SectionAddress != SectionAddresses.begin()) { 1365 --SectionAddress; 1366 TargetSectionSymbols = &AllSymbols[SectionAddress->second]; 1367 } else { 1368 TargetSectionSymbols = nullptr; 1369 } 1370 } 1371 1372 // Find the first symbol in the section whose offset is less than 1373 // or equal to the target. 1374 if (TargetSectionSymbols) { 1375 auto TargetSym = std::upper_bound( 1376 TargetSectionSymbols->begin(), TargetSectionSymbols->end(), 1377 Target, [](uint64_t LHS, 1378 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) { 1379 return LHS < std::get<0>(RHS); 1380 }); 1381 if (TargetSym != TargetSectionSymbols->begin()) { 1382 --TargetSym; 1383 uint64_t TargetAddress = std::get<0>(*TargetSym); 1384 StringRef TargetName = std::get<1>(*TargetSym); 1385 outs() << " <" << TargetName; 1386 uint64_t Disp = Target - TargetAddress; 1387 if (Disp) 1388 outs() << "+0x" << utohexstr(Disp); 1389 outs() << '>'; 1390 } 1391 } 1392 } 1393 } 1394 outs() << "\n"; 1395 1396 // Print relocation for instruction. 1397 while (rel_cur != rel_end) { 1398 bool hidden = getHidden(*rel_cur); 1399 uint64_t addr = rel_cur->getOffset(); 1400 SmallString<16> name; 1401 SmallString<32> val; 1402 1403 // If this relocation is hidden, skip it. 1404 if (hidden) goto skip_print_rel; 1405 1406 // Stop when rel_cur's address is past the current instruction. 1407 if (addr >= Index + Size) break; 1408 rel_cur->getTypeName(name); 1409 error(getRelocationValueString(*rel_cur, val)); 1410 outs() << format(Fmt.data(), SectionAddr + addr) << name 1411 << "\t" << val << "\n"; 1412 1413 skip_print_rel: 1414 ++rel_cur; 1415 } 1416 } 1417 } 1418 } 1419 } 1420 1421 void llvm::PrintRelocations(const ObjectFile *Obj) { 1422 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : 1423 "%08" PRIx64; 1424 // Regular objdump doesn't print relocations in non-relocatable object 1425 // files. 1426 if (!Obj->isRelocatableObject()) 1427 return; 1428 1429 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1430 if (Section.relocation_begin() == Section.relocation_end()) 1431 continue; 1432 StringRef secname; 1433 error(Section.getName(secname)); 1434 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n"; 1435 for (const RelocationRef &Reloc : Section.relocations()) { 1436 bool hidden = getHidden(Reloc); 1437 uint64_t address = Reloc.getOffset(); 1438 SmallString<32> relocname; 1439 SmallString<32> valuestr; 1440 if (hidden) 1441 continue; 1442 Reloc.getTypeName(relocname); 1443 error(getRelocationValueString(Reloc, valuestr)); 1444 outs() << format(Fmt.data(), address) << " " << relocname << " " 1445 << valuestr << "\n"; 1446 } 1447 outs() << "\n"; 1448 } 1449 } 1450 1451 void llvm::PrintSectionHeaders(const ObjectFile *Obj) { 1452 outs() << "Sections:\n" 1453 "Idx Name Size Address Type\n"; 1454 unsigned i = 0; 1455 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1456 StringRef Name; 1457 error(Section.getName(Name)); 1458 uint64_t Address = Section.getAddress(); 1459 uint64_t Size = Section.getSize(); 1460 bool Text = Section.isText(); 1461 bool Data = Section.isData(); 1462 bool BSS = Section.isBSS(); 1463 std::string Type = (std::string(Text ? "TEXT " : "") + 1464 (Data ? "DATA " : "") + (BSS ? "BSS" : "")); 1465 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i, 1466 Name.str().c_str(), Size, Address, Type.c_str()); 1467 ++i; 1468 } 1469 } 1470 1471 void llvm::PrintSectionContents(const ObjectFile *Obj) { 1472 std::error_code EC; 1473 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1474 StringRef Name; 1475 StringRef Contents; 1476 error(Section.getName(Name)); 1477 uint64_t BaseAddr = Section.getAddress(); 1478 uint64_t Size = Section.getSize(); 1479 if (!Size) 1480 continue; 1481 1482 outs() << "Contents of section " << Name << ":\n"; 1483 if (Section.isBSS()) { 1484 outs() << format("<skipping contents of bss section at [%04" PRIx64 1485 ", %04" PRIx64 ")>\n", 1486 BaseAddr, BaseAddr + Size); 1487 continue; 1488 } 1489 1490 error(Section.getContents(Contents)); 1491 1492 // Dump out the content as hex and printable ascii characters. 1493 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) { 1494 outs() << format(" %04" PRIx64 " ", BaseAddr + addr); 1495 // Dump line of hex. 1496 for (std::size_t i = 0; i < 16; ++i) { 1497 if (i != 0 && i % 4 == 0) 1498 outs() << ' '; 1499 if (addr + i < end) 1500 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true) 1501 << hexdigit(Contents[addr + i] & 0xF, true); 1502 else 1503 outs() << " "; 1504 } 1505 // Print ascii. 1506 outs() << " "; 1507 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) { 1508 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF)) 1509 outs() << Contents[addr + i]; 1510 else 1511 outs() << "."; 1512 } 1513 outs() << "\n"; 1514 } 1515 } 1516 } 1517 1518 void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName, 1519 StringRef ArchitectureName) { 1520 outs() << "SYMBOL TABLE:\n"; 1521 1522 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) { 1523 printCOFFSymbolTable(coff); 1524 return; 1525 } 1526 for (const SymbolRef &Symbol : o->symbols()) { 1527 Expected<uint64_t> AddressOrError = Symbol.getAddress(); 1528 if (!AddressOrError) 1529 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError()); 1530 uint64_t Address = *AddressOrError; 1531 Expected<SymbolRef::Type> TypeOrError = Symbol.getType(); 1532 if (!TypeOrError) 1533 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError()); 1534 SymbolRef::Type Type = *TypeOrError; 1535 uint32_t Flags = Symbol.getFlags(); 1536 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 1537 error(errorToErrorCode(SectionOrErr.takeError())); 1538 section_iterator Section = *SectionOrErr; 1539 StringRef Name; 1540 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) { 1541 Section->getName(Name); 1542 } else { 1543 Expected<StringRef> NameOrErr = Symbol.getName(); 1544 if (!NameOrErr) 1545 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(), 1546 ArchitectureName); 1547 Name = *NameOrErr; 1548 } 1549 1550 bool Global = Flags & SymbolRef::SF_Global; 1551 bool Weak = Flags & SymbolRef::SF_Weak; 1552 bool Absolute = Flags & SymbolRef::SF_Absolute; 1553 bool Common = Flags & SymbolRef::SF_Common; 1554 bool Hidden = Flags & SymbolRef::SF_Hidden; 1555 1556 char GlobLoc = ' '; 1557 if (Type != SymbolRef::ST_Unknown) 1558 GlobLoc = Global ? 'g' : 'l'; 1559 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 1560 ? 'd' : ' '; 1561 char FileFunc = ' '; 1562 if (Type == SymbolRef::ST_File) 1563 FileFunc = 'f'; 1564 else if (Type == SymbolRef::ST_Function) 1565 FileFunc = 'F'; 1566 1567 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : 1568 "%08" PRIx64; 1569 1570 outs() << format(Fmt, Address) << " " 1571 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 1572 << (Weak ? 'w' : ' ') // Weak? 1573 << ' ' // Constructor. Not supported yet. 1574 << ' ' // Warning. Not supported yet. 1575 << ' ' // Indirect reference to another symbol. 1576 << Debug // Debugging (d) or dynamic (D) symbol. 1577 << FileFunc // Name of function (F), file (f) or object (O). 1578 << ' '; 1579 if (Absolute) { 1580 outs() << "*ABS*"; 1581 } else if (Common) { 1582 outs() << "*COM*"; 1583 } else if (Section == o->section_end()) { 1584 outs() << "*UND*"; 1585 } else { 1586 if (const MachOObjectFile *MachO = 1587 dyn_cast<const MachOObjectFile>(o)) { 1588 DataRefImpl DR = Section->getRawDataRefImpl(); 1589 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 1590 outs() << SegmentName << ","; 1591 } 1592 StringRef SectionName; 1593 error(Section->getName(SectionName)); 1594 outs() << SectionName; 1595 } 1596 1597 outs() << '\t'; 1598 if (Common || isa<ELFObjectFileBase>(o)) { 1599 uint64_t Val = 1600 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize(); 1601 outs() << format("\t %08" PRIx64 " ", Val); 1602 } 1603 1604 if (Hidden) { 1605 outs() << ".hidden "; 1606 } 1607 outs() << Name 1608 << '\n'; 1609 } 1610 } 1611 1612 static void PrintUnwindInfo(const ObjectFile *o) { 1613 outs() << "Unwind info:\n\n"; 1614 1615 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) { 1616 printCOFFUnwindInfo(coff); 1617 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1618 printMachOUnwindInfo(MachO); 1619 else { 1620 // TODO: Extract DWARF dump tool to objdump. 1621 errs() << "This operation is only currently supported " 1622 "for COFF and MachO object files.\n"; 1623 return; 1624 } 1625 } 1626 1627 void llvm::printExportsTrie(const ObjectFile *o) { 1628 outs() << "Exports trie:\n"; 1629 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1630 printMachOExportsTrie(MachO); 1631 else { 1632 errs() << "This operation is only currently supported " 1633 "for Mach-O executable files.\n"; 1634 return; 1635 } 1636 } 1637 1638 void llvm::printRebaseTable(const ObjectFile *o) { 1639 outs() << "Rebase table:\n"; 1640 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1641 printMachORebaseTable(MachO); 1642 else { 1643 errs() << "This operation is only currently supported " 1644 "for Mach-O executable files.\n"; 1645 return; 1646 } 1647 } 1648 1649 void llvm::printBindTable(const ObjectFile *o) { 1650 outs() << "Bind table:\n"; 1651 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1652 printMachOBindTable(MachO); 1653 else { 1654 errs() << "This operation is only currently supported " 1655 "for Mach-O executable files.\n"; 1656 return; 1657 } 1658 } 1659 1660 void llvm::printLazyBindTable(const ObjectFile *o) { 1661 outs() << "Lazy bind table:\n"; 1662 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1663 printMachOLazyBindTable(MachO); 1664 else { 1665 errs() << "This operation is only currently supported " 1666 "for Mach-O executable files.\n"; 1667 return; 1668 } 1669 } 1670 1671 void llvm::printWeakBindTable(const ObjectFile *o) { 1672 outs() << "Weak bind table:\n"; 1673 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1674 printMachOWeakBindTable(MachO); 1675 else { 1676 errs() << "This operation is only currently supported " 1677 "for Mach-O executable files.\n"; 1678 return; 1679 } 1680 } 1681 1682 /// Dump the raw contents of the __clangast section so the output can be piped 1683 /// into llvm-bcanalyzer. 1684 void llvm::printRawClangAST(const ObjectFile *Obj) { 1685 if (outs().is_displayed()) { 1686 errs() << "The -raw-clang-ast option will dump the raw binary contents of " 1687 "the clang ast section.\n" 1688 "Please redirect the output to a file or another program such as " 1689 "llvm-bcanalyzer.\n"; 1690 return; 1691 } 1692 1693 StringRef ClangASTSectionName("__clangast"); 1694 if (isa<COFFObjectFile>(Obj)) { 1695 ClangASTSectionName = "clangast"; 1696 } 1697 1698 Optional<object::SectionRef> ClangASTSection; 1699 for (auto Sec : ToolSectionFilter(*Obj)) { 1700 StringRef Name; 1701 Sec.getName(Name); 1702 if (Name == ClangASTSectionName) { 1703 ClangASTSection = Sec; 1704 break; 1705 } 1706 } 1707 if (!ClangASTSection) 1708 return; 1709 1710 StringRef ClangASTContents; 1711 error(ClangASTSection.getValue().getContents(ClangASTContents)); 1712 outs().write(ClangASTContents.data(), ClangASTContents.size()); 1713 } 1714 1715 static void printFaultMaps(const ObjectFile *Obj) { 1716 const char *FaultMapSectionName = nullptr; 1717 1718 if (isa<ELFObjectFileBase>(Obj)) { 1719 FaultMapSectionName = ".llvm_faultmaps"; 1720 } else if (isa<MachOObjectFile>(Obj)) { 1721 FaultMapSectionName = "__llvm_faultmaps"; 1722 } else { 1723 errs() << "This operation is only currently supported " 1724 "for ELF and Mach-O executable files.\n"; 1725 return; 1726 } 1727 1728 Optional<object::SectionRef> FaultMapSection; 1729 1730 for (auto Sec : ToolSectionFilter(*Obj)) { 1731 StringRef Name; 1732 Sec.getName(Name); 1733 if (Name == FaultMapSectionName) { 1734 FaultMapSection = Sec; 1735 break; 1736 } 1737 } 1738 1739 outs() << "FaultMap table:\n"; 1740 1741 if (!FaultMapSection.hasValue()) { 1742 outs() << "<not found>\n"; 1743 return; 1744 } 1745 1746 StringRef FaultMapContents; 1747 error(FaultMapSection.getValue().getContents(FaultMapContents)); 1748 1749 FaultMapParser FMP(FaultMapContents.bytes_begin(), 1750 FaultMapContents.bytes_end()); 1751 1752 outs() << FMP; 1753 } 1754 1755 static void printPrivateFileHeaders(const ObjectFile *o) { 1756 if (o->isELF()) 1757 printELFFileHeader(o); 1758 else if (o->isCOFF()) 1759 printCOFFFileHeader(o); 1760 else if (o->isMachO()) { 1761 printMachOFileHeader(o); 1762 printMachOLoadCommands(o); 1763 } else 1764 report_fatal_error("Invalid/Unsupported object file format"); 1765 } 1766 1767 static void printFirstPrivateFileHeader(const ObjectFile *o) { 1768 if (o->isELF()) 1769 printELFFileHeader(o); 1770 else if (o->isCOFF()) 1771 printCOFFFileHeader(o); 1772 else if (o->isMachO()) 1773 printMachOFileHeader(o); 1774 else 1775 report_fatal_error("Invalid/Unsupported object file format"); 1776 } 1777 1778 static void DumpObject(const ObjectFile *o, const Archive *a = nullptr) { 1779 StringRef ArchiveName = a != nullptr ? a->getFileName() : ""; 1780 // Avoid other output when using a raw option. 1781 if (!RawClangAST) { 1782 outs() << '\n'; 1783 if (a) 1784 outs() << a->getFileName() << "(" << o->getFileName() << ")"; 1785 else 1786 outs() << o->getFileName(); 1787 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n"; 1788 } 1789 1790 if (Disassemble) 1791 DisassembleObject(o, Relocations); 1792 if (Relocations && !Disassemble) 1793 PrintRelocations(o); 1794 if (SectionHeaders) 1795 PrintSectionHeaders(o); 1796 if (SectionContents) 1797 PrintSectionContents(o); 1798 if (SymbolTable) 1799 PrintSymbolTable(o, ArchiveName); 1800 if (UnwindInfo) 1801 PrintUnwindInfo(o); 1802 if (PrivateHeaders) 1803 printPrivateFileHeaders(o); 1804 if (FirstPrivateHeader) 1805 printFirstPrivateFileHeader(o); 1806 if (ExportsTrie) 1807 printExportsTrie(o); 1808 if (Rebase) 1809 printRebaseTable(o); 1810 if (Bind) 1811 printBindTable(o); 1812 if (LazyBind) 1813 printLazyBindTable(o); 1814 if (WeakBind) 1815 printWeakBindTable(o); 1816 if (RawClangAST) 1817 printRawClangAST(o); 1818 if (PrintFaultMaps) 1819 printFaultMaps(o); 1820 if (DwarfDumpType != DIDT_Null) { 1821 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o)); 1822 // Dump the complete DWARF structure. 1823 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */); 1824 } 1825 } 1826 1827 /// @brief Dump each object file in \a a; 1828 static void DumpArchive(const Archive *a) { 1829 Error Err; 1830 for (auto &C : a->children(Err)) { 1831 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 1832 if (!ChildOrErr) { 1833 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 1834 report_error(a->getFileName(), C, std::move(E)); 1835 continue; 1836 } 1837 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 1838 DumpObject(o, a); 1839 else 1840 report_error(a->getFileName(), object_error::invalid_file_type); 1841 } 1842 if (Err) 1843 report_error(a->getFileName(), std::move(Err)); 1844 } 1845 1846 /// @brief Open file and figure out how to dump it. 1847 static void DumpInput(StringRef file) { 1848 1849 // If we are using the Mach-O specific object file parser, then let it parse 1850 // the file and process the command line options. So the -arch flags can 1851 // be used to select specific slices, etc. 1852 if (MachOOpt) { 1853 ParseInputMachO(file); 1854 return; 1855 } 1856 1857 // Attempt to open the binary. 1858 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file); 1859 if (!BinaryOrErr) 1860 report_error(file, BinaryOrErr.takeError()); 1861 Binary &Binary = *BinaryOrErr.get().getBinary(); 1862 1863 if (Archive *a = dyn_cast<Archive>(&Binary)) 1864 DumpArchive(a); 1865 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary)) 1866 DumpObject(o); 1867 else 1868 report_error(file, object_error::invalid_file_type); 1869 } 1870 1871 int main(int argc, char **argv) { 1872 // Print a stack trace if we signal out. 1873 sys::PrintStackTraceOnErrorSignal(argv[0]); 1874 PrettyStackTraceProgram X(argc, argv); 1875 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 1876 1877 // Initialize targets and assembly printers/parsers. 1878 llvm::InitializeAllTargetInfos(); 1879 llvm::InitializeAllTargetMCs(); 1880 llvm::InitializeAllDisassemblers(); 1881 1882 // Register the target printer for --version. 1883 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 1884 1885 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 1886 TripleName = Triple::normalize(TripleName); 1887 1888 ToolName = argv[0]; 1889 1890 // Defaults to a.out if no filenames specified. 1891 if (InputFilenames.size() == 0) 1892 InputFilenames.push_back("a.out"); 1893 1894 if (DisassembleAll || PrintSource || PrintLines) 1895 Disassemble = true; 1896 if (!Disassemble 1897 && !Relocations 1898 && !SectionHeaders 1899 && !SectionContents 1900 && !SymbolTable 1901 && !UnwindInfo 1902 && !PrivateHeaders 1903 && !FirstPrivateHeader 1904 && !ExportsTrie 1905 && !Rebase 1906 && !Bind 1907 && !LazyBind 1908 && !WeakBind 1909 && !RawClangAST 1910 && !(UniversalHeaders && MachOOpt) 1911 && !(ArchiveHeaders && MachOOpt) 1912 && !(IndirectSymbols && MachOOpt) 1913 && !(DataInCode && MachOOpt) 1914 && !(LinkOptHints && MachOOpt) 1915 && !(InfoPlist && MachOOpt) 1916 && !(DylibsUsed && MachOOpt) 1917 && !(DylibId && MachOOpt) 1918 && !(ObjcMetaData && MachOOpt) 1919 && !(FilterSections.size() != 0 && MachOOpt) 1920 && !PrintFaultMaps 1921 && DwarfDumpType == DIDT_Null) { 1922 cl::PrintHelpMessage(); 1923 return 2; 1924 } 1925 1926 std::for_each(InputFilenames.begin(), InputFilenames.end(), 1927 DumpInput); 1928 1929 return EXIT_SUCCESS; 1930 } 1931