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