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 (!MI) { 498 printLead(Bytes, Address, OS); 499 OS << " <unknown>"; 500 return; 501 } 502 std::string Buffer; 503 { 504 raw_string_ostream TempStream(Buffer); 505 IP.printInst(MI, TempStream, "", STI); 506 } 507 StringRef Contents(Buffer); 508 // Split off bundle attributes 509 auto PacketBundle = Contents.rsplit('\n'); 510 // Split off first instruction from the rest 511 auto HeadTail = PacketBundle.first.split('\n'); 512 auto Preamble = " { "; 513 auto Separator = ""; 514 while(!HeadTail.first.empty()) { 515 OS << Separator; 516 Separator = "\n"; 517 printLead(Bytes, Address, OS); 518 OS << Preamble; 519 Preamble = " "; 520 StringRef Inst; 521 auto Duplex = HeadTail.first.split('\v'); 522 if(!Duplex.second.empty()){ 523 OS << Duplex.first; 524 OS << "; "; 525 Inst = Duplex.second; 526 } 527 else 528 Inst = HeadTail.first; 529 OS << Inst; 530 Bytes = Bytes.slice(4); 531 Address += 4; 532 HeadTail = HeadTail.second.split('\n'); 533 } 534 OS << " } " << PacketBundle.second; 535 } 536 }; 537 HexagonPrettyPrinter HexagonPrettyPrinterInst; 538 539 class AMDGCNPrettyPrinter : public PrettyPrinter { 540 public: 541 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 542 uint64_t Address, raw_ostream &OS, StringRef Annot, 543 MCSubtargetInfo const &STI, SourcePrinter *SP) override { 544 if (!MI) { 545 OS << " <unknown>"; 546 return; 547 } 548 549 SmallString<40> InstStr; 550 raw_svector_ostream IS(InstStr); 551 552 IP.printInst(MI, IS, "", STI); 553 554 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address); 555 typedef support::ulittle32_t U32; 556 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()), 557 Bytes.size() / sizeof(U32))) 558 // D should be explicitly casted to uint32_t here as it is passed 559 // by format to snprintf as vararg. 560 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D)); 561 562 if (!Annot.empty()) 563 OS << "// " << Annot; 564 } 565 }; 566 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst; 567 568 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) { 569 switch(Triple.getArch()) { 570 default: 571 return PrettyPrinterInst; 572 case Triple::hexagon: 573 return HexagonPrettyPrinterInst; 574 case Triple::amdgcn: 575 return AMDGCNPrettyPrinterInst; 576 } 577 } 578 } 579 580 template <class ELFT> 581 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj, 582 const RelocationRef &RelRef, 583 SmallVectorImpl<char> &Result) { 584 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 585 586 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym; 587 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr; 588 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela; 589 590 const ELFFile<ELFT> &EF = *Obj->getELFFile(); 591 592 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a); 593 if (std::error_code EC = SecOrErr.getError()) 594 return EC; 595 const Elf_Shdr *Sec = *SecOrErr; 596 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link); 597 if (std::error_code EC = SymTabOrErr.getError()) 598 return EC; 599 const Elf_Shdr *SymTab = *SymTabOrErr; 600 assert(SymTab->sh_type == ELF::SHT_SYMTAB || 601 SymTab->sh_type == ELF::SHT_DYNSYM); 602 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link); 603 if (std::error_code EC = StrTabSec.getError()) 604 return EC; 605 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec); 606 if (std::error_code EC = StrTabOrErr.getError()) 607 return EC; 608 StringRef StrTab = *StrTabOrErr; 609 uint8_t type = RelRef.getType(); 610 StringRef res; 611 int64_t addend = 0; 612 switch (Sec->sh_type) { 613 default: 614 return object_error::parse_failed; 615 case ELF::SHT_REL: { 616 // TODO: Read implicit addend from section data. 617 break; 618 } 619 case ELF::SHT_RELA: { 620 const Elf_Rela *ERela = Obj->getRela(Rel); 621 addend = ERela->r_addend; 622 break; 623 } 624 } 625 symbol_iterator SI = RelRef.getSymbol(); 626 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl()); 627 StringRef Target; 628 if (symb->getType() == ELF::STT_SECTION) { 629 Expected<section_iterator> SymSI = SI->getSection(); 630 if (!SymSI) 631 return errorToErrorCode(SymSI.takeError()); 632 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl()); 633 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec); 634 if (std::error_code EC = SecName.getError()) 635 return EC; 636 Target = *SecName; 637 } else { 638 Expected<StringRef> SymName = symb->getName(StrTab); 639 if (!SymName) 640 return errorToErrorCode(SymName.takeError()); 641 Target = *SymName; 642 } 643 switch (EF.getHeader()->e_machine) { 644 case ELF::EM_X86_64: 645 switch (type) { 646 case ELF::R_X86_64_PC8: 647 case ELF::R_X86_64_PC16: 648 case ELF::R_X86_64_PC32: { 649 std::string fmtbuf; 650 raw_string_ostream fmt(fmtbuf); 651 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P"; 652 fmt.flush(); 653 Result.append(fmtbuf.begin(), fmtbuf.end()); 654 } break; 655 case ELF::R_X86_64_8: 656 case ELF::R_X86_64_16: 657 case ELF::R_X86_64_32: 658 case ELF::R_X86_64_32S: 659 case ELF::R_X86_64_64: { 660 std::string fmtbuf; 661 raw_string_ostream fmt(fmtbuf); 662 fmt << Target << (addend < 0 ? "" : "+") << addend; 663 fmt.flush(); 664 Result.append(fmtbuf.begin(), fmtbuf.end()); 665 } break; 666 default: 667 res = "Unknown"; 668 } 669 break; 670 case ELF::EM_LANAI: 671 case ELF::EM_AARCH64: { 672 std::string fmtbuf; 673 raw_string_ostream fmt(fmtbuf); 674 fmt << Target; 675 if (addend != 0) 676 fmt << (addend < 0 ? "" : "+") << addend; 677 fmt.flush(); 678 Result.append(fmtbuf.begin(), fmtbuf.end()); 679 break; 680 } 681 case ELF::EM_386: 682 case ELF::EM_IAMCU: 683 case ELF::EM_ARM: 684 case ELF::EM_HEXAGON: 685 case ELF::EM_MIPS: 686 case ELF::EM_BPF: 687 res = Target; 688 break; 689 case ELF::EM_WEBASSEMBLY: 690 switch (type) { 691 case ELF::R_WEBASSEMBLY_DATA: { 692 std::string fmtbuf; 693 raw_string_ostream fmt(fmtbuf); 694 fmt << Target << (addend < 0 ? "" : "+") << addend; 695 fmt.flush(); 696 Result.append(fmtbuf.begin(), fmtbuf.end()); 697 break; 698 } 699 case ELF::R_WEBASSEMBLY_FUNCTION: 700 res = Target; 701 break; 702 default: 703 res = "Unknown"; 704 } 705 break; 706 default: 707 res = "Unknown"; 708 } 709 if (Result.empty()) 710 Result.append(res.begin(), res.end()); 711 return std::error_code(); 712 } 713 714 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj, 715 const RelocationRef &Rel, 716 SmallVectorImpl<char> &Result) { 717 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj)) 718 return getRelocationValueString(ELF32LE, Rel, Result); 719 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj)) 720 return getRelocationValueString(ELF64LE, Rel, Result); 721 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj)) 722 return getRelocationValueString(ELF32BE, Rel, Result); 723 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj); 724 return getRelocationValueString(ELF64BE, Rel, Result); 725 } 726 727 static std::error_code getRelocationValueString(const COFFObjectFile *Obj, 728 const RelocationRef &Rel, 729 SmallVectorImpl<char> &Result) { 730 symbol_iterator SymI = Rel.getSymbol(); 731 Expected<StringRef> SymNameOrErr = SymI->getName(); 732 if (!SymNameOrErr) 733 return errorToErrorCode(SymNameOrErr.takeError()); 734 StringRef SymName = *SymNameOrErr; 735 Result.append(SymName.begin(), SymName.end()); 736 return std::error_code(); 737 } 738 739 static void printRelocationTargetName(const MachOObjectFile *O, 740 const MachO::any_relocation_info &RE, 741 raw_string_ostream &fmt) { 742 bool IsScattered = O->isRelocationScattered(RE); 743 744 // Target of a scattered relocation is an address. In the interest of 745 // generating pretty output, scan through the symbol table looking for a 746 // symbol that aligns with that address. If we find one, print it. 747 // Otherwise, we just print the hex address of the target. 748 if (IsScattered) { 749 uint32_t Val = O->getPlainRelocationSymbolNum(RE); 750 751 for (const SymbolRef &Symbol : O->symbols()) { 752 std::error_code ec; 753 Expected<uint64_t> Addr = Symbol.getAddress(); 754 if (!Addr) { 755 std::string Buf; 756 raw_string_ostream OS(Buf); 757 logAllUnhandledErrors(Addr.takeError(), OS, ""); 758 OS.flush(); 759 report_fatal_error(Buf); 760 } 761 if (*Addr != Val) 762 continue; 763 Expected<StringRef> Name = Symbol.getName(); 764 if (!Name) { 765 std::string Buf; 766 raw_string_ostream OS(Buf); 767 logAllUnhandledErrors(Name.takeError(), OS, ""); 768 OS.flush(); 769 report_fatal_error(Buf); 770 } 771 fmt << *Name; 772 return; 773 } 774 775 // If we couldn't find a symbol that this relocation refers to, try 776 // to find a section beginning instead. 777 for (const SectionRef &Section : ToolSectionFilter(*O)) { 778 std::error_code ec; 779 780 StringRef Name; 781 uint64_t Addr = Section.getAddress(); 782 if (Addr != Val) 783 continue; 784 if ((ec = Section.getName(Name))) 785 report_fatal_error(ec.message()); 786 fmt << Name; 787 return; 788 } 789 790 fmt << format("0x%x", Val); 791 return; 792 } 793 794 StringRef S; 795 bool isExtern = O->getPlainRelocationExternal(RE); 796 uint64_t Val = O->getPlainRelocationSymbolNum(RE); 797 798 if (isExtern) { 799 symbol_iterator SI = O->symbol_begin(); 800 advance(SI, Val); 801 Expected<StringRef> SOrErr = SI->getName(); 802 error(errorToErrorCode(SOrErr.takeError())); 803 S = *SOrErr; 804 } else { 805 section_iterator SI = O->section_begin(); 806 // Adjust for the fact that sections are 1-indexed. 807 advance(SI, Val - 1); 808 SI->getName(S); 809 } 810 811 fmt << S; 812 } 813 814 static std::error_code getRelocationValueString(const MachOObjectFile *Obj, 815 const RelocationRef &RelRef, 816 SmallVectorImpl<char> &Result) { 817 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 818 MachO::any_relocation_info RE = Obj->getRelocation(Rel); 819 820 unsigned Arch = Obj->getArch(); 821 822 std::string fmtbuf; 823 raw_string_ostream fmt(fmtbuf); 824 unsigned Type = Obj->getAnyRelocationType(RE); 825 bool IsPCRel = Obj->getAnyRelocationPCRel(RE); 826 827 // Determine any addends that should be displayed with the relocation. 828 // These require decoding the relocation type, which is triple-specific. 829 830 // X86_64 has entirely custom relocation types. 831 if (Arch == Triple::x86_64) { 832 bool isPCRel = Obj->getAnyRelocationPCRel(RE); 833 834 switch (Type) { 835 case MachO::X86_64_RELOC_GOT_LOAD: 836 case MachO::X86_64_RELOC_GOT: { 837 printRelocationTargetName(Obj, RE, fmt); 838 fmt << "@GOT"; 839 if (isPCRel) 840 fmt << "PCREL"; 841 break; 842 } 843 case MachO::X86_64_RELOC_SUBTRACTOR: { 844 DataRefImpl RelNext = Rel; 845 Obj->moveRelocationNext(RelNext); 846 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 847 848 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type 849 // X86_64_RELOC_UNSIGNED. 850 // NOTE: Scattered relocations don't exist on x86_64. 851 unsigned RType = Obj->getAnyRelocationType(RENext); 852 if (RType != MachO::X86_64_RELOC_UNSIGNED) 853 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after " 854 "X86_64_RELOC_SUBTRACTOR."); 855 856 // The X86_64_RELOC_UNSIGNED contains the minuend symbol; 857 // X86_64_RELOC_SUBTRACTOR contains the subtrahend. 858 printRelocationTargetName(Obj, RENext, fmt); 859 fmt << "-"; 860 printRelocationTargetName(Obj, RE, fmt); 861 break; 862 } 863 case MachO::X86_64_RELOC_TLV: 864 printRelocationTargetName(Obj, RE, fmt); 865 fmt << "@TLV"; 866 if (isPCRel) 867 fmt << "P"; 868 break; 869 case MachO::X86_64_RELOC_SIGNED_1: 870 printRelocationTargetName(Obj, RE, fmt); 871 fmt << "-1"; 872 break; 873 case MachO::X86_64_RELOC_SIGNED_2: 874 printRelocationTargetName(Obj, RE, fmt); 875 fmt << "-2"; 876 break; 877 case MachO::X86_64_RELOC_SIGNED_4: 878 printRelocationTargetName(Obj, RE, fmt); 879 fmt << "-4"; 880 break; 881 default: 882 printRelocationTargetName(Obj, RE, fmt); 883 break; 884 } 885 // X86 and ARM share some relocation types in common. 886 } else if (Arch == Triple::x86 || Arch == Triple::arm || 887 Arch == Triple::ppc) { 888 // Generic relocation types... 889 switch (Type) { 890 case MachO::GENERIC_RELOC_PAIR: // prints no info 891 return std::error_code(); 892 case MachO::GENERIC_RELOC_SECTDIFF: { 893 DataRefImpl RelNext = Rel; 894 Obj->moveRelocationNext(RelNext); 895 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 896 897 // X86 sect diff's must be followed by a relocation of type 898 // GENERIC_RELOC_PAIR. 899 unsigned RType = Obj->getAnyRelocationType(RENext); 900 901 if (RType != MachO::GENERIC_RELOC_PAIR) 902 report_fatal_error("Expected GENERIC_RELOC_PAIR after " 903 "GENERIC_RELOC_SECTDIFF."); 904 905 printRelocationTargetName(Obj, RE, fmt); 906 fmt << "-"; 907 printRelocationTargetName(Obj, RENext, fmt); 908 break; 909 } 910 } 911 912 if (Arch == Triple::x86 || Arch == Triple::ppc) { 913 switch (Type) { 914 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: { 915 DataRefImpl RelNext = Rel; 916 Obj->moveRelocationNext(RelNext); 917 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 918 919 // X86 sect diff's must be followed by a relocation of type 920 // GENERIC_RELOC_PAIR. 921 unsigned RType = Obj->getAnyRelocationType(RENext); 922 if (RType != MachO::GENERIC_RELOC_PAIR) 923 report_fatal_error("Expected GENERIC_RELOC_PAIR after " 924 "GENERIC_RELOC_LOCAL_SECTDIFF."); 925 926 printRelocationTargetName(Obj, RE, fmt); 927 fmt << "-"; 928 printRelocationTargetName(Obj, RENext, fmt); 929 break; 930 } 931 case MachO::GENERIC_RELOC_TLV: { 932 printRelocationTargetName(Obj, RE, fmt); 933 fmt << "@TLV"; 934 if (IsPCRel) 935 fmt << "P"; 936 break; 937 } 938 default: 939 printRelocationTargetName(Obj, RE, fmt); 940 } 941 } else { // ARM-specific relocations 942 switch (Type) { 943 case MachO::ARM_RELOC_HALF: 944 case MachO::ARM_RELOC_HALF_SECTDIFF: { 945 // Half relocations steal a bit from the length field to encode 946 // whether this is an upper16 or a lower16 relocation. 947 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1; 948 949 if (isUpper) 950 fmt << ":upper16:("; 951 else 952 fmt << ":lower16:("; 953 printRelocationTargetName(Obj, RE, fmt); 954 955 DataRefImpl RelNext = Rel; 956 Obj->moveRelocationNext(RelNext); 957 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 958 959 // ARM half relocs must be followed by a relocation of type 960 // ARM_RELOC_PAIR. 961 unsigned RType = Obj->getAnyRelocationType(RENext); 962 if (RType != MachO::ARM_RELOC_PAIR) 963 report_fatal_error("Expected ARM_RELOC_PAIR after " 964 "ARM_RELOC_HALF"); 965 966 // NOTE: The half of the target virtual address is stashed in the 967 // address field of the secondary relocation, but we can't reverse 968 // engineer the constant offset from it without decoding the movw/movt 969 // instruction to find the other half in its immediate field. 970 971 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the 972 // symbol/section pointer of the follow-on relocation. 973 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) { 974 fmt << "-"; 975 printRelocationTargetName(Obj, RENext, fmt); 976 } 977 978 fmt << ")"; 979 break; 980 } 981 default: { printRelocationTargetName(Obj, RE, fmt); } 982 } 983 } 984 } else 985 printRelocationTargetName(Obj, RE, fmt); 986 987 fmt.flush(); 988 Result.append(fmtbuf.begin(), fmtbuf.end()); 989 return std::error_code(); 990 } 991 992 static std::error_code getRelocationValueString(const RelocationRef &Rel, 993 SmallVectorImpl<char> &Result) { 994 const ObjectFile *Obj = Rel.getObject(); 995 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj)) 996 return getRelocationValueString(ELF, Rel, Result); 997 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj)) 998 return getRelocationValueString(COFF, Rel, Result); 999 auto *MachO = cast<MachOObjectFile>(Obj); 1000 return getRelocationValueString(MachO, Rel, Result); 1001 } 1002 1003 /// @brief Indicates whether this relocation should hidden when listing 1004 /// relocations, usually because it is the trailing part of a multipart 1005 /// relocation that will be printed as part of the leading relocation. 1006 static bool getHidden(RelocationRef RelRef) { 1007 const ObjectFile *Obj = RelRef.getObject(); 1008 auto *MachO = dyn_cast<MachOObjectFile>(Obj); 1009 if (!MachO) 1010 return false; 1011 1012 unsigned Arch = MachO->getArch(); 1013 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 1014 uint64_t Type = MachO->getRelocationType(Rel); 1015 1016 // On arches that use the generic relocations, GENERIC_RELOC_PAIR 1017 // is always hidden. 1018 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) { 1019 if (Type == MachO::GENERIC_RELOC_PAIR) 1020 return true; 1021 } else if (Arch == Triple::x86_64) { 1022 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows 1023 // an X86_64_RELOC_SUBTRACTOR. 1024 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) { 1025 DataRefImpl RelPrev = Rel; 1026 RelPrev.d.a--; 1027 uint64_t PrevType = MachO->getRelocationType(RelPrev); 1028 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR) 1029 return true; 1030 } 1031 } 1032 1033 return false; 1034 } 1035 1036 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) { 1037 assert(Obj->isELF()); 1038 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj)) 1039 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1040 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj)) 1041 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1042 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj)) 1043 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1044 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj)) 1045 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1046 llvm_unreachable("Unsupported binary format"); 1047 } 1048 1049 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) { 1050 const Target *TheTarget = getTarget(Obj); 1051 1052 // Package up features to be passed to target/subtarget 1053 SubtargetFeatures Features = Obj->getFeatures(); 1054 if (MAttrs.size()) { 1055 for (unsigned i = 0; i != MAttrs.size(); ++i) 1056 Features.AddFeature(MAttrs[i]); 1057 } 1058 1059 std::unique_ptr<const MCRegisterInfo> MRI( 1060 TheTarget->createMCRegInfo(TripleName)); 1061 if (!MRI) 1062 report_fatal_error("error: no register info for target " + TripleName); 1063 1064 // Set up disassembler. 1065 std::unique_ptr<const MCAsmInfo> AsmInfo( 1066 TheTarget->createMCAsmInfo(*MRI, TripleName)); 1067 if (!AsmInfo) 1068 report_fatal_error("error: no assembly info for target " + TripleName); 1069 std::unique_ptr<const MCSubtargetInfo> STI( 1070 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString())); 1071 if (!STI) 1072 report_fatal_error("error: no subtarget info for target " + TripleName); 1073 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); 1074 if (!MII) 1075 report_fatal_error("error: no instruction info for target " + TripleName); 1076 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo); 1077 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get()); 1078 1079 std::unique_ptr<MCDisassembler> DisAsm( 1080 TheTarget->createMCDisassembler(*STI, Ctx)); 1081 if (!DisAsm) 1082 report_fatal_error("error: no disassembler for target " + TripleName); 1083 1084 std::unique_ptr<const MCInstrAnalysis> MIA( 1085 TheTarget->createMCInstrAnalysis(MII.get())); 1086 1087 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 1088 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 1089 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI)); 1090 if (!IP) 1091 report_fatal_error("error: no instruction printer for target " + 1092 TripleName); 1093 IP->setPrintImmHex(PrintImmHex); 1094 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName)); 1095 1096 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " : 1097 "\t\t\t%08" PRIx64 ": "; 1098 1099 SourcePrinter SP(Obj, TheTarget->getName()); 1100 1101 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections 1102 // in RelocSecs contain the relocations for section S. 1103 std::error_code EC; 1104 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap; 1105 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1106 section_iterator Sec2 = Section.getRelocatedSection(); 1107 if (Sec2 != Obj->section_end()) 1108 SectionRelocMap[*Sec2].push_back(Section); 1109 } 1110 1111 // Create a mapping from virtual address to symbol name. This is used to 1112 // pretty print the symbols while disassembling. 1113 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy; 1114 std::map<SectionRef, SectionSymbolsTy> AllSymbols; 1115 for (const SymbolRef &Symbol : Obj->symbols()) { 1116 Expected<uint64_t> AddressOrErr = Symbol.getAddress(); 1117 error(errorToErrorCode(AddressOrErr.takeError())); 1118 uint64_t Address = *AddressOrErr; 1119 1120 Expected<StringRef> Name = Symbol.getName(); 1121 error(errorToErrorCode(Name.takeError())); 1122 if (Name->empty()) 1123 continue; 1124 1125 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 1126 error(errorToErrorCode(SectionOrErr.takeError())); 1127 section_iterator SecI = *SectionOrErr; 1128 if (SecI == Obj->section_end()) 1129 continue; 1130 1131 // For AMDGPU we need to track symbol types 1132 uint8_t SymbolType = ELF::STT_NOTYPE; 1133 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1134 SymbolType = getElfSymbolType(Obj, Symbol); 1135 } 1136 1137 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType); 1138 1139 } 1140 1141 // Create a mapping from virtual address to section. 1142 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses; 1143 for (SectionRef Sec : Obj->sections()) 1144 SectionAddresses.emplace_back(Sec.getAddress(), Sec); 1145 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end()); 1146 1147 // Linked executables (.exe and .dll files) typically don't include a real 1148 // symbol table but they might contain an export table. 1149 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) { 1150 for (const auto &ExportEntry : COFFObj->export_directories()) { 1151 StringRef Name; 1152 error(ExportEntry.getSymbolName(Name)); 1153 if (Name.empty()) 1154 continue; 1155 uint32_t RVA; 1156 error(ExportEntry.getExportRVA(RVA)); 1157 1158 uint64_t VA = COFFObj->getImageBase() + RVA; 1159 auto Sec = std::upper_bound( 1160 SectionAddresses.begin(), SectionAddresses.end(), VA, 1161 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) { 1162 return LHS < RHS.first; 1163 }); 1164 if (Sec != SectionAddresses.begin()) 1165 --Sec; 1166 else 1167 Sec = SectionAddresses.end(); 1168 1169 if (Sec != SectionAddresses.end()) 1170 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE); 1171 } 1172 } 1173 1174 // Sort all the symbols, this allows us to use a simple binary search to find 1175 // a symbol near an address. 1176 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols) 1177 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end()); 1178 1179 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1180 if (!DisassembleAll && (!Section.isText() || Section.isVirtual())) 1181 continue; 1182 1183 uint64_t SectionAddr = Section.getAddress(); 1184 uint64_t SectSize = Section.getSize(); 1185 if (!SectSize) 1186 continue; 1187 1188 // Get the list of all the symbols in this section. 1189 SectionSymbolsTy &Symbols = AllSymbols[Section]; 1190 std::vector<uint64_t> DataMappingSymsAddr; 1191 std::vector<uint64_t> TextMappingSymsAddr; 1192 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) { 1193 for (const auto &Symb : Symbols) { 1194 uint64_t Address = std::get<0>(Symb); 1195 StringRef Name = std::get<1>(Symb); 1196 if (Name.startswith("$d")) 1197 DataMappingSymsAddr.push_back(Address - SectionAddr); 1198 if (Name.startswith("$x")) 1199 TextMappingSymsAddr.push_back(Address - SectionAddr); 1200 } 1201 } 1202 1203 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end()); 1204 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end()); 1205 1206 // Make a list of all the relocations for this section. 1207 std::vector<RelocationRef> Rels; 1208 if (InlineRelocs) { 1209 for (const SectionRef &RelocSec : SectionRelocMap[Section]) { 1210 for (const RelocationRef &Reloc : RelocSec.relocations()) { 1211 Rels.push_back(Reloc); 1212 } 1213 } 1214 } 1215 1216 // Sort relocations by address. 1217 std::sort(Rels.begin(), Rels.end(), RelocAddressLess); 1218 1219 StringRef SegmentName = ""; 1220 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) { 1221 DataRefImpl DR = Section.getRawDataRefImpl(); 1222 SegmentName = MachO->getSectionFinalSegmentName(DR); 1223 } 1224 StringRef name; 1225 error(Section.getName(name)); 1226 outs() << "Disassembly of section "; 1227 if (!SegmentName.empty()) 1228 outs() << SegmentName << ","; 1229 outs() << name << ':'; 1230 1231 // If the section has no symbol at the start, just insert a dummy one. 1232 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) { 1233 Symbols.insert(Symbols.begin(), std::make_tuple(SectionAddr, name, ELF::STT_NOTYPE)); 1234 } 1235 1236 SmallString<40> Comments; 1237 raw_svector_ostream CommentStream(Comments); 1238 1239 StringRef BytesStr; 1240 error(Section.getContents(BytesStr)); 1241 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()), 1242 BytesStr.size()); 1243 1244 uint64_t Size; 1245 uint64_t Index; 1246 1247 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin(); 1248 std::vector<RelocationRef>::const_iterator rel_end = Rels.end(); 1249 // Disassemble symbol by symbol. 1250 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) { 1251 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr; 1252 // The end is either the section end or the beginning of the next 1253 // symbol. 1254 uint64_t End = 1255 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr; 1256 // Don't try to disassemble beyond the end of section contents. 1257 if (End > SectSize) 1258 End = SectSize; 1259 // If this symbol has the same address as the next symbol, then skip it. 1260 if (Start >= End) 1261 continue; 1262 1263 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1264 // make size 4 bytes folded 1265 End = Start + ((End - Start) & ~0x3ull); 1266 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) { 1267 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes) 1268 Start += 256; 1269 } 1270 if (si == se - 1 || 1271 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) { 1272 // cut trailing zeroes at the end of kernel 1273 // cut up to 256 bytes 1274 const uint64_t EndAlign = 256; 1275 const auto Limit = End - (std::min)(EndAlign, End - Start); 1276 while (End > Limit && 1277 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0) 1278 End -= 4; 1279 } 1280 } 1281 1282 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n"; 1283 1284 #ifndef NDEBUG 1285 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); 1286 #else 1287 raw_ostream &DebugOut = nulls(); 1288 #endif 1289 1290 for (Index = Start; Index < End; Index += Size) { 1291 MCInst Inst; 1292 1293 // AArch64 ELF binaries can interleave data and text in the 1294 // same section. We rely on the markers introduced to 1295 // understand what we need to dump. 1296 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) { 1297 uint64_t Stride = 0; 1298 1299 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(), 1300 DataMappingSymsAddr.end(), Index); 1301 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) { 1302 // Switch to data. 1303 while (Index < End) { 1304 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 1305 outs() << "\t"; 1306 if (Index + 4 <= End) { 1307 Stride = 4; 1308 dumpBytes(Bytes.slice(Index, 4), outs()); 1309 outs() << "\t.word"; 1310 } else if (Index + 2 <= End) { 1311 Stride = 2; 1312 dumpBytes(Bytes.slice(Index, 2), outs()); 1313 outs() << "\t.short"; 1314 } else { 1315 Stride = 1; 1316 dumpBytes(Bytes.slice(Index, 1), outs()); 1317 outs() << "\t.byte"; 1318 } 1319 Index += Stride; 1320 outs() << "\n"; 1321 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(), 1322 TextMappingSymsAddr.end(), Index); 1323 if (TAI != TextMappingSymsAddr.end() && *TAI == Index) 1324 break; 1325 } 1326 } 1327 } 1328 1329 if (Index >= End) 1330 break; 1331 1332 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), 1333 SectionAddr + Index, DebugOut, 1334 CommentStream); 1335 if (Size == 0) 1336 Size = 1; 1337 1338 PIP.printInst(*IP, Disassembled ? &Inst : nullptr, 1339 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "", 1340 *STI, &SP); 1341 outs() << CommentStream.str(); 1342 Comments.clear(); 1343 1344 // Try to resolve the target of a call, tail call, etc. to a specific 1345 // symbol. 1346 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) || 1347 MIA->isConditionalBranch(Inst))) { 1348 uint64_t Target; 1349 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) { 1350 // In a relocatable object, the target's section must reside in 1351 // the same section as the call instruction or it is accessed 1352 // through a relocation. 1353 // 1354 // In a non-relocatable object, the target may be in any section. 1355 // 1356 // N.B. We don't walk the relocations in the relocatable case yet. 1357 auto *TargetSectionSymbols = &Symbols; 1358 if (!Obj->isRelocatableObject()) { 1359 auto SectionAddress = std::upper_bound( 1360 SectionAddresses.begin(), SectionAddresses.end(), Target, 1361 [](uint64_t LHS, 1362 const std::pair<uint64_t, SectionRef> &RHS) { 1363 return LHS < RHS.first; 1364 }); 1365 if (SectionAddress != SectionAddresses.begin()) { 1366 --SectionAddress; 1367 TargetSectionSymbols = &AllSymbols[SectionAddress->second]; 1368 } else { 1369 TargetSectionSymbols = nullptr; 1370 } 1371 } 1372 1373 // Find the first symbol in the section whose offset is less than 1374 // or equal to the target. 1375 if (TargetSectionSymbols) { 1376 auto TargetSym = std::upper_bound( 1377 TargetSectionSymbols->begin(), TargetSectionSymbols->end(), 1378 Target, [](uint64_t LHS, 1379 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) { 1380 return LHS < std::get<0>(RHS); 1381 }); 1382 if (TargetSym != TargetSectionSymbols->begin()) { 1383 --TargetSym; 1384 uint64_t TargetAddress = std::get<0>(*TargetSym); 1385 StringRef TargetName = std::get<1>(*TargetSym); 1386 outs() << " <" << TargetName; 1387 uint64_t Disp = Target - TargetAddress; 1388 if (Disp) 1389 outs() << "+0x" << utohexstr(Disp); 1390 outs() << '>'; 1391 } 1392 } 1393 } 1394 } 1395 outs() << "\n"; 1396 1397 // Print relocation for instruction. 1398 while (rel_cur != rel_end) { 1399 bool hidden = getHidden(*rel_cur); 1400 uint64_t addr = rel_cur->getOffset(); 1401 SmallString<16> name; 1402 SmallString<32> val; 1403 1404 // If this relocation is hidden, skip it. 1405 if (hidden) goto skip_print_rel; 1406 1407 // Stop when rel_cur's address is past the current instruction. 1408 if (addr >= Index + Size) break; 1409 rel_cur->getTypeName(name); 1410 error(getRelocationValueString(*rel_cur, val)); 1411 outs() << format(Fmt.data(), SectionAddr + addr) << name 1412 << "\t" << val << "\n"; 1413 1414 skip_print_rel: 1415 ++rel_cur; 1416 } 1417 } 1418 } 1419 } 1420 } 1421 1422 void llvm::PrintRelocations(const ObjectFile *Obj) { 1423 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : 1424 "%08" PRIx64; 1425 // Regular objdump doesn't print relocations in non-relocatable object 1426 // files. 1427 if (!Obj->isRelocatableObject()) 1428 return; 1429 1430 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1431 if (Section.relocation_begin() == Section.relocation_end()) 1432 continue; 1433 StringRef secname; 1434 error(Section.getName(secname)); 1435 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n"; 1436 for (const RelocationRef &Reloc : Section.relocations()) { 1437 bool hidden = getHidden(Reloc); 1438 uint64_t address = Reloc.getOffset(); 1439 SmallString<32> relocname; 1440 SmallString<32> valuestr; 1441 if (hidden) 1442 continue; 1443 Reloc.getTypeName(relocname); 1444 error(getRelocationValueString(Reloc, valuestr)); 1445 outs() << format(Fmt.data(), address) << " " << relocname << " " 1446 << valuestr << "\n"; 1447 } 1448 outs() << "\n"; 1449 } 1450 } 1451 1452 void llvm::PrintSectionHeaders(const ObjectFile *Obj) { 1453 outs() << "Sections:\n" 1454 "Idx Name Size Address Type\n"; 1455 unsigned i = 0; 1456 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1457 StringRef Name; 1458 error(Section.getName(Name)); 1459 uint64_t Address = Section.getAddress(); 1460 uint64_t Size = Section.getSize(); 1461 bool Text = Section.isText(); 1462 bool Data = Section.isData(); 1463 bool BSS = Section.isBSS(); 1464 std::string Type = (std::string(Text ? "TEXT " : "") + 1465 (Data ? "DATA " : "") + (BSS ? "BSS" : "")); 1466 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i, 1467 Name.str().c_str(), Size, Address, Type.c_str()); 1468 ++i; 1469 } 1470 } 1471 1472 void llvm::PrintSectionContents(const ObjectFile *Obj) { 1473 std::error_code EC; 1474 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1475 StringRef Name; 1476 StringRef Contents; 1477 error(Section.getName(Name)); 1478 uint64_t BaseAddr = Section.getAddress(); 1479 uint64_t Size = Section.getSize(); 1480 if (!Size) 1481 continue; 1482 1483 outs() << "Contents of section " << Name << ":\n"; 1484 if (Section.isBSS()) { 1485 outs() << format("<skipping contents of bss section at [%04" PRIx64 1486 ", %04" PRIx64 ")>\n", 1487 BaseAddr, BaseAddr + Size); 1488 continue; 1489 } 1490 1491 error(Section.getContents(Contents)); 1492 1493 // Dump out the content as hex and printable ascii characters. 1494 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) { 1495 outs() << format(" %04" PRIx64 " ", BaseAddr + addr); 1496 // Dump line of hex. 1497 for (std::size_t i = 0; i < 16; ++i) { 1498 if (i != 0 && i % 4 == 0) 1499 outs() << ' '; 1500 if (addr + i < end) 1501 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true) 1502 << hexdigit(Contents[addr + i] & 0xF, true); 1503 else 1504 outs() << " "; 1505 } 1506 // Print ascii. 1507 outs() << " "; 1508 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) { 1509 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF)) 1510 outs() << Contents[addr + i]; 1511 else 1512 outs() << "."; 1513 } 1514 outs() << "\n"; 1515 } 1516 } 1517 } 1518 1519 void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName, 1520 StringRef ArchitectureName) { 1521 outs() << "SYMBOL TABLE:\n"; 1522 1523 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) { 1524 printCOFFSymbolTable(coff); 1525 return; 1526 } 1527 for (const SymbolRef &Symbol : o->symbols()) { 1528 Expected<uint64_t> AddressOrError = Symbol.getAddress(); 1529 if (!AddressOrError) 1530 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError()); 1531 uint64_t Address = *AddressOrError; 1532 Expected<SymbolRef::Type> TypeOrError = Symbol.getType(); 1533 if (!TypeOrError) 1534 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError()); 1535 SymbolRef::Type Type = *TypeOrError; 1536 uint32_t Flags = Symbol.getFlags(); 1537 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 1538 error(errorToErrorCode(SectionOrErr.takeError())); 1539 section_iterator Section = *SectionOrErr; 1540 StringRef Name; 1541 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) { 1542 Section->getName(Name); 1543 } else { 1544 Expected<StringRef> NameOrErr = Symbol.getName(); 1545 if (!NameOrErr) 1546 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(), 1547 ArchitectureName); 1548 Name = *NameOrErr; 1549 } 1550 1551 bool Global = Flags & SymbolRef::SF_Global; 1552 bool Weak = Flags & SymbolRef::SF_Weak; 1553 bool Absolute = Flags & SymbolRef::SF_Absolute; 1554 bool Common = Flags & SymbolRef::SF_Common; 1555 bool Hidden = Flags & SymbolRef::SF_Hidden; 1556 1557 char GlobLoc = ' '; 1558 if (Type != SymbolRef::ST_Unknown) 1559 GlobLoc = Global ? 'g' : 'l'; 1560 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 1561 ? 'd' : ' '; 1562 char FileFunc = ' '; 1563 if (Type == SymbolRef::ST_File) 1564 FileFunc = 'f'; 1565 else if (Type == SymbolRef::ST_Function) 1566 FileFunc = 'F'; 1567 1568 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : 1569 "%08" PRIx64; 1570 1571 outs() << format(Fmt, Address) << " " 1572 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 1573 << (Weak ? 'w' : ' ') // Weak? 1574 << ' ' // Constructor. Not supported yet. 1575 << ' ' // Warning. Not supported yet. 1576 << ' ' // Indirect reference to another symbol. 1577 << Debug // Debugging (d) or dynamic (D) symbol. 1578 << FileFunc // Name of function (F), file (f) or object (O). 1579 << ' '; 1580 if (Absolute) { 1581 outs() << "*ABS*"; 1582 } else if (Common) { 1583 outs() << "*COM*"; 1584 } else if (Section == o->section_end()) { 1585 outs() << "*UND*"; 1586 } else { 1587 if (const MachOObjectFile *MachO = 1588 dyn_cast<const MachOObjectFile>(o)) { 1589 DataRefImpl DR = Section->getRawDataRefImpl(); 1590 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 1591 outs() << SegmentName << ","; 1592 } 1593 StringRef SectionName; 1594 error(Section->getName(SectionName)); 1595 outs() << SectionName; 1596 } 1597 1598 outs() << '\t'; 1599 if (Common || isa<ELFObjectFileBase>(o)) { 1600 uint64_t Val = 1601 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize(); 1602 outs() << format("\t %08" PRIx64 " ", Val); 1603 } 1604 1605 if (Hidden) { 1606 outs() << ".hidden "; 1607 } 1608 outs() << Name 1609 << '\n'; 1610 } 1611 } 1612 1613 static void PrintUnwindInfo(const ObjectFile *o) { 1614 outs() << "Unwind info:\n\n"; 1615 1616 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) { 1617 printCOFFUnwindInfo(coff); 1618 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1619 printMachOUnwindInfo(MachO); 1620 else { 1621 // TODO: Extract DWARF dump tool to objdump. 1622 errs() << "This operation is only currently supported " 1623 "for COFF and MachO object files.\n"; 1624 return; 1625 } 1626 } 1627 1628 void llvm::printExportsTrie(const ObjectFile *o) { 1629 outs() << "Exports trie:\n"; 1630 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1631 printMachOExportsTrie(MachO); 1632 else { 1633 errs() << "This operation is only currently supported " 1634 "for Mach-O executable files.\n"; 1635 return; 1636 } 1637 } 1638 1639 void llvm::printRebaseTable(const ObjectFile *o) { 1640 outs() << "Rebase table:\n"; 1641 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1642 printMachORebaseTable(MachO); 1643 else { 1644 errs() << "This operation is only currently supported " 1645 "for Mach-O executable files.\n"; 1646 return; 1647 } 1648 } 1649 1650 void llvm::printBindTable(const ObjectFile *o) { 1651 outs() << "Bind table:\n"; 1652 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1653 printMachOBindTable(MachO); 1654 else { 1655 errs() << "This operation is only currently supported " 1656 "for Mach-O executable files.\n"; 1657 return; 1658 } 1659 } 1660 1661 void llvm::printLazyBindTable(const ObjectFile *o) { 1662 outs() << "Lazy bind table:\n"; 1663 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1664 printMachOLazyBindTable(MachO); 1665 else { 1666 errs() << "This operation is only currently supported " 1667 "for Mach-O executable files.\n"; 1668 return; 1669 } 1670 } 1671 1672 void llvm::printWeakBindTable(const ObjectFile *o) { 1673 outs() << "Weak bind table:\n"; 1674 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1675 printMachOWeakBindTable(MachO); 1676 else { 1677 errs() << "This operation is only currently supported " 1678 "for Mach-O executable files.\n"; 1679 return; 1680 } 1681 } 1682 1683 /// Dump the raw contents of the __clangast section so the output can be piped 1684 /// into llvm-bcanalyzer. 1685 void llvm::printRawClangAST(const ObjectFile *Obj) { 1686 if (outs().is_displayed()) { 1687 errs() << "The -raw-clang-ast option will dump the raw binary contents of " 1688 "the clang ast section.\n" 1689 "Please redirect the output to a file or another program such as " 1690 "llvm-bcanalyzer.\n"; 1691 return; 1692 } 1693 1694 StringRef ClangASTSectionName("__clangast"); 1695 if (isa<COFFObjectFile>(Obj)) { 1696 ClangASTSectionName = "clangast"; 1697 } 1698 1699 Optional<object::SectionRef> ClangASTSection; 1700 for (auto Sec : ToolSectionFilter(*Obj)) { 1701 StringRef Name; 1702 Sec.getName(Name); 1703 if (Name == ClangASTSectionName) { 1704 ClangASTSection = Sec; 1705 break; 1706 } 1707 } 1708 if (!ClangASTSection) 1709 return; 1710 1711 StringRef ClangASTContents; 1712 error(ClangASTSection.getValue().getContents(ClangASTContents)); 1713 outs().write(ClangASTContents.data(), ClangASTContents.size()); 1714 } 1715 1716 static void printFaultMaps(const ObjectFile *Obj) { 1717 const char *FaultMapSectionName = nullptr; 1718 1719 if (isa<ELFObjectFileBase>(Obj)) { 1720 FaultMapSectionName = ".llvm_faultmaps"; 1721 } else if (isa<MachOObjectFile>(Obj)) { 1722 FaultMapSectionName = "__llvm_faultmaps"; 1723 } else { 1724 errs() << "This operation is only currently supported " 1725 "for ELF and Mach-O executable files.\n"; 1726 return; 1727 } 1728 1729 Optional<object::SectionRef> FaultMapSection; 1730 1731 for (auto Sec : ToolSectionFilter(*Obj)) { 1732 StringRef Name; 1733 Sec.getName(Name); 1734 if (Name == FaultMapSectionName) { 1735 FaultMapSection = Sec; 1736 break; 1737 } 1738 } 1739 1740 outs() << "FaultMap table:\n"; 1741 1742 if (!FaultMapSection.hasValue()) { 1743 outs() << "<not found>\n"; 1744 return; 1745 } 1746 1747 StringRef FaultMapContents; 1748 error(FaultMapSection.getValue().getContents(FaultMapContents)); 1749 1750 FaultMapParser FMP(FaultMapContents.bytes_begin(), 1751 FaultMapContents.bytes_end()); 1752 1753 outs() << FMP; 1754 } 1755 1756 static void printPrivateFileHeaders(const ObjectFile *o) { 1757 if (o->isELF()) 1758 printELFFileHeader(o); 1759 else if (o->isCOFF()) 1760 printCOFFFileHeader(o); 1761 else if (o->isMachO()) { 1762 printMachOFileHeader(o); 1763 printMachOLoadCommands(o); 1764 } else 1765 report_fatal_error("Invalid/Unsupported object file format"); 1766 } 1767 1768 static void printFirstPrivateFileHeader(const ObjectFile *o) { 1769 if (o->isELF()) 1770 printELFFileHeader(o); 1771 else if (o->isCOFF()) 1772 printCOFFFileHeader(o); 1773 else if (o->isMachO()) 1774 printMachOFileHeader(o); 1775 else 1776 report_fatal_error("Invalid/Unsupported object file format"); 1777 } 1778 1779 static void DumpObject(const ObjectFile *o, const Archive *a = nullptr) { 1780 StringRef ArchiveName = a != nullptr ? a->getFileName() : ""; 1781 // Avoid other output when using a raw option. 1782 if (!RawClangAST) { 1783 outs() << '\n'; 1784 if (a) 1785 outs() << a->getFileName() << "(" << o->getFileName() << ")"; 1786 else 1787 outs() << o->getFileName(); 1788 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n"; 1789 } 1790 1791 if (Disassemble) 1792 DisassembleObject(o, Relocations); 1793 if (Relocations && !Disassemble) 1794 PrintRelocations(o); 1795 if (SectionHeaders) 1796 PrintSectionHeaders(o); 1797 if (SectionContents) 1798 PrintSectionContents(o); 1799 if (SymbolTable) 1800 PrintSymbolTable(o, ArchiveName); 1801 if (UnwindInfo) 1802 PrintUnwindInfo(o); 1803 if (PrivateHeaders) 1804 printPrivateFileHeaders(o); 1805 if (FirstPrivateHeader) 1806 printFirstPrivateFileHeader(o); 1807 if (ExportsTrie) 1808 printExportsTrie(o); 1809 if (Rebase) 1810 printRebaseTable(o); 1811 if (Bind) 1812 printBindTable(o); 1813 if (LazyBind) 1814 printLazyBindTable(o); 1815 if (WeakBind) 1816 printWeakBindTable(o); 1817 if (RawClangAST) 1818 printRawClangAST(o); 1819 if (PrintFaultMaps) 1820 printFaultMaps(o); 1821 if (DwarfDumpType != DIDT_Null) { 1822 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o)); 1823 // Dump the complete DWARF structure. 1824 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */); 1825 } 1826 } 1827 1828 static void DumpObject(const COFFImportFile *I, const Archive *A) { 1829 StringRef ArchiveName = A ? A->getFileName() : ""; 1830 1831 // Avoid other output when using a raw option. 1832 if (!RawClangAST) 1833 outs() << '\n' 1834 << ArchiveName << "(" << I->getFileName() << ")" 1835 << ":\tfile format COFF-import-file" 1836 << "\n\n"; 1837 1838 if (SymbolTable) 1839 printCOFFSymbolTable(I); 1840 } 1841 1842 /// @brief Dump each object file in \a a; 1843 static void DumpArchive(const Archive *a) { 1844 Error Err; 1845 for (auto &C : a->children(Err)) { 1846 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 1847 if (!ChildOrErr) { 1848 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 1849 report_error(a->getFileName(), C, std::move(E)); 1850 continue; 1851 } 1852 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 1853 DumpObject(o, a); 1854 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get())) 1855 DumpObject(I, a); 1856 else 1857 report_error(a->getFileName(), object_error::invalid_file_type); 1858 } 1859 if (Err) 1860 report_error(a->getFileName(), std::move(Err)); 1861 } 1862 1863 /// @brief Open file and figure out how to dump it. 1864 static void DumpInput(StringRef file) { 1865 1866 // If we are using the Mach-O specific object file parser, then let it parse 1867 // the file and process the command line options. So the -arch flags can 1868 // be used to select specific slices, etc. 1869 if (MachOOpt) { 1870 ParseInputMachO(file); 1871 return; 1872 } 1873 1874 // Attempt to open the binary. 1875 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file); 1876 if (!BinaryOrErr) 1877 report_error(file, BinaryOrErr.takeError()); 1878 Binary &Binary = *BinaryOrErr.get().getBinary(); 1879 1880 if (Archive *a = dyn_cast<Archive>(&Binary)) 1881 DumpArchive(a); 1882 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary)) 1883 DumpObject(o); 1884 else 1885 report_error(file, object_error::invalid_file_type); 1886 } 1887 1888 int main(int argc, char **argv) { 1889 // Print a stack trace if we signal out. 1890 sys::PrintStackTraceOnErrorSignal(argv[0]); 1891 PrettyStackTraceProgram X(argc, argv); 1892 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 1893 1894 // Initialize targets and assembly printers/parsers. 1895 llvm::InitializeAllTargetInfos(); 1896 llvm::InitializeAllTargetMCs(); 1897 llvm::InitializeAllDisassemblers(); 1898 1899 // Register the target printer for --version. 1900 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 1901 1902 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 1903 TripleName = Triple::normalize(TripleName); 1904 1905 ToolName = argv[0]; 1906 1907 // Defaults to a.out if no filenames specified. 1908 if (InputFilenames.size() == 0) 1909 InputFilenames.push_back("a.out"); 1910 1911 if (DisassembleAll || PrintSource || PrintLines) 1912 Disassemble = true; 1913 if (!Disassemble 1914 && !Relocations 1915 && !SectionHeaders 1916 && !SectionContents 1917 && !SymbolTable 1918 && !UnwindInfo 1919 && !PrivateHeaders 1920 && !FirstPrivateHeader 1921 && !ExportsTrie 1922 && !Rebase 1923 && !Bind 1924 && !LazyBind 1925 && !WeakBind 1926 && !RawClangAST 1927 && !(UniversalHeaders && MachOOpt) 1928 && !(ArchiveHeaders && MachOOpt) 1929 && !(IndirectSymbols && MachOOpt) 1930 && !(DataInCode && MachOOpt) 1931 && !(LinkOptHints && MachOOpt) 1932 && !(InfoPlist && MachOOpt) 1933 && !(DylibsUsed && MachOOpt) 1934 && !(DylibId && MachOOpt) 1935 && !(ObjcMetaData && MachOOpt) 1936 && !(FilterSections.size() != 0 && MachOOpt) 1937 && !PrintFaultMaps 1938 && DwarfDumpType == DIDT_Null) { 1939 cl::PrintHelpMessage(); 1940 return 2; 1941 } 1942 1943 std::for_each(InputFilenames.begin(), InputFilenames.end(), 1944 DumpInput); 1945 1946 return EXIT_SUCCESS; 1947 } 1948