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