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