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