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/StringSet.h" 24 #include "llvm/ADT/Triple.h" 25 #include "llvm/CodeGen/FaultMaps.h" 26 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 27 #include "llvm/DebugInfo/Symbolize/Symbolize.h" 28 #include "llvm/Demangle/Demangle.h" 29 #include "llvm/MC/MCAsmInfo.h" 30 #include "llvm/MC/MCContext.h" 31 #include "llvm/MC/MCDisassembler/MCDisassembler.h" 32 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h" 33 #include "llvm/MC/MCInst.h" 34 #include "llvm/MC/MCInstPrinter.h" 35 #include "llvm/MC/MCInstrAnalysis.h" 36 #include "llvm/MC/MCInstrInfo.h" 37 #include "llvm/MC/MCObjectFileInfo.h" 38 #include "llvm/MC/MCRegisterInfo.h" 39 #include "llvm/MC/MCSubtargetInfo.h" 40 #include "llvm/Object/Archive.h" 41 #include "llvm/Object/COFF.h" 42 #include "llvm/Object/COFFImportFile.h" 43 #include "llvm/Object/ELFObjectFile.h" 44 #include "llvm/Object/MachO.h" 45 #include "llvm/Object/MachOUniversal.h" 46 #include "llvm/Object/ObjectFile.h" 47 #include "llvm/Object/Wasm.h" 48 #include "llvm/Support/Casting.h" 49 #include "llvm/Support/CommandLine.h" 50 #include "llvm/Support/Debug.h" 51 #include "llvm/Support/Errc.h" 52 #include "llvm/Support/FileSystem.h" 53 #include "llvm/Support/Format.h" 54 #include "llvm/Support/GraphWriter.h" 55 #include "llvm/Support/Host.h" 56 #include "llvm/Support/InitLLVM.h" 57 #include "llvm/Support/MemoryBuffer.h" 58 #include "llvm/Support/SourceMgr.h" 59 #include "llvm/Support/StringSaver.h" 60 #include "llvm/Support/TargetRegistry.h" 61 #include "llvm/Support/TargetSelect.h" 62 #include "llvm/Support/raw_ostream.h" 63 #include <algorithm> 64 #include <cctype> 65 #include <cstring> 66 #include <system_error> 67 #include <unordered_map> 68 #include <utility> 69 70 using namespace llvm; 71 using namespace object; 72 73 cl::opt<bool> 74 llvm::AllHeaders("all-headers", 75 cl::desc("Display all available header information")); 76 static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"), 77 cl::aliasopt(AllHeaders)); 78 79 static cl::list<std::string> 80 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore); 81 82 cl::opt<bool> 83 llvm::Disassemble("disassemble", 84 cl::desc("Display assembler mnemonics for the machine instructions")); 85 static cl::alias 86 Disassembled("d", cl::desc("Alias for --disassemble"), 87 cl::aliasopt(Disassemble)); 88 89 cl::opt<bool> 90 llvm::DisassembleAll("disassemble-all", 91 cl::desc("Display assembler mnemonics for the machine instructions")); 92 static cl::alias 93 DisassembleAlld("D", cl::desc("Alias for --disassemble-all"), 94 cl::aliasopt(DisassembleAll)); 95 96 cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"), 97 cl::init(false)); 98 99 static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"), 100 cl::aliasopt(llvm::Demangle)); 101 102 static cl::list<std::string> 103 DisassembleFunctions("df", 104 cl::CommaSeparated, 105 cl::desc("List of functions to disassemble")); 106 static StringSet<> DisasmFuncsSet; 107 108 cl::opt<bool> 109 llvm::Relocations("r", cl::desc("Display the relocation entries in the file")); 110 111 cl::opt<bool> 112 llvm::DynamicRelocations("dynamic-reloc", 113 cl::desc("Display the dynamic relocation entries in the file")); 114 static cl::alias 115 DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"), 116 cl::aliasopt(DynamicRelocations)); 117 118 cl::opt<bool> 119 llvm::SectionContents("s", cl::desc("Display the content of each section")); 120 121 cl::opt<bool> 122 llvm::SymbolTable("t", cl::desc("Display the symbol table")); 123 124 cl::opt<bool> 125 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols")); 126 127 cl::opt<bool> 128 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info")); 129 130 cl::opt<bool> 131 llvm::Bind("bind", cl::desc("Display mach-o binding info")); 132 133 cl::opt<bool> 134 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info")); 135 136 cl::opt<bool> 137 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info")); 138 139 cl::opt<bool> 140 llvm::RawClangAST("raw-clang-ast", 141 cl::desc("Dump the raw binary contents of the clang AST section")); 142 143 static cl::opt<bool> 144 MachOOpt("macho", cl::desc("Use MachO specific object file parser")); 145 static cl::alias 146 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt)); 147 148 cl::opt<std::string> 149 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, " 150 "see -version for available targets")); 151 152 cl::opt<std::string> 153 llvm::MCPU("mcpu", 154 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 155 cl::value_desc("cpu-name"), 156 cl::init("")); 157 158 cl::opt<std::string> 159 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, " 160 "see -version for available targets")); 161 162 cl::opt<bool> 163 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the " 164 "headers for each section.")); 165 static cl::alias 166 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"), 167 cl::aliasopt(SectionHeaders)); 168 static cl::alias 169 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"), 170 cl::aliasopt(SectionHeaders)); 171 172 cl::list<std::string> 173 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. " 174 "With -macho dump segment,section")); 175 cl::alias 176 static FilterSectionsj("j", cl::desc("Alias for --section"), 177 cl::aliasopt(llvm::FilterSections)); 178 179 cl::list<std::string> 180 llvm::MAttrs("mattr", 181 cl::CommaSeparated, 182 cl::desc("Target specific attributes"), 183 cl::value_desc("a1,+a2,-a3,...")); 184 185 cl::opt<bool> 186 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling " 187 "instructions, do not print " 188 "the instruction bytes.")); 189 cl::opt<bool> 190 llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address")); 191 192 cl::opt<bool> 193 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information")); 194 195 static cl::alias 196 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"), 197 cl::aliasopt(UnwindInfo)); 198 199 cl::opt<bool> 200 llvm::PrivateHeaders("private-headers", 201 cl::desc("Display format specific file headers")); 202 203 cl::opt<bool> 204 llvm::FirstPrivateHeader("private-header", 205 cl::desc("Display only the first format specific file " 206 "header")); 207 208 static cl::alias 209 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"), 210 cl::aliasopt(PrivateHeaders)); 211 212 cl::opt<bool> llvm::FileHeaders( 213 "file-headers", 214 cl::desc("Display the contents of the overall file header")); 215 216 static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"), 217 cl::aliasopt(FileHeaders)); 218 219 cl::opt<bool> 220 llvm::ArchiveHeaders("archive-headers", 221 cl::desc("Display archive header information")); 222 223 cl::alias 224 ArchiveHeadersShort("a", cl::desc("Alias for --archive-headers"), 225 cl::aliasopt(ArchiveHeaders)); 226 227 cl::opt<bool> 228 llvm::PrintImmHex("print-imm-hex", 229 cl::desc("Use hex format for immediate values")); 230 231 cl::opt<bool> PrintFaultMaps("fault-map-section", 232 cl::desc("Display contents of faultmap section")); 233 234 cl::opt<DIDumpType> llvm::DwarfDumpType( 235 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"), 236 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame"))); 237 238 cl::opt<bool> PrintSource( 239 "source", 240 cl::desc( 241 "Display source inlined with disassembly. Implies disassemble object")); 242 243 cl::alias PrintSourceShort("S", cl::desc("Alias for -source"), 244 cl::aliasopt(PrintSource)); 245 246 cl::opt<bool> PrintLines("line-numbers", 247 cl::desc("Display source line numbers with " 248 "disassembly. Implies disassemble object")); 249 250 cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"), 251 cl::aliasopt(PrintLines)); 252 253 cl::opt<unsigned long long> 254 StartAddress("start-address", cl::desc("Disassemble beginning at address"), 255 cl::value_desc("address"), cl::init(0)); 256 cl::opt<unsigned long long> 257 StopAddress("stop-address", cl::desc("Stop disassembly at address"), 258 cl::value_desc("address"), cl::init(UINT64_MAX)); 259 static StringRef ToolName; 260 261 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy; 262 263 namespace { 264 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate; 265 266 class SectionFilterIterator { 267 public: 268 SectionFilterIterator(FilterPredicate P, 269 llvm::object::section_iterator const &I, 270 llvm::object::section_iterator const &E) 271 : Predicate(std::move(P)), Iterator(I), End(E) { 272 ScanPredicate(); 273 } 274 const llvm::object::SectionRef &operator*() const { return *Iterator; } 275 SectionFilterIterator &operator++() { 276 ++Iterator; 277 ScanPredicate(); 278 return *this; 279 } 280 bool operator!=(SectionFilterIterator const &Other) const { 281 return Iterator != Other.Iterator; 282 } 283 284 private: 285 void ScanPredicate() { 286 while (Iterator != End && !Predicate(*Iterator)) { 287 ++Iterator; 288 } 289 } 290 FilterPredicate Predicate; 291 llvm::object::section_iterator Iterator; 292 llvm::object::section_iterator End; 293 }; 294 295 class SectionFilter { 296 public: 297 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O) 298 : Predicate(std::move(P)), Object(O) {} 299 SectionFilterIterator begin() { 300 return SectionFilterIterator(Predicate, Object.section_begin(), 301 Object.section_end()); 302 } 303 SectionFilterIterator end() { 304 return SectionFilterIterator(Predicate, Object.section_end(), 305 Object.section_end()); 306 } 307 308 private: 309 FilterPredicate Predicate; 310 llvm::object::ObjectFile const &Object; 311 }; 312 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) { 313 return SectionFilter( 314 [](llvm::object::SectionRef const &S) { 315 if (FilterSections.empty()) 316 return true; 317 llvm::StringRef String; 318 std::error_code error = S.getName(String); 319 if (error) 320 return false; 321 return is_contained(FilterSections, String); 322 }, 323 O); 324 } 325 } 326 327 void llvm::error(std::error_code EC) { 328 if (!EC) 329 return; 330 331 errs() << ToolName << ": error reading file: " << EC.message() << ".\n"; 332 errs().flush(); 333 exit(1); 334 } 335 336 LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) { 337 errs() << ToolName << ": " << Message << ".\n"; 338 errs().flush(); 339 exit(1); 340 } 341 342 void llvm::warn(StringRef Message) { 343 errs() << ToolName << ": warning: " << Message << ".\n"; 344 errs().flush(); 345 } 346 347 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File, 348 Twine Message) { 349 errs() << ToolName << ": '" << File << "': " << Message << ".\n"; 350 exit(1); 351 } 352 353 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File, 354 std::error_code EC) { 355 assert(EC); 356 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n"; 357 exit(1); 358 } 359 360 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File, 361 llvm::Error E) { 362 assert(E); 363 std::string Buf; 364 raw_string_ostream OS(Buf); 365 logAllUnhandledErrors(std::move(E), OS, ""); 366 OS.flush(); 367 errs() << ToolName << ": '" << File << "': " << Buf; 368 exit(1); 369 } 370 371 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName, 372 StringRef FileName, 373 llvm::Error E, 374 StringRef ArchitectureName) { 375 assert(E); 376 errs() << ToolName << ": "; 377 if (ArchiveName != "") 378 errs() << ArchiveName << "(" << FileName << ")"; 379 else 380 errs() << "'" << FileName << "'"; 381 if (!ArchitectureName.empty()) 382 errs() << " (for architecture " << ArchitectureName << ")"; 383 std::string Buf; 384 raw_string_ostream OS(Buf); 385 logAllUnhandledErrors(std::move(E), OS, ""); 386 OS.flush(); 387 errs() << ": " << Buf; 388 exit(1); 389 } 390 391 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName, 392 const object::Archive::Child &C, 393 llvm::Error E, 394 StringRef ArchitectureName) { 395 Expected<StringRef> NameOrErr = C.getName(); 396 // TODO: if we have a error getting the name then it would be nice to print 397 // the index of which archive member this is and or its offset in the 398 // archive instead of "???" as the name. 399 if (!NameOrErr) { 400 consumeError(NameOrErr.takeError()); 401 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName); 402 } else 403 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E), 404 ArchitectureName); 405 } 406 407 static const Target *getTarget(const ObjectFile *Obj = nullptr) { 408 // Figure out the target triple. 409 llvm::Triple TheTriple("unknown-unknown-unknown"); 410 if (TripleName.empty()) { 411 if (Obj) { 412 TheTriple = Obj->makeTriple(); 413 } 414 } else { 415 TheTriple.setTriple(Triple::normalize(TripleName)); 416 417 // Use the triple, but also try to combine with ARM build attributes. 418 if (Obj) { 419 auto Arch = Obj->getArch(); 420 if (Arch == Triple::arm || Arch == Triple::armeb) { 421 Obj->setARMSubArch(TheTriple); 422 } 423 } 424 } 425 426 // Get the target specific parser. 427 std::string Error; 428 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, 429 Error); 430 if (!TheTarget) { 431 if (Obj) 432 report_error(Obj->getFileName(), "can't find target: " + Error); 433 else 434 error("can't find target: " + Error); 435 } 436 437 // Update the triple name and return the found target. 438 TripleName = TheTriple.getTriple(); 439 return TheTarget; 440 } 441 442 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) { 443 return a.getOffset() < b.getOffset(); 444 } 445 446 template <class ELFT> 447 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj, 448 const RelocationRef &RelRef, 449 SmallVectorImpl<char> &Result) { 450 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 451 452 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym; 453 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr; 454 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela; 455 456 const ELFFile<ELFT> &EF = *Obj->getELFFile(); 457 458 auto SecOrErr = EF.getSection(Rel.d.a); 459 if (!SecOrErr) 460 return errorToErrorCode(SecOrErr.takeError()); 461 const Elf_Shdr *Sec = *SecOrErr; 462 auto SymTabOrErr = EF.getSection(Sec->sh_link); 463 if (!SymTabOrErr) 464 return errorToErrorCode(SymTabOrErr.takeError()); 465 const Elf_Shdr *SymTab = *SymTabOrErr; 466 assert(SymTab->sh_type == ELF::SHT_SYMTAB || 467 SymTab->sh_type == ELF::SHT_DYNSYM); 468 auto StrTabSec = EF.getSection(SymTab->sh_link); 469 if (!StrTabSec) 470 return errorToErrorCode(StrTabSec.takeError()); 471 auto StrTabOrErr = EF.getStringTable(*StrTabSec); 472 if (!StrTabOrErr) 473 return errorToErrorCode(StrTabOrErr.takeError()); 474 StringRef StrTab = *StrTabOrErr; 475 int64_t addend = 0; 476 // If there is no Symbol associated with the relocation, we set the undef 477 // boolean value to 'true'. This will prevent us from calling functions that 478 // requires the relocation to be associated with a symbol. 479 bool undef = false; 480 switch (Sec->sh_type) { 481 default: 482 return object_error::parse_failed; 483 case ELF::SHT_REL: { 484 // TODO: Read implicit addend from section data. 485 break; 486 } 487 case ELF::SHT_RELA: { 488 const Elf_Rela *ERela = Obj->getRela(Rel); 489 addend = ERela->r_addend; 490 undef = ERela->getSymbol(false) == 0; 491 break; 492 } 493 } 494 StringRef Target; 495 if (!undef) { 496 symbol_iterator SI = RelRef.getSymbol(); 497 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl()); 498 if (symb->getType() == ELF::STT_SECTION) { 499 Expected<section_iterator> SymSI = SI->getSection(); 500 if (!SymSI) 501 return errorToErrorCode(SymSI.takeError()); 502 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl()); 503 auto SecName = EF.getSectionName(SymSec); 504 if (!SecName) 505 return errorToErrorCode(SecName.takeError()); 506 Target = *SecName; 507 } else { 508 Expected<StringRef> SymName = symb->getName(StrTab); 509 if (!SymName) 510 return errorToErrorCode(SymName.takeError()); 511 Target = *SymName; 512 } 513 } else 514 Target = "*ABS*"; 515 516 // Default scheme is to print Target, as well as "+ <addend>" for nonzero 517 // addend. Should be acceptable for all normal purposes. 518 std::string fmtbuf; 519 raw_string_ostream fmt(fmtbuf); 520 fmt << Target; 521 if (addend != 0) 522 fmt << (addend < 0 ? "" : "+") << addend; 523 fmt.flush(); 524 Result.append(fmtbuf.begin(), fmtbuf.end()); 525 return std::error_code(); 526 } 527 528 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj, 529 const RelocationRef &Rel, 530 SmallVectorImpl<char> &Result) { 531 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj)) 532 return getRelocationValueString(ELF32LE, Rel, Result); 533 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj)) 534 return getRelocationValueString(ELF64LE, Rel, Result); 535 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj)) 536 return getRelocationValueString(ELF32BE, Rel, Result); 537 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj); 538 return getRelocationValueString(ELF64BE, Rel, Result); 539 } 540 541 static std::error_code getRelocationValueString(const COFFObjectFile *Obj, 542 const RelocationRef &Rel, 543 SmallVectorImpl<char> &Result) { 544 symbol_iterator SymI = Rel.getSymbol(); 545 Expected<StringRef> SymNameOrErr = SymI->getName(); 546 if (!SymNameOrErr) 547 return errorToErrorCode(SymNameOrErr.takeError()); 548 StringRef SymName = *SymNameOrErr; 549 Result.append(SymName.begin(), SymName.end()); 550 return std::error_code(); 551 } 552 553 static void printRelocationTargetName(const MachOObjectFile *O, 554 const MachO::any_relocation_info &RE, 555 raw_string_ostream &fmt) { 556 bool IsScattered = O->isRelocationScattered(RE); 557 558 // Target of a scattered relocation is an address. In the interest of 559 // generating pretty output, scan through the symbol table looking for a 560 // symbol that aligns with that address. If we find one, print it. 561 // Otherwise, we just print the hex address of the target. 562 if (IsScattered) { 563 uint32_t Val = O->getPlainRelocationSymbolNum(RE); 564 565 for (const SymbolRef &Symbol : O->symbols()) { 566 std::error_code ec; 567 Expected<uint64_t> Addr = Symbol.getAddress(); 568 if (!Addr) 569 report_error(O->getFileName(), Addr.takeError()); 570 if (*Addr != Val) 571 continue; 572 Expected<StringRef> Name = Symbol.getName(); 573 if (!Name) 574 report_error(O->getFileName(), Name.takeError()); 575 fmt << *Name; 576 return; 577 } 578 579 // If we couldn't find a symbol that this relocation refers to, try 580 // to find a section beginning instead. 581 for (const SectionRef &Section : ToolSectionFilter(*O)) { 582 std::error_code ec; 583 584 StringRef Name; 585 uint64_t Addr = Section.getAddress(); 586 if (Addr != Val) 587 continue; 588 if ((ec = Section.getName(Name))) 589 report_error(O->getFileName(), ec); 590 fmt << Name; 591 return; 592 } 593 594 fmt << format("0x%x", Val); 595 return; 596 } 597 598 StringRef S; 599 bool isExtern = O->getPlainRelocationExternal(RE); 600 uint64_t Val = O->getPlainRelocationSymbolNum(RE); 601 602 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) { 603 fmt << format("0x%0" PRIx64, Val); 604 return; 605 } else if (isExtern) { 606 symbol_iterator SI = O->symbol_begin(); 607 advance(SI, Val); 608 Expected<StringRef> SOrErr = SI->getName(); 609 if (!SOrErr) 610 report_error(O->getFileName(), SOrErr.takeError()); 611 S = *SOrErr; 612 } else { 613 section_iterator SI = O->section_begin(); 614 // Adjust for the fact that sections are 1-indexed. 615 if (Val == 0) { 616 fmt << "0 (?,?)"; 617 return; 618 } 619 uint32_t i = Val - 1; 620 while (i != 0 && SI != O->section_end()) { 621 i--; 622 advance(SI, 1); 623 } 624 if (SI == O->section_end()) 625 fmt << Val << " (?,?)"; 626 else 627 SI->getName(S); 628 } 629 630 fmt << S; 631 } 632 633 static std::error_code getRelocationValueString(const WasmObjectFile *Obj, 634 const RelocationRef &RelRef, 635 SmallVectorImpl<char> &Result) { 636 const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef); 637 symbol_iterator SI = RelRef.getSymbol(); 638 std::string fmtbuf; 639 raw_string_ostream fmt(fmtbuf); 640 if (SI == Obj->symbol_end()) { 641 // Not all wasm relocations have symbols associated with them. 642 // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB. 643 fmt << Rel.Index; 644 } else { 645 Expected<StringRef> SymNameOrErr = SI->getName(); 646 if (!SymNameOrErr) 647 return errorToErrorCode(SymNameOrErr.takeError()); 648 StringRef SymName = *SymNameOrErr; 649 Result.append(SymName.begin(), SymName.end()); 650 } 651 fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend; 652 fmt.flush(); 653 Result.append(fmtbuf.begin(), fmtbuf.end()); 654 return std::error_code(); 655 } 656 657 static std::error_code getRelocationValueString(const MachOObjectFile *Obj, 658 const RelocationRef &RelRef, 659 SmallVectorImpl<char> &Result) { 660 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 661 MachO::any_relocation_info RE = Obj->getRelocation(Rel); 662 663 unsigned Arch = Obj->getArch(); 664 665 std::string fmtbuf; 666 raw_string_ostream fmt(fmtbuf); 667 unsigned Type = Obj->getAnyRelocationType(RE); 668 bool IsPCRel = Obj->getAnyRelocationPCRel(RE); 669 670 // Determine any addends that should be displayed with the relocation. 671 // These require decoding the relocation type, which is triple-specific. 672 673 // X86_64 has entirely custom relocation types. 674 if (Arch == Triple::x86_64) { 675 bool isPCRel = Obj->getAnyRelocationPCRel(RE); 676 677 switch (Type) { 678 case MachO::X86_64_RELOC_GOT_LOAD: 679 case MachO::X86_64_RELOC_GOT: { 680 printRelocationTargetName(Obj, RE, fmt); 681 fmt << "@GOT"; 682 if (isPCRel) 683 fmt << "PCREL"; 684 break; 685 } 686 case MachO::X86_64_RELOC_SUBTRACTOR: { 687 DataRefImpl RelNext = Rel; 688 Obj->moveRelocationNext(RelNext); 689 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 690 691 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type 692 // X86_64_RELOC_UNSIGNED. 693 // NOTE: Scattered relocations don't exist on x86_64. 694 unsigned RType = Obj->getAnyRelocationType(RENext); 695 if (RType != MachO::X86_64_RELOC_UNSIGNED) 696 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after " 697 "X86_64_RELOC_SUBTRACTOR."); 698 699 // The X86_64_RELOC_UNSIGNED contains the minuend symbol; 700 // X86_64_RELOC_SUBTRACTOR contains the subtrahend. 701 printRelocationTargetName(Obj, RENext, fmt); 702 fmt << "-"; 703 printRelocationTargetName(Obj, RE, fmt); 704 break; 705 } 706 case MachO::X86_64_RELOC_TLV: 707 printRelocationTargetName(Obj, RE, fmt); 708 fmt << "@TLV"; 709 if (isPCRel) 710 fmt << "P"; 711 break; 712 case MachO::X86_64_RELOC_SIGNED_1: 713 printRelocationTargetName(Obj, RE, fmt); 714 fmt << "-1"; 715 break; 716 case MachO::X86_64_RELOC_SIGNED_2: 717 printRelocationTargetName(Obj, RE, fmt); 718 fmt << "-2"; 719 break; 720 case MachO::X86_64_RELOC_SIGNED_4: 721 printRelocationTargetName(Obj, RE, fmt); 722 fmt << "-4"; 723 break; 724 default: 725 printRelocationTargetName(Obj, RE, fmt); 726 break; 727 } 728 // X86 and ARM share some relocation types in common. 729 } else if (Arch == Triple::x86 || Arch == Triple::arm || 730 Arch == Triple::ppc) { 731 // Generic relocation types... 732 switch (Type) { 733 case MachO::GENERIC_RELOC_PAIR: // prints no info 734 return std::error_code(); 735 case MachO::GENERIC_RELOC_SECTDIFF: { 736 DataRefImpl RelNext = Rel; 737 Obj->moveRelocationNext(RelNext); 738 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 739 740 // X86 sect diff's must be followed by a relocation of type 741 // GENERIC_RELOC_PAIR. 742 unsigned RType = Obj->getAnyRelocationType(RENext); 743 744 if (RType != MachO::GENERIC_RELOC_PAIR) 745 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after " 746 "GENERIC_RELOC_SECTDIFF."); 747 748 printRelocationTargetName(Obj, RE, fmt); 749 fmt << "-"; 750 printRelocationTargetName(Obj, RENext, fmt); 751 break; 752 } 753 } 754 755 if (Arch == Triple::x86 || Arch == Triple::ppc) { 756 switch (Type) { 757 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: { 758 DataRefImpl RelNext = Rel; 759 Obj->moveRelocationNext(RelNext); 760 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 761 762 // X86 sect diff's must be followed by a relocation of type 763 // GENERIC_RELOC_PAIR. 764 unsigned RType = Obj->getAnyRelocationType(RENext); 765 if (RType != MachO::GENERIC_RELOC_PAIR) 766 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after " 767 "GENERIC_RELOC_LOCAL_SECTDIFF."); 768 769 printRelocationTargetName(Obj, RE, fmt); 770 fmt << "-"; 771 printRelocationTargetName(Obj, RENext, fmt); 772 break; 773 } 774 case MachO::GENERIC_RELOC_TLV: { 775 printRelocationTargetName(Obj, RE, fmt); 776 fmt << "@TLV"; 777 if (IsPCRel) 778 fmt << "P"; 779 break; 780 } 781 default: 782 printRelocationTargetName(Obj, RE, fmt); 783 } 784 } else { // ARM-specific relocations 785 switch (Type) { 786 case MachO::ARM_RELOC_HALF: 787 case MachO::ARM_RELOC_HALF_SECTDIFF: { 788 // Half relocations steal a bit from the length field to encode 789 // whether this is an upper16 or a lower16 relocation. 790 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1; 791 792 if (isUpper) 793 fmt << ":upper16:("; 794 else 795 fmt << ":lower16:("; 796 printRelocationTargetName(Obj, RE, fmt); 797 798 DataRefImpl RelNext = Rel; 799 Obj->moveRelocationNext(RelNext); 800 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 801 802 // ARM half relocs must be followed by a relocation of type 803 // ARM_RELOC_PAIR. 804 unsigned RType = Obj->getAnyRelocationType(RENext); 805 if (RType != MachO::ARM_RELOC_PAIR) 806 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after " 807 "ARM_RELOC_HALF"); 808 809 // NOTE: The half of the target virtual address is stashed in the 810 // address field of the secondary relocation, but we can't reverse 811 // engineer the constant offset from it without decoding the movw/movt 812 // instruction to find the other half in its immediate field. 813 814 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the 815 // symbol/section pointer of the follow-on relocation. 816 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) { 817 fmt << "-"; 818 printRelocationTargetName(Obj, RENext, fmt); 819 } 820 821 fmt << ")"; 822 break; 823 } 824 default: { printRelocationTargetName(Obj, RE, fmt); } 825 } 826 } 827 } else 828 printRelocationTargetName(Obj, RE, fmt); 829 830 fmt.flush(); 831 Result.append(fmtbuf.begin(), fmtbuf.end()); 832 return std::error_code(); 833 } 834 835 static std::error_code getRelocationValueString(const RelocationRef &Rel, 836 SmallVectorImpl<char> &Result) { 837 const ObjectFile *Obj = Rel.getObject(); 838 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj)) 839 return getRelocationValueString(ELF, Rel, Result); 840 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj)) 841 return getRelocationValueString(COFF, Rel, Result); 842 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj)) 843 return getRelocationValueString(Wasm, Rel, Result); 844 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj)) 845 return getRelocationValueString(MachO, Rel, Result); 846 llvm_unreachable("unknown object file format"); 847 } 848 849 /// Indicates whether this relocation should hidden when listing 850 /// relocations, usually because it is the trailing part of a multipart 851 /// relocation that will be printed as part of the leading relocation. 852 static bool getHidden(RelocationRef RelRef) { 853 const ObjectFile *Obj = RelRef.getObject(); 854 auto *MachO = dyn_cast<MachOObjectFile>(Obj); 855 if (!MachO) 856 return false; 857 858 unsigned Arch = MachO->getArch(); 859 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 860 uint64_t Type = MachO->getRelocationType(Rel); 861 862 // On arches that use the generic relocations, GENERIC_RELOC_PAIR 863 // is always hidden. 864 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) { 865 if (Type == MachO::GENERIC_RELOC_PAIR) 866 return true; 867 } else if (Arch == Triple::x86_64) { 868 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows 869 // an X86_64_RELOC_SUBTRACTOR. 870 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) { 871 DataRefImpl RelPrev = Rel; 872 RelPrev.d.a--; 873 uint64_t PrevType = MachO->getRelocationType(RelPrev); 874 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR) 875 return true; 876 } 877 } 878 879 return false; 880 } 881 882 namespace { 883 class SourcePrinter { 884 protected: 885 DILineInfo OldLineInfo; 886 const ObjectFile *Obj = nullptr; 887 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer; 888 // File name to file contents of source 889 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache; 890 // Mark the line endings of the cached source 891 std::unordered_map<std::string, std::vector<StringRef>> LineCache; 892 893 private: 894 bool cacheSource(const DILineInfo& LineInfoFile); 895 896 public: 897 SourcePrinter() = default; 898 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) { 899 symbolize::LLVMSymbolizer::Options SymbolizerOpts( 900 DILineInfoSpecifier::FunctionNameKind::None, true, false, false, 901 DefaultArch); 902 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts)); 903 } 904 virtual ~SourcePrinter() = default; 905 virtual void printSourceLine(raw_ostream &OS, uint64_t Address, 906 StringRef Delimiter = "; "); 907 }; 908 909 bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) { 910 std::unique_ptr<MemoryBuffer> Buffer; 911 if (LineInfo.Source) { 912 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source); 913 } else { 914 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName); 915 if (!BufferOrError) 916 return false; 917 Buffer = std::move(*BufferOrError); 918 } 919 // Chomp the file to get lines 920 size_t BufferSize = Buffer->getBufferSize(); 921 const char *BufferStart = Buffer->getBufferStart(); 922 for (const char *Start = BufferStart, *End = BufferStart; 923 End < BufferStart + BufferSize; End++) 924 if (*End == '\n' || End == BufferStart + BufferSize - 1 || 925 (*End == '\r' && *(End + 1) == '\n')) { 926 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start)); 927 if (*End == '\r') 928 End++; 929 Start = End + 1; 930 } 931 SourceCache[LineInfo.FileName] = std::move(Buffer); 932 return true; 933 } 934 935 void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address, 936 StringRef Delimiter) { 937 if (!Symbolizer) 938 return; 939 DILineInfo LineInfo = DILineInfo(); 940 auto ExpectecLineInfo = 941 Symbolizer->symbolizeCode(Obj->getFileName(), Address); 942 if (!ExpectecLineInfo) 943 consumeError(ExpectecLineInfo.takeError()); 944 else 945 LineInfo = *ExpectecLineInfo; 946 947 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line || 948 LineInfo.Line == 0) 949 return; 950 951 if (PrintLines) 952 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n"; 953 if (PrintSource) { 954 if (SourceCache.find(LineInfo.FileName) == SourceCache.end()) 955 if (!cacheSource(LineInfo)) 956 return; 957 auto FileBuffer = SourceCache.find(LineInfo.FileName); 958 if (FileBuffer != SourceCache.end()) { 959 auto LineBuffer = LineCache.find(LineInfo.FileName); 960 if (LineBuffer != LineCache.end()) { 961 if (LineInfo.Line > LineBuffer->second.size()) 962 return; 963 // Vector begins at 0, line numbers are non-zero 964 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim() 965 << "\n"; 966 } 967 } 968 } 969 OldLineInfo = LineInfo; 970 } 971 972 static bool isArmElf(const ObjectFile *Obj) { 973 return (Obj->isELF() && 974 (Obj->getArch() == Triple::aarch64 || 975 Obj->getArch() == Triple::aarch64_be || 976 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb || 977 Obj->getArch() == Triple::thumb || 978 Obj->getArch() == Triple::thumbeb)); 979 } 980 981 class PrettyPrinter { 982 public: 983 virtual ~PrettyPrinter() = default; 984 virtual void printInst(MCInstPrinter &IP, const MCInst *MI, 985 ArrayRef<uint8_t> Bytes, uint64_t Address, 986 raw_ostream &OS, StringRef Annot, 987 MCSubtargetInfo const &STI, SourcePrinter *SP, 988 std::vector<RelocationRef> *Rels = nullptr) { 989 if (SP && (PrintSource || PrintLines)) 990 SP->printSourceLine(OS, Address); 991 if (!NoLeadingAddr) 992 OS << format("%8" PRIx64 ":", Address); 993 if (!NoShowRawInsn) { 994 OS << "\t"; 995 dumpBytes(Bytes, OS); 996 } 997 if (MI) 998 IP.printInst(MI, OS, "", STI); 999 else 1000 OS << " <unknown>"; 1001 } 1002 }; 1003 PrettyPrinter PrettyPrinterInst; 1004 class HexagonPrettyPrinter : public PrettyPrinter { 1005 public: 1006 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address, 1007 raw_ostream &OS) { 1008 uint32_t opcode = 1009 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0]; 1010 if (!NoLeadingAddr) 1011 OS << format("%8" PRIx64 ":", Address); 1012 if (!NoShowRawInsn) { 1013 OS << "\t"; 1014 dumpBytes(Bytes.slice(0, 4), OS); 1015 OS << format("%08" PRIx32, opcode); 1016 } 1017 } 1018 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 1019 uint64_t Address, raw_ostream &OS, StringRef Annot, 1020 MCSubtargetInfo const &STI, SourcePrinter *SP, 1021 std::vector<RelocationRef> *Rels) override { 1022 if (SP && (PrintSource || PrintLines)) 1023 SP->printSourceLine(OS, Address, ""); 1024 if (!MI) { 1025 printLead(Bytes, Address, OS); 1026 OS << " <unknown>"; 1027 return; 1028 } 1029 std::string Buffer; 1030 { 1031 raw_string_ostream TempStream(Buffer); 1032 IP.printInst(MI, TempStream, "", STI); 1033 } 1034 StringRef Contents(Buffer); 1035 // Split off bundle attributes 1036 auto PacketBundle = Contents.rsplit('\n'); 1037 // Split off first instruction from the rest 1038 auto HeadTail = PacketBundle.first.split('\n'); 1039 auto Preamble = " { "; 1040 auto Separator = ""; 1041 StringRef Fmt = "\t\t\t%08" PRIx64 ": "; 1042 std::vector<RelocationRef>::const_iterator rel_cur = Rels->begin(); 1043 std::vector<RelocationRef>::const_iterator rel_end = Rels->end(); 1044 1045 // Hexagon's packets require relocations to be inline rather than 1046 // clustered at the end of the packet. 1047 auto PrintReloc = [&]() -> void { 1048 while ((rel_cur != rel_end) && (rel_cur->getOffset() <= Address)) { 1049 if (rel_cur->getOffset() == Address) { 1050 SmallString<16> name; 1051 SmallString<32> val; 1052 rel_cur->getTypeName(name); 1053 error(getRelocationValueString(*rel_cur, val)); 1054 OS << Separator << format(Fmt.data(), Address) << name << "\t" << val 1055 << "\n"; 1056 return; 1057 } 1058 rel_cur++; 1059 } 1060 }; 1061 1062 while(!HeadTail.first.empty()) { 1063 OS << Separator; 1064 Separator = "\n"; 1065 if (SP && (PrintSource || PrintLines)) 1066 SP->printSourceLine(OS, Address, ""); 1067 printLead(Bytes, Address, OS); 1068 OS << Preamble; 1069 Preamble = " "; 1070 StringRef Inst; 1071 auto Duplex = HeadTail.first.split('\v'); 1072 if(!Duplex.second.empty()){ 1073 OS << Duplex.first; 1074 OS << "; "; 1075 Inst = Duplex.second; 1076 } 1077 else 1078 Inst = HeadTail.first; 1079 OS << Inst; 1080 HeadTail = HeadTail.second.split('\n'); 1081 if (HeadTail.first.empty()) 1082 OS << " } " << PacketBundle.second; 1083 PrintReloc(); 1084 Bytes = Bytes.slice(4); 1085 Address += 4; 1086 } 1087 } 1088 }; 1089 HexagonPrettyPrinter HexagonPrettyPrinterInst; 1090 1091 class AMDGCNPrettyPrinter : public PrettyPrinter { 1092 public: 1093 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 1094 uint64_t Address, raw_ostream &OS, StringRef Annot, 1095 MCSubtargetInfo const &STI, SourcePrinter *SP, 1096 std::vector<RelocationRef> *Rels) override { 1097 if (SP && (PrintSource || PrintLines)) 1098 SP->printSourceLine(OS, Address); 1099 1100 typedef support::ulittle32_t U32; 1101 1102 if (MI) { 1103 SmallString<40> InstStr; 1104 raw_svector_ostream IS(InstStr); 1105 1106 IP.printInst(MI, IS, "", STI); 1107 1108 OS << left_justify(IS.str(), 60); 1109 } else { 1110 // an unrecognized encoding - this is probably data so represent it 1111 // using the .long directive, or .byte directive if fewer than 4 bytes 1112 // remaining 1113 if (Bytes.size() >= 4) { 1114 OS << format("\t.long 0x%08" PRIx32 " ", 1115 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data()))); 1116 OS.indent(42); 1117 } else { 1118 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]); 1119 for (unsigned int i = 1; i < Bytes.size(); i++) 1120 OS << format(", 0x%02" PRIx8, Bytes[i]); 1121 OS.indent(55 - (6 * Bytes.size())); 1122 } 1123 } 1124 1125 OS << format("// %012" PRIX64 ": ", Address); 1126 if (Bytes.size() >=4) { 1127 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()), 1128 Bytes.size() / sizeof(U32))) 1129 // D should be explicitly casted to uint32_t here as it is passed 1130 // by format to snprintf as vararg. 1131 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D)); 1132 } else { 1133 for (unsigned int i = 0; i < Bytes.size(); i++) 1134 OS << format("%02" PRIX8 " ", Bytes[i]); 1135 } 1136 1137 if (!Annot.empty()) 1138 OS << "// " << Annot; 1139 } 1140 }; 1141 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst; 1142 1143 class BPFPrettyPrinter : public PrettyPrinter { 1144 public: 1145 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 1146 uint64_t Address, raw_ostream &OS, StringRef Annot, 1147 MCSubtargetInfo const &STI, SourcePrinter *SP, 1148 std::vector<RelocationRef> *Rels) override { 1149 if (SP && (PrintSource || PrintLines)) 1150 SP->printSourceLine(OS, Address); 1151 if (!NoLeadingAddr) 1152 OS << format("%8" PRId64 ":", Address / 8); 1153 if (!NoShowRawInsn) { 1154 OS << "\t"; 1155 dumpBytes(Bytes, OS); 1156 } 1157 if (MI) 1158 IP.printInst(MI, OS, "", STI); 1159 else 1160 OS << " <unknown>"; 1161 } 1162 }; 1163 BPFPrettyPrinter BPFPrettyPrinterInst; 1164 1165 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) { 1166 switch(Triple.getArch()) { 1167 default: 1168 return PrettyPrinterInst; 1169 case Triple::hexagon: 1170 return HexagonPrettyPrinterInst; 1171 case Triple::amdgcn: 1172 return AMDGCNPrettyPrinterInst; 1173 case Triple::bpfel: 1174 case Triple::bpfeb: 1175 return BPFPrettyPrinterInst; 1176 } 1177 } 1178 } 1179 1180 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) { 1181 assert(Obj->isELF()); 1182 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj)) 1183 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1184 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj)) 1185 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1186 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj)) 1187 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1188 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj)) 1189 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 1190 llvm_unreachable("Unsupported binary format"); 1191 } 1192 1193 template <class ELFT> static void 1194 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj, 1195 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { 1196 for (auto Symbol : Obj->getDynamicSymbolIterators()) { 1197 uint8_t SymbolType = Symbol.getELFType(); 1198 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0) 1199 continue; 1200 1201 Expected<uint64_t> AddressOrErr = Symbol.getAddress(); 1202 if (!AddressOrErr) 1203 report_error(Obj->getFileName(), AddressOrErr.takeError()); 1204 uint64_t Address = *AddressOrErr; 1205 1206 Expected<StringRef> Name = Symbol.getName(); 1207 if (!Name) 1208 report_error(Obj->getFileName(), Name.takeError()); 1209 if (Name->empty()) 1210 continue; 1211 1212 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 1213 if (!SectionOrErr) 1214 report_error(Obj->getFileName(), SectionOrErr.takeError()); 1215 section_iterator SecI = *SectionOrErr; 1216 if (SecI == Obj->section_end()) 1217 continue; 1218 1219 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType); 1220 } 1221 } 1222 1223 static void 1224 addDynamicElfSymbols(const ObjectFile *Obj, 1225 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { 1226 assert(Obj->isELF()); 1227 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj)) 1228 addDynamicElfSymbols(Elf32LEObj, AllSymbols); 1229 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj)) 1230 addDynamicElfSymbols(Elf64LEObj, AllSymbols); 1231 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj)) 1232 addDynamicElfSymbols(Elf32BEObj, AllSymbols); 1233 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj)) 1234 addDynamicElfSymbols(Elf64BEObj, AllSymbols); 1235 else 1236 llvm_unreachable("Unsupported binary format"); 1237 } 1238 1239 static void addPltEntries(const ObjectFile *Obj, 1240 std::map<SectionRef, SectionSymbolsTy> &AllSymbols, 1241 StringSaver &Saver) { 1242 Optional<SectionRef> Plt = None; 1243 for (const SectionRef &Section : Obj->sections()) { 1244 StringRef Name; 1245 if (Section.getName(Name)) 1246 continue; 1247 if (Name == ".plt") 1248 Plt = Section; 1249 } 1250 if (!Plt) 1251 return; 1252 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) { 1253 for (auto PltEntry : ElfObj->getPltAddresses()) { 1254 SymbolRef Symbol(PltEntry.first, ElfObj); 1255 1256 uint8_t SymbolType = getElfSymbolType(Obj, Symbol); 1257 1258 Expected<StringRef> NameOrErr = Symbol.getName(); 1259 if (!NameOrErr) 1260 report_error(Obj->getFileName(), NameOrErr.takeError()); 1261 if (NameOrErr->empty()) 1262 continue; 1263 StringRef Name = Saver.save((*NameOrErr + "@plt").str()); 1264 1265 AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType); 1266 } 1267 } 1268 } 1269 1270 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) { 1271 if (StartAddress > StopAddress) 1272 error("Start address should be less than stop address"); 1273 1274 const Target *TheTarget = getTarget(Obj); 1275 1276 // Package up features to be passed to target/subtarget 1277 SubtargetFeatures Features = Obj->getFeatures(); 1278 if (MAttrs.size()) { 1279 for (unsigned i = 0; i != MAttrs.size(); ++i) 1280 Features.AddFeature(MAttrs[i]); 1281 } 1282 1283 std::unique_ptr<const MCRegisterInfo> MRI( 1284 TheTarget->createMCRegInfo(TripleName)); 1285 if (!MRI) 1286 report_error(Obj->getFileName(), "no register info for target " + 1287 TripleName); 1288 1289 // Set up disassembler. 1290 std::unique_ptr<const MCAsmInfo> AsmInfo( 1291 TheTarget->createMCAsmInfo(*MRI, TripleName)); 1292 if (!AsmInfo) 1293 report_error(Obj->getFileName(), "no assembly info for target " + 1294 TripleName); 1295 std::unique_ptr<const MCSubtargetInfo> STI( 1296 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString())); 1297 if (!STI) 1298 report_error(Obj->getFileName(), "no subtarget info for target " + 1299 TripleName); 1300 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); 1301 if (!MII) 1302 report_error(Obj->getFileName(), "no instruction info for target " + 1303 TripleName); 1304 MCObjectFileInfo MOFI; 1305 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI); 1306 // FIXME: for now initialize MCObjectFileInfo with default values 1307 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx); 1308 1309 std::unique_ptr<MCDisassembler> DisAsm( 1310 TheTarget->createMCDisassembler(*STI, Ctx)); 1311 if (!DisAsm) 1312 report_error(Obj->getFileName(), "no disassembler for target " + 1313 TripleName); 1314 1315 std::unique_ptr<const MCInstrAnalysis> MIA( 1316 TheTarget->createMCInstrAnalysis(MII.get())); 1317 1318 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 1319 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 1320 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI)); 1321 if (!IP) 1322 report_error(Obj->getFileName(), "no instruction printer for target " + 1323 TripleName); 1324 IP->setPrintImmHex(PrintImmHex); 1325 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName)); 1326 1327 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " : 1328 "\t\t\t%08" PRIx64 ": "; 1329 1330 SourcePrinter SP(Obj, TheTarget->getName()); 1331 1332 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections 1333 // in RelocSecs contain the relocations for section S. 1334 std::error_code EC; 1335 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap; 1336 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1337 section_iterator Sec2 = Section.getRelocatedSection(); 1338 if (Sec2 != Obj->section_end()) 1339 SectionRelocMap[*Sec2].push_back(Section); 1340 } 1341 1342 // Create a mapping from virtual address to symbol name. This is used to 1343 // pretty print the symbols while disassembling. 1344 std::map<SectionRef, SectionSymbolsTy> AllSymbols; 1345 SectionSymbolsTy AbsoluteSymbols; 1346 for (const SymbolRef &Symbol : Obj->symbols()) { 1347 Expected<uint64_t> AddressOrErr = Symbol.getAddress(); 1348 if (!AddressOrErr) 1349 report_error(Obj->getFileName(), AddressOrErr.takeError()); 1350 uint64_t Address = *AddressOrErr; 1351 1352 Expected<StringRef> Name = Symbol.getName(); 1353 if (!Name) 1354 report_error(Obj->getFileName(), Name.takeError()); 1355 if (Name->empty()) 1356 continue; 1357 1358 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 1359 if (!SectionOrErr) 1360 report_error(Obj->getFileName(), SectionOrErr.takeError()); 1361 1362 uint8_t SymbolType = ELF::STT_NOTYPE; 1363 if (Obj->isELF()) 1364 SymbolType = getElfSymbolType(Obj, Symbol); 1365 1366 section_iterator SecI = *SectionOrErr; 1367 if (SecI != Obj->section_end()) 1368 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType); 1369 else 1370 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType); 1371 1372 1373 } 1374 if (AllSymbols.empty() && Obj->isELF()) 1375 addDynamicElfSymbols(Obj, AllSymbols); 1376 1377 BumpPtrAllocator A; 1378 StringSaver Saver(A); 1379 addPltEntries(Obj, AllSymbols, Saver); 1380 1381 // Create a mapping from virtual address to section. 1382 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses; 1383 for (SectionRef Sec : Obj->sections()) 1384 SectionAddresses.emplace_back(Sec.getAddress(), Sec); 1385 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end()); 1386 1387 // Linked executables (.exe and .dll files) typically don't include a real 1388 // symbol table but they might contain an export table. 1389 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) { 1390 for (const auto &ExportEntry : COFFObj->export_directories()) { 1391 StringRef Name; 1392 error(ExportEntry.getSymbolName(Name)); 1393 if (Name.empty()) 1394 continue; 1395 uint32_t RVA; 1396 error(ExportEntry.getExportRVA(RVA)); 1397 1398 uint64_t VA = COFFObj->getImageBase() + RVA; 1399 auto Sec = std::upper_bound( 1400 SectionAddresses.begin(), SectionAddresses.end(), VA, 1401 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) { 1402 return LHS < RHS.first; 1403 }); 1404 if (Sec != SectionAddresses.begin()) 1405 --Sec; 1406 else 1407 Sec = SectionAddresses.end(); 1408 1409 if (Sec != SectionAddresses.end()) 1410 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE); 1411 else 1412 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE); 1413 } 1414 } 1415 1416 // Sort all the symbols, this allows us to use a simple binary search to find 1417 // a symbol near an address. 1418 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols) 1419 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end()); 1420 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end()); 1421 1422 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1423 if (!DisassembleAll && (!Section.isText() || Section.isVirtual())) 1424 continue; 1425 1426 uint64_t SectionAddr = Section.getAddress(); 1427 uint64_t SectSize = Section.getSize(); 1428 if (!SectSize) 1429 continue; 1430 1431 // Get the list of all the symbols in this section. 1432 SectionSymbolsTy &Symbols = AllSymbols[Section]; 1433 std::vector<uint64_t> DataMappingSymsAddr; 1434 std::vector<uint64_t> TextMappingSymsAddr; 1435 if (isArmElf(Obj)) { 1436 for (const auto &Symb : Symbols) { 1437 uint64_t Address = std::get<0>(Symb); 1438 StringRef Name = std::get<1>(Symb); 1439 if (Name.startswith("$d")) 1440 DataMappingSymsAddr.push_back(Address - SectionAddr); 1441 if (Name.startswith("$x")) 1442 TextMappingSymsAddr.push_back(Address - SectionAddr); 1443 if (Name.startswith("$a")) 1444 TextMappingSymsAddr.push_back(Address - SectionAddr); 1445 if (Name.startswith("$t")) 1446 TextMappingSymsAddr.push_back(Address - SectionAddr); 1447 } 1448 } 1449 1450 llvm::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end()); 1451 llvm::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end()); 1452 1453 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1454 // AMDGPU disassembler uses symbolizer for printing labels 1455 std::unique_ptr<MCRelocationInfo> RelInfo( 1456 TheTarget->createMCRelocationInfo(TripleName, Ctx)); 1457 if (RelInfo) { 1458 std::unique_ptr<MCSymbolizer> Symbolizer( 1459 TheTarget->createMCSymbolizer( 1460 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo))); 1461 DisAsm->setSymbolizer(std::move(Symbolizer)); 1462 } 1463 } 1464 1465 // Make a list of all the relocations for this section. 1466 std::vector<RelocationRef> Rels; 1467 if (InlineRelocs) { 1468 for (const SectionRef &RelocSec : SectionRelocMap[Section]) { 1469 for (const RelocationRef &Reloc : RelocSec.relocations()) { 1470 Rels.push_back(Reloc); 1471 } 1472 } 1473 } 1474 1475 // Sort relocations by address. 1476 llvm::sort(Rels.begin(), Rels.end(), RelocAddressLess); 1477 1478 StringRef SegmentName = ""; 1479 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) { 1480 DataRefImpl DR = Section.getRawDataRefImpl(); 1481 SegmentName = MachO->getSectionFinalSegmentName(DR); 1482 } 1483 StringRef SectionName; 1484 error(Section.getName(SectionName)); 1485 1486 // If the section has no symbol at the start, just insert a dummy one. 1487 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) { 1488 Symbols.insert( 1489 Symbols.begin(), 1490 std::make_tuple(SectionAddr, SectionName, 1491 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT)); 1492 } 1493 1494 SmallString<40> Comments; 1495 raw_svector_ostream CommentStream(Comments); 1496 1497 StringRef BytesStr; 1498 error(Section.getContents(BytesStr)); 1499 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()), 1500 BytesStr.size()); 1501 1502 uint64_t Size; 1503 uint64_t Index; 1504 bool PrintedSection = false; 1505 1506 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin(); 1507 std::vector<RelocationRef>::const_iterator rel_end = Rels.end(); 1508 // Disassemble symbol by symbol. 1509 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) { 1510 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr; 1511 // The end is either the section end or the beginning of the next 1512 // symbol. 1513 uint64_t End = 1514 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr; 1515 // Don't try to disassemble beyond the end of section contents. 1516 if (End > SectSize) 1517 End = SectSize; 1518 // If this symbol has the same address as the next symbol, then skip it. 1519 if (Start >= End) 1520 continue; 1521 1522 // Check if we need to skip symbol 1523 // Skip if the symbol's data is not between StartAddress and StopAddress 1524 if (End + SectionAddr < StartAddress || 1525 Start + SectionAddr > StopAddress) { 1526 continue; 1527 } 1528 1529 /// Skip if user requested specific symbols and this is not in the list 1530 if (!DisasmFuncsSet.empty() && 1531 !DisasmFuncsSet.count(std::get<1>(Symbols[si]))) 1532 continue; 1533 1534 if (!PrintedSection) { 1535 PrintedSection = true; 1536 outs() << "Disassembly of section "; 1537 if (!SegmentName.empty()) 1538 outs() << SegmentName << ","; 1539 outs() << SectionName << ':'; 1540 } 1541 1542 // Stop disassembly at the stop address specified 1543 if (End + SectionAddr > StopAddress) 1544 End = StopAddress - SectionAddr; 1545 1546 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1547 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) { 1548 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes) 1549 Start += 256; 1550 } 1551 if (si == se - 1 || 1552 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) { 1553 // cut trailing zeroes at the end of kernel 1554 // cut up to 256 bytes 1555 const uint64_t EndAlign = 256; 1556 const auto Limit = End - (std::min)(EndAlign, End - Start); 1557 while (End > Limit && 1558 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0) 1559 End -= 4; 1560 } 1561 } 1562 1563 auto PrintSymbol = [](StringRef Name) { 1564 outs() << '\n' << Name << ":\n"; 1565 }; 1566 StringRef SymbolName = std::get<1>(Symbols[si]); 1567 if (Demangle) { 1568 char *DemangledSymbol = nullptr; 1569 size_t Size = 0; 1570 int Status = -1; 1571 if (SymbolName.startswith("_Z")) 1572 DemangledSymbol = itaniumDemangle(SymbolName.data(), DemangledSymbol, 1573 &Size, &Status); 1574 else if (SymbolName.startswith("?")) 1575 DemangledSymbol = microsoftDemangle(SymbolName.data(), 1576 DemangledSymbol, &Size, &Status); 1577 1578 if (Status == 0 && DemangledSymbol) 1579 PrintSymbol(StringRef(DemangledSymbol)); 1580 else 1581 PrintSymbol(SymbolName); 1582 1583 if (DemangledSymbol) 1584 free(DemangledSymbol); 1585 } else 1586 PrintSymbol(SymbolName); 1587 1588 // Don't print raw contents of a virtual section. A virtual section 1589 // doesn't have any contents in the file. 1590 if (Section.isVirtual()) { 1591 outs() << "...\n"; 1592 continue; 1593 } 1594 1595 #ifndef NDEBUG 1596 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); 1597 #else 1598 raw_ostream &DebugOut = nulls(); 1599 #endif 1600 1601 for (Index = Start; Index < End; Index += Size) { 1602 MCInst Inst; 1603 1604 if (Index + SectionAddr < StartAddress || 1605 Index + SectionAddr > StopAddress) { 1606 // skip byte by byte till StartAddress is reached 1607 Size = 1; 1608 continue; 1609 } 1610 // AArch64 ELF binaries can interleave data and text in the 1611 // same section. We rely on the markers introduced to 1612 // understand what we need to dump. If the data marker is within a 1613 // function, it is denoted as a word/short etc 1614 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT && 1615 !DisassembleAll) { 1616 uint64_t Stride = 0; 1617 1618 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(), 1619 DataMappingSymsAddr.end(), Index); 1620 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) { 1621 // Switch to data. 1622 while (Index < End) { 1623 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 1624 outs() << "\t"; 1625 if (Index + 4 <= End) { 1626 Stride = 4; 1627 dumpBytes(Bytes.slice(Index, 4), outs()); 1628 outs() << "\t.word\t"; 1629 uint32_t Data = 0; 1630 if (Obj->isLittleEndian()) { 1631 const auto Word = 1632 reinterpret_cast<const support::ulittle32_t *>( 1633 Bytes.data() + Index); 1634 Data = *Word; 1635 } else { 1636 const auto Word = reinterpret_cast<const support::ubig32_t *>( 1637 Bytes.data() + Index); 1638 Data = *Word; 1639 } 1640 outs() << "0x" << format("%08" PRIx32, Data); 1641 } else if (Index + 2 <= End) { 1642 Stride = 2; 1643 dumpBytes(Bytes.slice(Index, 2), outs()); 1644 outs() << "\t\t.short\t"; 1645 uint16_t Data = 0; 1646 if (Obj->isLittleEndian()) { 1647 const auto Short = 1648 reinterpret_cast<const support::ulittle16_t *>( 1649 Bytes.data() + Index); 1650 Data = *Short; 1651 } else { 1652 const auto Short = 1653 reinterpret_cast<const support::ubig16_t *>(Bytes.data() + 1654 Index); 1655 Data = *Short; 1656 } 1657 outs() << "0x" << format("%04" PRIx16, Data); 1658 } else { 1659 Stride = 1; 1660 dumpBytes(Bytes.slice(Index, 1), outs()); 1661 outs() << "\t\t.byte\t"; 1662 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]); 1663 } 1664 Index += Stride; 1665 outs() << "\n"; 1666 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(), 1667 TextMappingSymsAddr.end(), Index); 1668 if (TAI != TextMappingSymsAddr.end() && *TAI == Index) 1669 break; 1670 } 1671 } 1672 } 1673 1674 // If there is a data symbol inside an ELF text section and we are only 1675 // disassembling text (applicable all architectures), 1676 // we are in a situation where we must print the data and not 1677 // disassemble it. 1678 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT && 1679 !DisassembleAll && Section.isText()) { 1680 // print out data up to 8 bytes at a time in hex and ascii 1681 uint8_t AsciiData[9] = {'\0'}; 1682 uint8_t Byte; 1683 int NumBytes = 0; 1684 1685 for (Index = Start; Index < End; Index += 1) { 1686 if (((SectionAddr + Index) < StartAddress) || 1687 ((SectionAddr + Index) > StopAddress)) 1688 continue; 1689 if (NumBytes == 0) { 1690 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 1691 outs() << "\t"; 1692 } 1693 Byte = Bytes.slice(Index)[0]; 1694 outs() << format(" %02x", Byte); 1695 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.'; 1696 1697 uint8_t IndentOffset = 0; 1698 NumBytes++; 1699 if (Index == End - 1 || NumBytes > 8) { 1700 // Indent the space for less than 8 bytes data. 1701 // 2 spaces for byte and one for space between bytes 1702 IndentOffset = 3 * (8 - NumBytes); 1703 for (int Excess = 8 - NumBytes; Excess < 8; Excess++) 1704 AsciiData[Excess] = '\0'; 1705 NumBytes = 8; 1706 } 1707 if (NumBytes == 8) { 1708 AsciiData[8] = '\0'; 1709 outs() << std::string(IndentOffset, ' ') << " "; 1710 outs() << reinterpret_cast<char *>(AsciiData); 1711 outs() << '\n'; 1712 NumBytes = 0; 1713 } 1714 } 1715 } 1716 if (Index >= End) 1717 break; 1718 1719 // Disassemble a real instruction or a data when disassemble all is 1720 // provided 1721 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), 1722 SectionAddr + Index, DebugOut, 1723 CommentStream); 1724 if (Size == 0) 1725 Size = 1; 1726 1727 PIP.printInst(*IP, Disassembled ? &Inst : nullptr, 1728 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "", 1729 *STI, &SP, &Rels); 1730 outs() << CommentStream.str(); 1731 Comments.clear(); 1732 1733 // Try to resolve the target of a call, tail call, etc. to a specific 1734 // symbol. 1735 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) || 1736 MIA->isConditionalBranch(Inst))) { 1737 uint64_t Target; 1738 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) { 1739 // In a relocatable object, the target's section must reside in 1740 // the same section as the call instruction or it is accessed 1741 // through a relocation. 1742 // 1743 // In a non-relocatable object, the target may be in any section. 1744 // 1745 // N.B. We don't walk the relocations in the relocatable case yet. 1746 auto *TargetSectionSymbols = &Symbols; 1747 if (!Obj->isRelocatableObject()) { 1748 auto SectionAddress = std::upper_bound( 1749 SectionAddresses.begin(), SectionAddresses.end(), Target, 1750 [](uint64_t LHS, 1751 const std::pair<uint64_t, SectionRef> &RHS) { 1752 return LHS < RHS.first; 1753 }); 1754 if (SectionAddress != SectionAddresses.begin()) { 1755 --SectionAddress; 1756 TargetSectionSymbols = &AllSymbols[SectionAddress->second]; 1757 } else { 1758 TargetSectionSymbols = &AbsoluteSymbols; 1759 } 1760 } 1761 1762 // Find the first symbol in the section whose offset is less than 1763 // or equal to the target. If there isn't a section that contains 1764 // the target, find the nearest preceding absolute symbol. 1765 auto TargetSym = std::upper_bound( 1766 TargetSectionSymbols->begin(), TargetSectionSymbols->end(), 1767 Target, [](uint64_t LHS, 1768 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) { 1769 return LHS < std::get<0>(RHS); 1770 }); 1771 if (TargetSym == TargetSectionSymbols->begin()) { 1772 TargetSectionSymbols = &AbsoluteSymbols; 1773 TargetSym = std::upper_bound( 1774 AbsoluteSymbols.begin(), AbsoluteSymbols.end(), 1775 Target, [](uint64_t LHS, 1776 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) { 1777 return LHS < std::get<0>(RHS); 1778 }); 1779 } 1780 if (TargetSym != TargetSectionSymbols->begin()) { 1781 --TargetSym; 1782 uint64_t TargetAddress = std::get<0>(*TargetSym); 1783 StringRef TargetName = std::get<1>(*TargetSym); 1784 outs() << " <" << TargetName; 1785 uint64_t Disp = Target - TargetAddress; 1786 if (Disp) 1787 outs() << "+0x" << Twine::utohexstr(Disp); 1788 outs() << '>'; 1789 } 1790 } 1791 } 1792 outs() << "\n"; 1793 1794 // Hexagon does this in pretty printer 1795 if (Obj->getArch() != Triple::hexagon) 1796 // Print relocation for instruction. 1797 while (rel_cur != rel_end) { 1798 bool hidden = getHidden(*rel_cur); 1799 uint64_t addr = rel_cur->getOffset(); 1800 SmallString<16> name; 1801 SmallString<32> val; 1802 1803 // If this relocation is hidden, skip it. 1804 if (hidden || ((SectionAddr + addr) < StartAddress)) { 1805 ++rel_cur; 1806 continue; 1807 } 1808 1809 // Stop when rel_cur's address is past the current instruction. 1810 if (addr >= Index + Size) break; 1811 rel_cur->getTypeName(name); 1812 error(getRelocationValueString(*rel_cur, val)); 1813 outs() << format(Fmt.data(), SectionAddr + addr) << name 1814 << "\t" << val << "\n"; 1815 ++rel_cur; 1816 } 1817 } 1818 } 1819 } 1820 } 1821 1822 void llvm::PrintRelocations(const ObjectFile *Obj) { 1823 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : 1824 "%08" PRIx64; 1825 // Regular objdump doesn't print relocations in non-relocatable object 1826 // files. 1827 if (!Obj->isRelocatableObject()) 1828 return; 1829 1830 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1831 if (Section.relocation_begin() == Section.relocation_end()) 1832 continue; 1833 StringRef secname; 1834 error(Section.getName(secname)); 1835 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n"; 1836 for (const RelocationRef &Reloc : Section.relocations()) { 1837 bool hidden = getHidden(Reloc); 1838 uint64_t address = Reloc.getOffset(); 1839 SmallString<32> relocname; 1840 SmallString<32> valuestr; 1841 if (address < StartAddress || address > StopAddress || hidden) 1842 continue; 1843 Reloc.getTypeName(relocname); 1844 error(getRelocationValueString(Reloc, valuestr)); 1845 outs() << format(Fmt.data(), address) << " " << relocname << " " 1846 << valuestr << "\n"; 1847 } 1848 outs() << "\n"; 1849 } 1850 } 1851 1852 void llvm::PrintDynamicRelocations(const ObjectFile *Obj) { 1853 1854 // For the moment, this option is for ELF only 1855 if (!Obj->isELF()) 1856 return; 1857 1858 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj); 1859 1860 if (!Elf || Elf->getEType() != ELF::ET_DYN) { 1861 error("not a dynamic object"); 1862 return; 1863 } 1864 1865 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 1866 1867 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections(); 1868 if (DynRelSec.empty()) 1869 return; 1870 1871 outs() << "DYNAMIC RELOCATION RECORDS\n"; 1872 for (const SectionRef &Section : DynRelSec) { 1873 if (Section.relocation_begin() == Section.relocation_end()) 1874 continue; 1875 for (const RelocationRef &Reloc : Section.relocations()) { 1876 uint64_t address = Reloc.getOffset(); 1877 SmallString<32> relocname; 1878 SmallString<32> valuestr; 1879 Reloc.getTypeName(relocname); 1880 error(getRelocationValueString(Reloc, valuestr)); 1881 outs() << format(Fmt.data(), address) << " " << relocname << " " 1882 << valuestr << "\n"; 1883 } 1884 } 1885 } 1886 1887 void llvm::PrintSectionHeaders(const ObjectFile *Obj) { 1888 outs() << "Sections:\n" 1889 "Idx Name Size Address Type\n"; 1890 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1891 StringRef Name; 1892 error(Section.getName(Name)); 1893 uint64_t Address = Section.getAddress(); 1894 uint64_t Size = Section.getSize(); 1895 bool Text = Section.isText(); 1896 bool Data = Section.isData(); 1897 bool BSS = Section.isBSS(); 1898 std::string Type = (std::string(Text ? "TEXT " : "") + 1899 (Data ? "DATA " : "") + (BSS ? "BSS" : "")); 1900 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", 1901 (unsigned)Section.getIndex(), Name.str().c_str(), Size, 1902 Address, Type.c_str()); 1903 } 1904 } 1905 1906 void llvm::PrintSectionContents(const ObjectFile *Obj) { 1907 std::error_code EC; 1908 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1909 StringRef Name; 1910 StringRef Contents; 1911 error(Section.getName(Name)); 1912 uint64_t BaseAddr = Section.getAddress(); 1913 uint64_t Size = Section.getSize(); 1914 if (!Size) 1915 continue; 1916 1917 outs() << "Contents of section " << Name << ":\n"; 1918 if (Section.isBSS()) { 1919 outs() << format("<skipping contents of bss section at [%04" PRIx64 1920 ", %04" PRIx64 ")>\n", 1921 BaseAddr, BaseAddr + Size); 1922 continue; 1923 } 1924 1925 error(Section.getContents(Contents)); 1926 1927 // Dump out the content as hex and printable ascii characters. 1928 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) { 1929 outs() << format(" %04" PRIx64 " ", BaseAddr + addr); 1930 // Dump line of hex. 1931 for (std::size_t i = 0; i < 16; ++i) { 1932 if (i != 0 && i % 4 == 0) 1933 outs() << ' '; 1934 if (addr + i < end) 1935 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true) 1936 << hexdigit(Contents[addr + i] & 0xF, true); 1937 else 1938 outs() << " "; 1939 } 1940 // Print ascii. 1941 outs() << " "; 1942 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) { 1943 if (isPrint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF)) 1944 outs() << Contents[addr + i]; 1945 else 1946 outs() << "."; 1947 } 1948 outs() << "\n"; 1949 } 1950 } 1951 } 1952 1953 void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName, 1954 StringRef ArchitectureName) { 1955 outs() << "SYMBOL TABLE:\n"; 1956 1957 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) { 1958 printCOFFSymbolTable(coff); 1959 return; 1960 } 1961 for (const SymbolRef &Symbol : o->symbols()) { 1962 Expected<uint64_t> AddressOrError = Symbol.getAddress(); 1963 if (!AddressOrError) 1964 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(), 1965 ArchitectureName); 1966 uint64_t Address = *AddressOrError; 1967 if ((Address < StartAddress) || (Address > StopAddress)) 1968 continue; 1969 Expected<SymbolRef::Type> TypeOrError = Symbol.getType(); 1970 if (!TypeOrError) 1971 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(), 1972 ArchitectureName); 1973 SymbolRef::Type Type = *TypeOrError; 1974 uint32_t Flags = Symbol.getFlags(); 1975 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 1976 if (!SectionOrErr) 1977 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(), 1978 ArchitectureName); 1979 section_iterator Section = *SectionOrErr; 1980 StringRef Name; 1981 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) { 1982 Section->getName(Name); 1983 } else { 1984 Expected<StringRef> NameOrErr = Symbol.getName(); 1985 if (!NameOrErr) 1986 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(), 1987 ArchitectureName); 1988 Name = *NameOrErr; 1989 } 1990 1991 bool Global = Flags & SymbolRef::SF_Global; 1992 bool Weak = Flags & SymbolRef::SF_Weak; 1993 bool Absolute = Flags & SymbolRef::SF_Absolute; 1994 bool Common = Flags & SymbolRef::SF_Common; 1995 bool Hidden = Flags & SymbolRef::SF_Hidden; 1996 1997 char GlobLoc = ' '; 1998 if (Type != SymbolRef::ST_Unknown) 1999 GlobLoc = Global ? 'g' : 'l'; 2000 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 2001 ? 'd' : ' '; 2002 char FileFunc = ' '; 2003 if (Type == SymbolRef::ST_File) 2004 FileFunc = 'f'; 2005 else if (Type == SymbolRef::ST_Function) 2006 FileFunc = 'F'; 2007 2008 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : 2009 "%08" PRIx64; 2010 2011 outs() << format(Fmt, Address) << " " 2012 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 2013 << (Weak ? 'w' : ' ') // Weak? 2014 << ' ' // Constructor. Not supported yet. 2015 << ' ' // Warning. Not supported yet. 2016 << ' ' // Indirect reference to another symbol. 2017 << Debug // Debugging (d) or dynamic (D) symbol. 2018 << FileFunc // Name of function (F), file (f) or object (O). 2019 << ' '; 2020 if (Absolute) { 2021 outs() << "*ABS*"; 2022 } else if (Common) { 2023 outs() << "*COM*"; 2024 } else if (Section == o->section_end()) { 2025 outs() << "*UND*"; 2026 } else { 2027 if (const MachOObjectFile *MachO = 2028 dyn_cast<const MachOObjectFile>(o)) { 2029 DataRefImpl DR = Section->getRawDataRefImpl(); 2030 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 2031 outs() << SegmentName << ","; 2032 } 2033 StringRef SectionName; 2034 error(Section->getName(SectionName)); 2035 outs() << SectionName; 2036 } 2037 2038 outs() << '\t'; 2039 if (Common || isa<ELFObjectFileBase>(o)) { 2040 uint64_t Val = 2041 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize(); 2042 outs() << format("\t %08" PRIx64 " ", Val); 2043 } 2044 2045 if (Hidden) { 2046 outs() << ".hidden "; 2047 } 2048 outs() << Name 2049 << '\n'; 2050 } 2051 } 2052 2053 static void PrintUnwindInfo(const ObjectFile *o) { 2054 outs() << "Unwind info:\n\n"; 2055 2056 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) { 2057 printCOFFUnwindInfo(coff); 2058 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 2059 printMachOUnwindInfo(MachO); 2060 else { 2061 // TODO: Extract DWARF dump tool to objdump. 2062 errs() << "This operation is only currently supported " 2063 "for COFF and MachO object files.\n"; 2064 return; 2065 } 2066 } 2067 2068 void llvm::printExportsTrie(const ObjectFile *o) { 2069 outs() << "Exports trie:\n"; 2070 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 2071 printMachOExportsTrie(MachO); 2072 else { 2073 errs() << "This operation is only currently supported " 2074 "for Mach-O executable files.\n"; 2075 return; 2076 } 2077 } 2078 2079 void llvm::printRebaseTable(ObjectFile *o) { 2080 outs() << "Rebase table:\n"; 2081 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 2082 printMachORebaseTable(MachO); 2083 else { 2084 errs() << "This operation is only currently supported " 2085 "for Mach-O executable files.\n"; 2086 return; 2087 } 2088 } 2089 2090 void llvm::printBindTable(ObjectFile *o) { 2091 outs() << "Bind table:\n"; 2092 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 2093 printMachOBindTable(MachO); 2094 else { 2095 errs() << "This operation is only currently supported " 2096 "for Mach-O executable files.\n"; 2097 return; 2098 } 2099 } 2100 2101 void llvm::printLazyBindTable(ObjectFile *o) { 2102 outs() << "Lazy bind table:\n"; 2103 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 2104 printMachOLazyBindTable(MachO); 2105 else { 2106 errs() << "This operation is only currently supported " 2107 "for Mach-O executable files.\n"; 2108 return; 2109 } 2110 } 2111 2112 void llvm::printWeakBindTable(ObjectFile *o) { 2113 outs() << "Weak bind table:\n"; 2114 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 2115 printMachOWeakBindTable(MachO); 2116 else { 2117 errs() << "This operation is only currently supported " 2118 "for Mach-O executable files.\n"; 2119 return; 2120 } 2121 } 2122 2123 /// Dump the raw contents of the __clangast section so the output can be piped 2124 /// into llvm-bcanalyzer. 2125 void llvm::printRawClangAST(const ObjectFile *Obj) { 2126 if (outs().is_displayed()) { 2127 errs() << "The -raw-clang-ast option will dump the raw binary contents of " 2128 "the clang ast section.\n" 2129 "Please redirect the output to a file or another program such as " 2130 "llvm-bcanalyzer.\n"; 2131 return; 2132 } 2133 2134 StringRef ClangASTSectionName("__clangast"); 2135 if (isa<COFFObjectFile>(Obj)) { 2136 ClangASTSectionName = "clangast"; 2137 } 2138 2139 Optional<object::SectionRef> ClangASTSection; 2140 for (auto Sec : ToolSectionFilter(*Obj)) { 2141 StringRef Name; 2142 Sec.getName(Name); 2143 if (Name == ClangASTSectionName) { 2144 ClangASTSection = Sec; 2145 break; 2146 } 2147 } 2148 if (!ClangASTSection) 2149 return; 2150 2151 StringRef ClangASTContents; 2152 error(ClangASTSection.getValue().getContents(ClangASTContents)); 2153 outs().write(ClangASTContents.data(), ClangASTContents.size()); 2154 } 2155 2156 static void printFaultMaps(const ObjectFile *Obj) { 2157 const char *FaultMapSectionName = nullptr; 2158 2159 if (isa<ELFObjectFileBase>(Obj)) { 2160 FaultMapSectionName = ".llvm_faultmaps"; 2161 } else if (isa<MachOObjectFile>(Obj)) { 2162 FaultMapSectionName = "__llvm_faultmaps"; 2163 } else { 2164 errs() << "This operation is only currently supported " 2165 "for ELF and Mach-O executable files.\n"; 2166 return; 2167 } 2168 2169 Optional<object::SectionRef> FaultMapSection; 2170 2171 for (auto Sec : ToolSectionFilter(*Obj)) { 2172 StringRef Name; 2173 Sec.getName(Name); 2174 if (Name == FaultMapSectionName) { 2175 FaultMapSection = Sec; 2176 break; 2177 } 2178 } 2179 2180 outs() << "FaultMap table:\n"; 2181 2182 if (!FaultMapSection.hasValue()) { 2183 outs() << "<not found>\n"; 2184 return; 2185 } 2186 2187 StringRef FaultMapContents; 2188 error(FaultMapSection.getValue().getContents(FaultMapContents)); 2189 2190 FaultMapParser FMP(FaultMapContents.bytes_begin(), 2191 FaultMapContents.bytes_end()); 2192 2193 outs() << FMP; 2194 } 2195 2196 static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) { 2197 if (o->isELF()) { 2198 printELFFileHeader(o); 2199 return printELFDynamicSection(o); 2200 } 2201 if (o->isCOFF()) 2202 return printCOFFFileHeader(o); 2203 if (o->isWasm()) 2204 return printWasmFileHeader(o); 2205 if (o->isMachO()) { 2206 printMachOFileHeader(o); 2207 if (!onlyFirst) 2208 printMachOLoadCommands(o); 2209 return; 2210 } 2211 report_error(o->getFileName(), "Invalid/Unsupported object file format"); 2212 } 2213 2214 static void printFileHeaders(const ObjectFile *o) { 2215 if (!o->isELF() && !o->isCOFF()) 2216 report_error(o->getFileName(), "Invalid/Unsupported object file format"); 2217 2218 Triple::ArchType AT = o->getArch(); 2219 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n"; 2220 Expected<uint64_t> StartAddrOrErr = o->getStartAddress(); 2221 if (!StartAddrOrErr) 2222 report_error(o->getFileName(), StartAddrOrErr.takeError()); 2223 outs() << "start address: " 2224 << format("0x%0*x", o->getBytesInAddress(), StartAddrOrErr.get()) 2225 << "\n"; 2226 } 2227 2228 static void printArchiveChild(StringRef Filename, const Archive::Child &C) { 2229 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode(); 2230 if (!ModeOrErr) { 2231 errs() << "ill-formed archive entry.\n"; 2232 consumeError(ModeOrErr.takeError()); 2233 return; 2234 } 2235 sys::fs::perms Mode = ModeOrErr.get(); 2236 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-"); 2237 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-"); 2238 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-"); 2239 outs() << ((Mode & sys::fs::group_read) ? "r" : "-"); 2240 outs() << ((Mode & sys::fs::group_write) ? "w" : "-"); 2241 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-"); 2242 outs() << ((Mode & sys::fs::others_read) ? "r" : "-"); 2243 outs() << ((Mode & sys::fs::others_write) ? "w" : "-"); 2244 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-"); 2245 2246 outs() << " "; 2247 2248 Expected<unsigned> UIDOrErr = C.getUID(); 2249 if (!UIDOrErr) 2250 report_error(Filename, UIDOrErr.takeError()); 2251 unsigned UID = UIDOrErr.get(); 2252 outs() << format("%d/", UID); 2253 2254 Expected<unsigned> GIDOrErr = C.getGID(); 2255 if (!GIDOrErr) 2256 report_error(Filename, GIDOrErr.takeError()); 2257 unsigned GID = GIDOrErr.get(); 2258 outs() << format("%-d ", GID); 2259 2260 Expected<uint64_t> Size = C.getRawSize(); 2261 if (!Size) 2262 report_error(Filename, Size.takeError()); 2263 outs() << format("%6" PRId64, Size.get()) << " "; 2264 2265 StringRef RawLastModified = C.getRawLastModified(); 2266 unsigned Seconds; 2267 if (RawLastModified.getAsInteger(10, Seconds)) 2268 outs() << "(date: \"" << RawLastModified 2269 << "\" contains non-decimal chars) "; 2270 else { 2271 // Since ctime(3) returns a 26 character string of the form: 2272 // "Sun Sep 16 01:03:52 1973\n\0" 2273 // just print 24 characters. 2274 time_t t = Seconds; 2275 outs() << format("%.24s ", ctime(&t)); 2276 } 2277 2278 StringRef Name = ""; 2279 Expected<StringRef> NameOrErr = C.getName(); 2280 if (!NameOrErr) { 2281 consumeError(NameOrErr.takeError()); 2282 Expected<StringRef> RawNameOrErr = C.getRawName(); 2283 if (!RawNameOrErr) 2284 report_error(Filename, NameOrErr.takeError()); 2285 Name = RawNameOrErr.get(); 2286 } else { 2287 Name = NameOrErr.get(); 2288 } 2289 outs() << Name << "\n"; 2290 } 2291 2292 static void DumpObject(ObjectFile *o, const Archive *a = nullptr, 2293 const Archive::Child *c = nullptr) { 2294 StringRef ArchiveName = a != nullptr ? a->getFileName() : ""; 2295 // Avoid other output when using a raw option. 2296 if (!RawClangAST) { 2297 outs() << '\n'; 2298 if (a) 2299 outs() << a->getFileName() << "(" << o->getFileName() << ")"; 2300 else 2301 outs() << o->getFileName(); 2302 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n"; 2303 } 2304 2305 if (ArchiveHeaders && !MachOOpt) 2306 printArchiveChild(a->getFileName(), *c); 2307 if (Disassemble) 2308 DisassembleObject(o, Relocations); 2309 if (Relocations && !Disassemble) 2310 PrintRelocations(o); 2311 if (DynamicRelocations) 2312 PrintDynamicRelocations(o); 2313 if (SectionHeaders) 2314 PrintSectionHeaders(o); 2315 if (SectionContents) 2316 PrintSectionContents(o); 2317 if (SymbolTable) 2318 PrintSymbolTable(o, ArchiveName); 2319 if (UnwindInfo) 2320 PrintUnwindInfo(o); 2321 if (PrivateHeaders || FirstPrivateHeader) 2322 printPrivateFileHeaders(o, FirstPrivateHeader); 2323 if (FileHeaders) 2324 printFileHeaders(o); 2325 if (ExportsTrie) 2326 printExportsTrie(o); 2327 if (Rebase) 2328 printRebaseTable(o); 2329 if (Bind) 2330 printBindTable(o); 2331 if (LazyBind) 2332 printLazyBindTable(o); 2333 if (WeakBind) 2334 printWeakBindTable(o); 2335 if (RawClangAST) 2336 printRawClangAST(o); 2337 if (PrintFaultMaps) 2338 printFaultMaps(o); 2339 if (DwarfDumpType != DIDT_Null) { 2340 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*o); 2341 // Dump the complete DWARF structure. 2342 DIDumpOptions DumpOpts; 2343 DumpOpts.DumpType = DwarfDumpType; 2344 DICtx->dump(outs(), DumpOpts); 2345 } 2346 } 2347 2348 static void DumpObject(const COFFImportFile *I, const Archive *A, 2349 const Archive::Child *C = nullptr) { 2350 StringRef ArchiveName = A ? A->getFileName() : ""; 2351 2352 // Avoid other output when using a raw option. 2353 if (!RawClangAST) 2354 outs() << '\n' 2355 << ArchiveName << "(" << I->getFileName() << ")" 2356 << ":\tfile format COFF-import-file" 2357 << "\n\n"; 2358 2359 if (ArchiveHeaders && !MachOOpt) 2360 printArchiveChild(A->getFileName(), *C); 2361 if (SymbolTable) 2362 printCOFFSymbolTable(I); 2363 } 2364 2365 /// Dump each object file in \a a; 2366 static void DumpArchive(const Archive *a) { 2367 Error Err = Error::success(); 2368 for (auto &C : a->children(Err)) { 2369 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2370 if (!ChildOrErr) { 2371 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2372 report_error(a->getFileName(), C, std::move(E)); 2373 continue; 2374 } 2375 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 2376 DumpObject(o, a, &C); 2377 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get())) 2378 DumpObject(I, a, &C); 2379 else 2380 report_error(a->getFileName(), object_error::invalid_file_type); 2381 } 2382 if (Err) 2383 report_error(a->getFileName(), std::move(Err)); 2384 } 2385 2386 /// Open file and figure out how to dump it. 2387 static void DumpInput(StringRef file) { 2388 2389 // If we are using the Mach-O specific object file parser, then let it parse 2390 // the file and process the command line options. So the -arch flags can 2391 // be used to select specific slices, etc. 2392 if (MachOOpt) { 2393 ParseInputMachO(file); 2394 return; 2395 } 2396 2397 // Attempt to open the binary. 2398 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file); 2399 if (!BinaryOrErr) 2400 report_error(file, BinaryOrErr.takeError()); 2401 Binary &Binary = *BinaryOrErr.get().getBinary(); 2402 2403 if (Archive *a = dyn_cast<Archive>(&Binary)) 2404 DumpArchive(a); 2405 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary)) 2406 DumpObject(o); 2407 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary)) 2408 ParseInputMachO(UB); 2409 else 2410 report_error(file, object_error::invalid_file_type); 2411 } 2412 2413 int main(int argc, char **argv) { 2414 InitLLVM X(argc, argv); 2415 2416 // Initialize targets and assembly printers/parsers. 2417 llvm::InitializeAllTargetInfos(); 2418 llvm::InitializeAllTargetMCs(); 2419 llvm::InitializeAllDisassemblers(); 2420 2421 // Register the target printer for --version. 2422 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 2423 2424 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 2425 2426 ToolName = argv[0]; 2427 2428 // Defaults to a.out if no filenames specified. 2429 if (InputFilenames.size() == 0) 2430 InputFilenames.push_back("a.out"); 2431 2432 if (AllHeaders) 2433 PrivateHeaders = Relocations = SectionHeaders = SymbolTable = true; 2434 2435 if (DisassembleAll || PrintSource || PrintLines) 2436 Disassemble = true; 2437 2438 if (!Disassemble 2439 && !Relocations 2440 && !DynamicRelocations 2441 && !SectionHeaders 2442 && !SectionContents 2443 && !SymbolTable 2444 && !UnwindInfo 2445 && !PrivateHeaders 2446 && !FileHeaders 2447 && !FirstPrivateHeader 2448 && !ExportsTrie 2449 && !Rebase 2450 && !Bind 2451 && !LazyBind 2452 && !WeakBind 2453 && !RawClangAST 2454 && !(UniversalHeaders && MachOOpt) 2455 && !ArchiveHeaders 2456 && !(IndirectSymbols && MachOOpt) 2457 && !(DataInCode && MachOOpt) 2458 && !(LinkOptHints && MachOOpt) 2459 && !(InfoPlist && MachOOpt) 2460 && !(DylibsUsed && MachOOpt) 2461 && !(DylibId && MachOOpt) 2462 && !(ObjcMetaData && MachOOpt) 2463 && !(FilterSections.size() != 0 && MachOOpt) 2464 && !PrintFaultMaps 2465 && DwarfDumpType == DIDT_Null) { 2466 cl::PrintHelpMessage(); 2467 return 2; 2468 } 2469 2470 DisasmFuncsSet.insert(DisassembleFunctions.begin(), 2471 DisassembleFunctions.end()); 2472 2473 llvm::for_each(InputFilenames, DumpInput); 2474 2475 return EXIT_SUCCESS; 2476 } 2477