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