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