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