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