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