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