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