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