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