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