1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This program is a utility that works like binutils "objdump", that is, it 10 // dumps out a plethora of information about an object file depending on the 11 // flags. 12 // 13 // The flags and output of this program should be near identical to those of 14 // binutils objdump. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm-objdump.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/ADT/StringSet.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/Demangle/Demangle.h" 28 #include "llvm/MC/MCAsmInfo.h" 29 #include "llvm/MC/MCContext.h" 30 #include "llvm/MC/MCDisassembler/MCDisassembler.h" 31 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h" 32 #include "llvm/MC/MCInst.h" 33 #include "llvm/MC/MCInstPrinter.h" 34 #include "llvm/MC/MCInstrAnalysis.h" 35 #include "llvm/MC/MCInstrInfo.h" 36 #include "llvm/MC/MCObjectFileInfo.h" 37 #include "llvm/MC/MCRegisterInfo.h" 38 #include "llvm/MC/MCSubtargetInfo.h" 39 #include "llvm/Object/Archive.h" 40 #include "llvm/Object/COFF.h" 41 #include "llvm/Object/COFFImportFile.h" 42 #include "llvm/Object/ELFObjectFile.h" 43 #include "llvm/Object/MachO.h" 44 #include "llvm/Object/MachOUniversal.h" 45 #include "llvm/Object/ObjectFile.h" 46 #include "llvm/Object/Wasm.h" 47 #include "llvm/Support/Casting.h" 48 #include "llvm/Support/CommandLine.h" 49 #include "llvm/Support/Debug.h" 50 #include "llvm/Support/Errc.h" 51 #include "llvm/Support/FileSystem.h" 52 #include "llvm/Support/Format.h" 53 #include "llvm/Support/GraphWriter.h" 54 #include "llvm/Support/Host.h" 55 #include "llvm/Support/InitLLVM.h" 56 #include "llvm/Support/MemoryBuffer.h" 57 #include "llvm/Support/SourceMgr.h" 58 #include "llvm/Support/StringSaver.h" 59 #include "llvm/Support/TargetRegistry.h" 60 #include "llvm/Support/TargetSelect.h" 61 #include "llvm/Support/WithColor.h" 62 #include "llvm/Support/raw_ostream.h" 63 #include <algorithm> 64 #include <cctype> 65 #include <cstring> 66 #include <system_error> 67 #include <unordered_map> 68 #include <utility> 69 70 using namespace llvm; 71 using namespace object; 72 73 cl::opt<bool> 74 llvm::AllHeaders("all-headers", 75 cl::desc("Display all available header information")); 76 static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"), 77 cl::NotHidden, cl::aliasopt(AllHeaders)); 78 79 static cl::list<std::string> 80 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore); 81 82 cl::opt<bool> 83 llvm::Disassemble("disassemble", 84 cl::desc("Display assembler mnemonics for the machine instructions")); 85 static cl::alias Disassembled("d", cl::desc("Alias for --disassemble"), 86 cl::NotHidden, cl::aliasopt(Disassemble)); 87 88 cl::opt<bool> 89 llvm::DisassembleAll("disassemble-all", 90 cl::desc("Display assembler mnemonics for the machine instructions")); 91 static cl::alias DisassembleAlld("D", cl::desc("Alias for --disassemble-all"), 92 cl::NotHidden, cl::aliasopt(DisassembleAll)); 93 94 cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"), 95 cl::init(false)); 96 97 static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"), 98 cl::NotHidden, cl::aliasopt(llvm::Demangle)); 99 100 static cl::list<std::string> 101 DisassembleFunctions("df", 102 cl::CommaSeparated, 103 cl::desc("List of functions to disassemble")); 104 static StringSet<> DisasmFuncsSet; 105 106 cl::opt<bool> 107 llvm::Relocations("reloc", 108 cl::desc("Display the relocation entries in the file")); 109 static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"), 110 cl::NotHidden, 111 cl::aliasopt(llvm::Relocations)); 112 113 cl::opt<bool> 114 llvm::DynamicRelocations("dynamic-reloc", 115 cl::desc("Display the dynamic relocation entries in the file")); 116 static cl::alias DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"), 117 cl::NotHidden, 118 cl::aliasopt(DynamicRelocations)); 119 120 cl::opt<bool> 121 llvm::SectionContents("full-contents", 122 cl::desc("Display the content of each section")); 123 static cl::alias SectionContentsShort("s", 124 cl::desc("Alias for --full-contents"), 125 cl::NotHidden, 126 cl::aliasopt(SectionContents)); 127 128 cl::opt<bool> llvm::SymbolTable("syms", cl::desc("Display the symbol table")); 129 static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"), 130 cl::NotHidden, 131 cl::aliasopt(llvm::SymbolTable)); 132 133 cl::opt<bool> 134 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols")); 135 136 cl::opt<bool> 137 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info")); 138 139 cl::opt<bool> 140 llvm::Bind("bind", cl::desc("Display mach-o binding info")); 141 142 cl::opt<bool> 143 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info")); 144 145 cl::opt<bool> 146 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info")); 147 148 cl::opt<bool> 149 llvm::RawClangAST("raw-clang-ast", 150 cl::desc("Dump the raw binary contents of the clang AST section")); 151 152 static cl::opt<bool> 153 MachOOpt("macho", cl::desc("Use MachO specific object file parser")); 154 static cl::alias MachOm("m", cl::desc("Alias for --macho"), cl::NotHidden, 155 cl::aliasopt(MachOOpt)); 156 157 cl::opt<std::string> 158 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, " 159 "see -version for available targets")); 160 161 cl::opt<std::string> 162 llvm::MCPU("mcpu", 163 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 164 cl::value_desc("cpu-name"), 165 cl::init("")); 166 167 cl::opt<std::string> 168 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, " 169 "see -version for available targets")); 170 171 cl::opt<bool> 172 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the " 173 "headers for each section.")); 174 static cl::alias SectionHeadersShort("headers", 175 cl::desc("Alias for --section-headers"), 176 cl::NotHidden, 177 cl::aliasopt(SectionHeaders)); 178 static cl::alias SectionHeadersShorter("h", 179 cl::desc("Alias for --section-headers"), 180 cl::NotHidden, 181 cl::aliasopt(SectionHeaders)); 182 183 cl::list<std::string> 184 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. " 185 "With -macho dump segment,section")); 186 cl::alias static FilterSectionsj("j", cl::desc("Alias for --section"), 187 cl::NotHidden, 188 cl::aliasopt(llvm::FilterSections)); 189 190 cl::list<std::string> 191 llvm::MAttrs("mattr", 192 cl::CommaSeparated, 193 cl::desc("Target specific attributes"), 194 cl::value_desc("a1,+a2,-a3,...")); 195 196 cl::opt<bool> 197 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling " 198 "instructions, do not print " 199 "the instruction bytes.")); 200 cl::opt<bool> 201 llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address")); 202 203 cl::opt<bool> 204 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information")); 205 206 static cl::alias UnwindInfoShort("u", cl::desc("Alias for --unwind-info"), 207 cl::NotHidden, cl::aliasopt(UnwindInfo)); 208 209 cl::opt<bool> 210 llvm::PrivateHeaders("private-headers", 211 cl::desc("Display format specific file headers")); 212 213 cl::opt<bool> 214 llvm::FirstPrivateHeader("private-header", 215 cl::desc("Display only the first format specific file " 216 "header")); 217 218 static cl::alias PrivateHeadersShort("p", 219 cl::desc("Alias for --private-headers"), 220 cl::NotHidden, 221 cl::aliasopt(PrivateHeaders)); 222 223 cl::opt<bool> llvm::FileHeaders( 224 "file-headers", 225 cl::desc("Display the contents of the overall file header")); 226 227 static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"), 228 cl::NotHidden, cl::aliasopt(FileHeaders)); 229 230 cl::opt<bool> 231 llvm::ArchiveHeaders("archive-headers", 232 cl::desc("Display archive header information")); 233 234 cl::alias ArchiveHeadersShort("a", cl::desc("Alias for --archive-headers"), 235 cl::NotHidden, cl::aliasopt(ArchiveHeaders)); 236 237 cl::opt<bool> 238 llvm::PrintImmHex("print-imm-hex", 239 cl::desc("Use hex format for immediate values")); 240 241 cl::opt<bool> PrintFaultMaps("fault-map-section", 242 cl::desc("Display contents of faultmap section")); 243 244 cl::opt<DIDumpType> llvm::DwarfDumpType( 245 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"), 246 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame"))); 247 248 cl::opt<bool> PrintSource( 249 "source", 250 cl::desc( 251 "Display source inlined with disassembly. Implies disassemble object")); 252 253 cl::alias PrintSourceShort("S", cl::desc("Alias for -source"), cl::NotHidden, 254 cl::aliasopt(PrintSource)); 255 256 cl::opt<bool> PrintLines("line-numbers", 257 cl::desc("Display source line numbers with " 258 "disassembly. Implies disassemble object")); 259 260 cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"), 261 cl::NotHidden, cl::aliasopt(PrintLines)); 262 263 cl::opt<unsigned long long> 264 StartAddress("start-address", cl::desc("Disassemble beginning at address"), 265 cl::value_desc("address"), cl::init(0)); 266 cl::opt<unsigned long long> 267 StopAddress("stop-address", 268 cl::desc("Stop disassembly at address"), 269 cl::value_desc("address"), cl::init(UINT64_MAX)); 270 271 cl::opt<bool> DisassembleZeroes( 272 "disassemble-zeroes", 273 cl::desc("Do not skip blocks of zeroes when disassembling")); 274 cl::alias DisassembleZeroesShort("z", 275 cl::desc("Alias for --disassemble-zeroes"), 276 cl::NotHidden, 277 cl::aliasopt(DisassembleZeroes)); 278 279 static StringRef ToolName; 280 281 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy; 282 283 SectionFilter llvm::ToolSectionFilter(llvm::object::ObjectFile const &O) { 284 return SectionFilter( 285 [](llvm::object::SectionRef const &S) { 286 if (FilterSections.empty()) 287 return true; 288 llvm::StringRef String; 289 std::error_code error = S.getName(String); 290 if (error) 291 return false; 292 return is_contained(FilterSections, String); 293 }, 294 O); 295 } 296 297 void llvm::error(std::error_code EC) { 298 if (!EC) 299 return; 300 WithColor::error(errs(), ToolName) 301 << "reading file: " << EC.message() << ".\n"; 302 errs().flush(); 303 exit(1); 304 } 305 306 LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) { 307 WithColor::error(errs(), ToolName) << Message << ".\n"; 308 errs().flush(); 309 exit(1); 310 } 311 312 void llvm::warn(StringRef Message) { 313 WithColor::warning(errs(), ToolName) << Message << ".\n"; 314 errs().flush(); 315 } 316 317 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File, 318 Twine Message) { 319 WithColor::error(errs(), ToolName) 320 << "'" << File << "': " << Message << ".\n"; 321 exit(1); 322 } 323 324 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File, 325 std::error_code EC) { 326 assert(EC); 327 WithColor::error(errs(), ToolName) 328 << "'" << File << "': " << EC.message() << ".\n"; 329 exit(1); 330 } 331 332 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File, 333 llvm::Error E) { 334 assert(E); 335 std::string Buf; 336 raw_string_ostream OS(Buf); 337 logAllUnhandledErrors(std::move(E), OS); 338 OS.flush(); 339 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf; 340 exit(1); 341 } 342 343 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName, 344 StringRef FileName, 345 llvm::Error E, 346 StringRef ArchitectureName) { 347 assert(E); 348 WithColor::error(errs(), ToolName); 349 if (ArchiveName != "") 350 errs() << ArchiveName << "(" << FileName << ")"; 351 else 352 errs() << "'" << FileName << "'"; 353 if (!ArchitectureName.empty()) 354 errs() << " (for architecture " << ArchitectureName << ")"; 355 std::string Buf; 356 raw_string_ostream OS(Buf); 357 logAllUnhandledErrors(std::move(E), OS); 358 OS.flush(); 359 errs() << ": " << Buf; 360 exit(1); 361 } 362 363 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName, 364 const object::Archive::Child &C, 365 llvm::Error E, 366 StringRef ArchitectureName) { 367 Expected<StringRef> NameOrErr = C.getName(); 368 // TODO: if we have a error getting the name then it would be nice to print 369 // the index of which archive member this is and or its offset in the 370 // archive instead of "???" as the name. 371 if (!NameOrErr) { 372 consumeError(NameOrErr.takeError()); 373 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName); 374 } else 375 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E), 376 ArchitectureName); 377 } 378 379 static const Target *getTarget(const ObjectFile *Obj = nullptr) { 380 // Figure out the target triple. 381 llvm::Triple TheTriple("unknown-unknown-unknown"); 382 if (TripleName.empty()) { 383 if (Obj) 384 TheTriple = Obj->makeTriple(); 385 } else { 386 TheTriple.setTriple(Triple::normalize(TripleName)); 387 388 // Use the triple, but also try to combine with ARM build attributes. 389 if (Obj) { 390 auto Arch = Obj->getArch(); 391 if (Arch == Triple::arm || Arch == Triple::armeb) 392 Obj->setARMSubArch(TheTriple); 393 } 394 } 395 396 // Get the target specific parser. 397 std::string Error; 398 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, 399 Error); 400 if (!TheTarget) { 401 if (Obj) 402 report_error(Obj->getFileName(), "can't find target: " + Error); 403 else 404 error("can't find target: " + Error); 405 } 406 407 // Update the triple name and return the found target. 408 TripleName = TheTriple.getTriple(); 409 return TheTarget; 410 } 411 412 bool llvm::isRelocAddressLess(RelocationRef A, RelocationRef B) { 413 return A.getOffset() < B.getOffset(); 414 } 415 416 static std::error_code getRelocationValueString(const RelocationRef &Rel, 417 SmallVectorImpl<char> &Result) { 418 const ObjectFile *Obj = Rel.getObject(); 419 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj)) 420 return getELFRelocationValueString(ELF, Rel, Result); 421 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj)) 422 return getCOFFRelocationValueString(COFF, Rel, Result); 423 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj)) 424 return getWasmRelocationValueString(Wasm, Rel, Result); 425 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj)) 426 return getMachORelocationValueString(MachO, Rel, Result); 427 llvm_unreachable("unknown object file format"); 428 } 429 430 /// Indicates whether this relocation should hidden when listing 431 /// relocations, usually because it is the trailing part of a multipart 432 /// relocation that will be printed as part of the leading relocation. 433 static bool getHidden(RelocationRef RelRef) { 434 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject()); 435 if (!MachO) 436 return false; 437 438 unsigned Arch = MachO->getArch(); 439 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 440 uint64_t Type = MachO->getRelocationType(Rel); 441 442 // On arches that use the generic relocations, GENERIC_RELOC_PAIR 443 // is always hidden. 444 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) 445 return Type == MachO::GENERIC_RELOC_PAIR; 446 447 if (Arch == Triple::x86_64) { 448 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows 449 // an X86_64_RELOC_SUBTRACTOR. 450 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) { 451 DataRefImpl RelPrev = Rel; 452 RelPrev.d.a--; 453 uint64_t PrevType = MachO->getRelocationType(RelPrev); 454 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR) 455 return true; 456 } 457 } 458 459 return false; 460 } 461 462 namespace { 463 class SourcePrinter { 464 protected: 465 DILineInfo OldLineInfo; 466 const ObjectFile *Obj = nullptr; 467 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer; 468 // File name to file contents of source 469 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache; 470 // Mark the line endings of the cached source 471 std::unordered_map<std::string, std::vector<StringRef>> LineCache; 472 473 private: 474 bool cacheSource(const DILineInfo& LineInfoFile); 475 476 public: 477 SourcePrinter() = default; 478 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) { 479 symbolize::LLVMSymbolizer::Options SymbolizerOpts( 480 DILineInfoSpecifier::FunctionNameKind::None, true, false, false, 481 DefaultArch); 482 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts)); 483 } 484 virtual ~SourcePrinter() = default; 485 virtual void printSourceLine(raw_ostream &OS, uint64_t Address, 486 StringRef Delimiter = "; "); 487 }; 488 489 bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) { 490 std::unique_ptr<MemoryBuffer> Buffer; 491 if (LineInfo.Source) { 492 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source); 493 } else { 494 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName); 495 if (!BufferOrError) 496 return false; 497 Buffer = std::move(*BufferOrError); 498 } 499 // Chomp the file to get lines 500 size_t BufferSize = Buffer->getBufferSize(); 501 const char *BufferStart = Buffer->getBufferStart(); 502 for (const char *Start = BufferStart, *End = BufferStart; 503 End < BufferStart + BufferSize; End++) 504 if (*End == '\n' || End == BufferStart + BufferSize - 1 || 505 (*End == '\r' && *(End + 1) == '\n')) { 506 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start)); 507 if (*End == '\r') 508 End++; 509 Start = End + 1; 510 } 511 SourceCache[LineInfo.FileName] = std::move(Buffer); 512 return true; 513 } 514 515 void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address, 516 StringRef Delimiter) { 517 if (!Symbolizer) 518 return; 519 DILineInfo LineInfo = DILineInfo(); 520 auto ExpectecLineInfo = 521 Symbolizer->symbolizeCode(Obj->getFileName(), Address); 522 if (!ExpectecLineInfo) 523 consumeError(ExpectecLineInfo.takeError()); 524 else 525 LineInfo = *ExpectecLineInfo; 526 527 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line || 528 LineInfo.Line == 0) 529 return; 530 531 if (PrintLines) 532 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n"; 533 if (PrintSource) { 534 if (SourceCache.find(LineInfo.FileName) == SourceCache.end()) 535 if (!cacheSource(LineInfo)) 536 return; 537 auto FileBuffer = SourceCache.find(LineInfo.FileName); 538 if (FileBuffer != SourceCache.end()) { 539 auto LineBuffer = LineCache.find(LineInfo.FileName); 540 if (LineBuffer != LineCache.end()) { 541 if (LineInfo.Line > LineBuffer->second.size()) 542 return; 543 // Vector begins at 0, line numbers are non-zero 544 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim() 545 << "\n"; 546 } 547 } 548 } 549 OldLineInfo = LineInfo; 550 } 551 552 static bool isArmElf(const ObjectFile *Obj) { 553 return (Obj->isELF() && 554 (Obj->getArch() == Triple::aarch64 || 555 Obj->getArch() == Triple::aarch64_be || 556 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb || 557 Obj->getArch() == Triple::thumb || 558 Obj->getArch() == Triple::thumbeb)); 559 } 560 561 static void printRelocation(const RelocationRef &Rel, uint64_t Address, 562 uint8_t AddrSize) { 563 StringRef Fmt = 564 AddrSize > 4 ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": "; 565 SmallString<16> Name; 566 SmallString<32> Val; 567 Rel.getTypeName(Name); 568 error(getRelocationValueString(Rel, Val)); 569 outs() << format(Fmt.data(), Address) << Name << "\t" << Val << "\n"; 570 } 571 572 class PrettyPrinter { 573 public: 574 virtual ~PrettyPrinter() = default; 575 virtual void printInst(MCInstPrinter &IP, const MCInst *MI, 576 ArrayRef<uint8_t> Bytes, uint64_t Address, 577 raw_ostream &OS, StringRef Annot, 578 MCSubtargetInfo const &STI, SourcePrinter *SP, 579 std::vector<RelocationRef> *Rels = nullptr) { 580 if (SP && (PrintSource || PrintLines)) 581 SP->printSourceLine(OS, Address); 582 if (!NoLeadingAddr) 583 OS << format("%8" PRIx64 ":", Address); 584 if (!NoShowRawInsn) { 585 OS << "\t"; 586 dumpBytes(Bytes, OS); 587 } 588 if (MI) 589 IP.printInst(MI, OS, "", STI); 590 else 591 OS << " <unknown>"; 592 } 593 }; 594 PrettyPrinter PrettyPrinterInst; 595 class HexagonPrettyPrinter : public PrettyPrinter { 596 public: 597 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address, 598 raw_ostream &OS) { 599 uint32_t opcode = 600 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0]; 601 if (!NoLeadingAddr) 602 OS << format("%8" PRIx64 ":", Address); 603 if (!NoShowRawInsn) { 604 OS << "\t"; 605 dumpBytes(Bytes.slice(0, 4), OS); 606 OS << format("%08" PRIx32, opcode); 607 } 608 } 609 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 610 uint64_t Address, raw_ostream &OS, StringRef Annot, 611 MCSubtargetInfo const &STI, SourcePrinter *SP, 612 std::vector<RelocationRef> *Rels) override { 613 if (SP && (PrintSource || PrintLines)) 614 SP->printSourceLine(OS, Address, ""); 615 if (!MI) { 616 printLead(Bytes, Address, OS); 617 OS << " <unknown>"; 618 return; 619 } 620 std::string Buffer; 621 { 622 raw_string_ostream TempStream(Buffer); 623 IP.printInst(MI, TempStream, "", STI); 624 } 625 StringRef Contents(Buffer); 626 // Split off bundle attributes 627 auto PacketBundle = Contents.rsplit('\n'); 628 // Split off first instruction from the rest 629 auto HeadTail = PacketBundle.first.split('\n'); 630 auto Preamble = " { "; 631 auto Separator = ""; 632 633 // Hexagon's packets require relocations to be inline rather than 634 // clustered at the end of the packet. 635 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin(); 636 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end(); 637 auto PrintReloc = [&]() -> void { 638 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address)) { 639 if (RelCur->getOffset() == Address) { 640 printRelocation(*RelCur, Address, 4); 641 return; 642 } 643 ++RelCur; 644 } 645 }; 646 647 while (!HeadTail.first.empty()) { 648 OS << Separator; 649 Separator = "\n"; 650 if (SP && (PrintSource || PrintLines)) 651 SP->printSourceLine(OS, Address, ""); 652 printLead(Bytes, Address, OS); 653 OS << Preamble; 654 Preamble = " "; 655 StringRef Inst; 656 auto Duplex = HeadTail.first.split('\v'); 657 if (!Duplex.second.empty()) { 658 OS << Duplex.first; 659 OS << "; "; 660 Inst = Duplex.second; 661 } 662 else 663 Inst = HeadTail.first; 664 OS << Inst; 665 HeadTail = HeadTail.second.split('\n'); 666 if (HeadTail.first.empty()) 667 OS << " } " << PacketBundle.second; 668 PrintReloc(); 669 Bytes = Bytes.slice(4); 670 Address += 4; 671 } 672 } 673 }; 674 HexagonPrettyPrinter HexagonPrettyPrinterInst; 675 676 class AMDGCNPrettyPrinter : public PrettyPrinter { 677 public: 678 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 679 uint64_t Address, raw_ostream &OS, StringRef Annot, 680 MCSubtargetInfo const &STI, SourcePrinter *SP, 681 std::vector<RelocationRef> *Rels) override { 682 if (SP && (PrintSource || PrintLines)) 683 SP->printSourceLine(OS, Address); 684 685 typedef support::ulittle32_t U32; 686 687 if (MI) { 688 SmallString<40> InstStr; 689 raw_svector_ostream IS(InstStr); 690 691 IP.printInst(MI, IS, "", STI); 692 693 OS << left_justify(IS.str(), 60); 694 } else { 695 // an unrecognized encoding - this is probably data so represent it 696 // using the .long directive, or .byte directive if fewer than 4 bytes 697 // remaining 698 if (Bytes.size() >= 4) { 699 OS << format("\t.long 0x%08" PRIx32 " ", 700 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data()))); 701 OS.indent(42); 702 } else { 703 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]); 704 for (unsigned int i = 1; i < Bytes.size(); i++) 705 OS << format(", 0x%02" PRIx8, Bytes[i]); 706 OS.indent(55 - (6 * Bytes.size())); 707 } 708 } 709 710 OS << format("// %012" PRIX64 ": ", Address); 711 if (Bytes.size() >=4) { 712 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()), 713 Bytes.size() / sizeof(U32))) 714 // D should be explicitly casted to uint32_t here as it is passed 715 // by format to snprintf as vararg. 716 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D)); 717 } else { 718 for (unsigned int i = 0; i < Bytes.size(); i++) 719 OS << format("%02" PRIX8 " ", Bytes[i]); 720 } 721 722 if (!Annot.empty()) 723 OS << "// " << Annot; 724 } 725 }; 726 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst; 727 728 class BPFPrettyPrinter : public PrettyPrinter { 729 public: 730 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 731 uint64_t Address, raw_ostream &OS, StringRef Annot, 732 MCSubtargetInfo const &STI, SourcePrinter *SP, 733 std::vector<RelocationRef> *Rels) override { 734 if (SP && (PrintSource || PrintLines)) 735 SP->printSourceLine(OS, Address); 736 if (!NoLeadingAddr) 737 OS << format("%8" PRId64 ":", Address / 8); 738 if (!NoShowRawInsn) { 739 OS << "\t"; 740 dumpBytes(Bytes, OS); 741 } 742 if (MI) 743 IP.printInst(MI, OS, "", STI); 744 else 745 OS << " <unknown>"; 746 } 747 }; 748 BPFPrettyPrinter BPFPrettyPrinterInst; 749 750 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) { 751 switch(Triple.getArch()) { 752 default: 753 return PrettyPrinterInst; 754 case Triple::hexagon: 755 return HexagonPrettyPrinterInst; 756 case Triple::amdgcn: 757 return AMDGCNPrettyPrinterInst; 758 case Triple::bpfel: 759 case Triple::bpfeb: 760 return BPFPrettyPrinterInst; 761 } 762 } 763 } 764 765 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) { 766 assert(Obj->isELF()); 767 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj)) 768 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 769 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj)) 770 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 771 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj)) 772 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 773 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj)) 774 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 775 llvm_unreachable("Unsupported binary format"); 776 } 777 778 template <class ELFT> static void 779 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj, 780 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { 781 for (auto Symbol : Obj->getDynamicSymbolIterators()) { 782 uint8_t SymbolType = Symbol.getELFType(); 783 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0) 784 continue; 785 786 Expected<uint64_t> AddressOrErr = Symbol.getAddress(); 787 if (!AddressOrErr) 788 report_error(Obj->getFileName(), AddressOrErr.takeError()); 789 790 Expected<StringRef> Name = Symbol.getName(); 791 if (!Name) 792 report_error(Obj->getFileName(), Name.takeError()); 793 if (Name->empty()) 794 continue; 795 796 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 797 if (!SectionOrErr) 798 report_error(Obj->getFileName(), SectionOrErr.takeError()); 799 section_iterator SecI = *SectionOrErr; 800 if (SecI == Obj->section_end()) 801 continue; 802 803 AllSymbols[*SecI].emplace_back(*AddressOrErr, *Name, SymbolType); 804 } 805 } 806 807 static void 808 addDynamicElfSymbols(const ObjectFile *Obj, 809 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { 810 assert(Obj->isELF()); 811 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj)) 812 addDynamicElfSymbols(Elf32LEObj, AllSymbols); 813 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj)) 814 addDynamicElfSymbols(Elf64LEObj, AllSymbols); 815 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj)) 816 addDynamicElfSymbols(Elf32BEObj, AllSymbols); 817 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj)) 818 addDynamicElfSymbols(Elf64BEObj, AllSymbols); 819 else 820 llvm_unreachable("Unsupported binary format"); 821 } 822 823 static void addPltEntries(const ObjectFile *Obj, 824 std::map<SectionRef, SectionSymbolsTy> &AllSymbols, 825 StringSaver &Saver) { 826 Optional<SectionRef> Plt = None; 827 for (const SectionRef &Section : Obj->sections()) { 828 StringRef Name; 829 if (Section.getName(Name)) 830 continue; 831 if (Name == ".plt") 832 Plt = Section; 833 } 834 if (!Plt) 835 return; 836 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) { 837 for (auto PltEntry : ElfObj->getPltAddresses()) { 838 SymbolRef Symbol(PltEntry.first, ElfObj); 839 uint8_t SymbolType = getElfSymbolType(Obj, Symbol); 840 841 Expected<StringRef> NameOrErr = Symbol.getName(); 842 if (!NameOrErr) 843 report_error(Obj->getFileName(), NameOrErr.takeError()); 844 if (NameOrErr->empty()) 845 continue; 846 StringRef Name = Saver.save((*NameOrErr + "@plt").str()); 847 848 AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType); 849 } 850 } 851 } 852 853 // Normally the disassembly output will skip blocks of zeroes. This function 854 // returns the number of zero bytes that can be skipped when dumping the 855 // disassembly of the instructions in Buf. 856 static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) { 857 // When -z or --disassemble-zeroes are given we always dissasemble them. 858 if (DisassembleZeroes) 859 return 0; 860 861 // Find the number of leading zeroes. 862 size_t N = 0; 863 while (N < Buf.size() && !Buf[N]) 864 ++N; 865 866 // We may want to skip blocks of zero bytes, but unless we see 867 // at least 8 of them in a row. 868 if (N < 8) 869 return 0; 870 871 // We skip zeroes in multiples of 4 because do not want to truncate an 872 // instruction if it starts with a zero byte. 873 return N & ~0x3; 874 } 875 876 // Returns a map from sections to their relocations. 877 static std::map<SectionRef, std::vector<RelocationRef>> 878 getRelocsMap(llvm::object::ObjectFile const &Obj) { 879 std::map<SectionRef, std::vector<RelocationRef>> Ret; 880 for (const SectionRef &Section : ToolSectionFilter(Obj)) { 881 section_iterator RelSec = Section.getRelocatedSection(); 882 if (RelSec == Obj.section_end()) 883 continue; 884 std::vector<RelocationRef> &V = Ret[*RelSec]; 885 for (const RelocationRef &R : Section.relocations()) 886 V.push_back(R); 887 // Sort relocations by address. 888 llvm::sort(V, isRelocAddressLess); 889 } 890 return Ret; 891 } 892 893 static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj, 894 MCContext &Ctx, MCDisassembler *DisAsm, 895 const MCInstrAnalysis *MIA, MCInstPrinter *IP, 896 const MCSubtargetInfo *STI, PrettyPrinter &PIP, 897 SourcePrinter &SP, bool InlineRelocs) { 898 std::map<SectionRef, std::vector<RelocationRef>> RelocMap; 899 if (InlineRelocs) 900 RelocMap = getRelocsMap(*Obj); 901 902 // Create a mapping from virtual address to symbol name. This is used to 903 // pretty print the symbols while disassembling. 904 std::map<SectionRef, SectionSymbolsTy> AllSymbols; 905 SectionSymbolsTy AbsoluteSymbols; 906 for (const SymbolRef &Symbol : Obj->symbols()) { 907 Expected<uint64_t> AddressOrErr = Symbol.getAddress(); 908 if (!AddressOrErr) 909 report_error(Obj->getFileName(), AddressOrErr.takeError()); 910 uint64_t Address = *AddressOrErr; 911 912 Expected<StringRef> Name = Symbol.getName(); 913 if (!Name) 914 report_error(Obj->getFileName(), Name.takeError()); 915 if (Name->empty()) 916 continue; 917 918 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 919 if (!SectionOrErr) 920 report_error(Obj->getFileName(), SectionOrErr.takeError()); 921 922 uint8_t SymbolType = ELF::STT_NOTYPE; 923 if (Obj->isELF()) 924 SymbolType = getElfSymbolType(Obj, Symbol); 925 926 section_iterator SecI = *SectionOrErr; 927 if (SecI != Obj->section_end()) 928 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType); 929 else 930 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType); 931 932 933 } 934 if (AllSymbols.empty() && Obj->isELF()) 935 addDynamicElfSymbols(Obj, AllSymbols); 936 937 BumpPtrAllocator A; 938 StringSaver Saver(A); 939 addPltEntries(Obj, AllSymbols, Saver); 940 941 // Create a mapping from virtual address to section. 942 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses; 943 for (SectionRef Sec : Obj->sections()) 944 SectionAddresses.emplace_back(Sec.getAddress(), Sec); 945 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end()); 946 947 // Linked executables (.exe and .dll files) typically don't include a real 948 // symbol table but they might contain an export table. 949 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) { 950 for (const auto &ExportEntry : COFFObj->export_directories()) { 951 StringRef Name; 952 error(ExportEntry.getSymbolName(Name)); 953 if (Name.empty()) 954 continue; 955 uint32_t RVA; 956 error(ExportEntry.getExportRVA(RVA)); 957 958 uint64_t VA = COFFObj->getImageBase() + RVA; 959 auto Sec = std::upper_bound( 960 SectionAddresses.begin(), SectionAddresses.end(), VA, 961 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) { 962 return LHS < RHS.first; 963 }); 964 if (Sec != SectionAddresses.begin()) 965 --Sec; 966 else 967 Sec = SectionAddresses.end(); 968 969 if (Sec != SectionAddresses.end()) 970 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE); 971 else 972 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE); 973 } 974 } 975 976 // Sort all the symbols, this allows us to use a simple binary search to find 977 // a symbol near an address. 978 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols) 979 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end()); 980 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end()); 981 982 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 983 if (!DisassembleAll && (!Section.isText() || Section.isVirtual())) 984 continue; 985 986 uint64_t SectionAddr = Section.getAddress(); 987 uint64_t SectSize = Section.getSize(); 988 if (!SectSize) 989 continue; 990 991 // Get the list of all the symbols in this section. 992 SectionSymbolsTy &Symbols = AllSymbols[Section]; 993 std::vector<uint64_t> DataMappingSymsAddr; 994 std::vector<uint64_t> TextMappingSymsAddr; 995 if (isArmElf(Obj)) { 996 for (const auto &Symb : Symbols) { 997 uint64_t Address = std::get<0>(Symb); 998 StringRef Name = std::get<1>(Symb); 999 if (Name.startswith("$d")) 1000 DataMappingSymsAddr.push_back(Address - SectionAddr); 1001 if (Name.startswith("$x")) 1002 TextMappingSymsAddr.push_back(Address - SectionAddr); 1003 if (Name.startswith("$a")) 1004 TextMappingSymsAddr.push_back(Address - SectionAddr); 1005 if (Name.startswith("$t")) 1006 TextMappingSymsAddr.push_back(Address - SectionAddr); 1007 } 1008 } 1009 1010 llvm::sort(DataMappingSymsAddr); 1011 llvm::sort(TextMappingSymsAddr); 1012 1013 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1014 // AMDGPU disassembler uses symbolizer for printing labels 1015 std::unique_ptr<MCRelocationInfo> RelInfo( 1016 TheTarget->createMCRelocationInfo(TripleName, Ctx)); 1017 if (RelInfo) { 1018 std::unique_ptr<MCSymbolizer> Symbolizer( 1019 TheTarget->createMCSymbolizer( 1020 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo))); 1021 DisAsm->setSymbolizer(std::move(Symbolizer)); 1022 } 1023 } 1024 1025 StringRef SegmentName = ""; 1026 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) { 1027 DataRefImpl DR = Section.getRawDataRefImpl(); 1028 SegmentName = MachO->getSectionFinalSegmentName(DR); 1029 } 1030 StringRef SectionName; 1031 error(Section.getName(SectionName)); 1032 1033 // If the section has no symbol at the start, just insert a dummy one. 1034 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) { 1035 Symbols.insert( 1036 Symbols.begin(), 1037 std::make_tuple(SectionAddr, SectionName, 1038 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT)); 1039 } 1040 1041 SmallString<40> Comments; 1042 raw_svector_ostream CommentStream(Comments); 1043 1044 StringRef BytesStr; 1045 error(Section.getContents(BytesStr)); 1046 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()), 1047 BytesStr.size()); 1048 1049 uint64_t Size; 1050 uint64_t Index; 1051 bool PrintedSection = false; 1052 std::vector<RelocationRef> Rels = RelocMap[Section]; 1053 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin(); 1054 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end(); 1055 // Disassemble symbol by symbol. 1056 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) { 1057 uint64_t Start = std::get<0>(Symbols[SI]) - SectionAddr; 1058 // The end is either the section end or the beginning of the next 1059 // symbol. 1060 uint64_t End = (SI == SE - 1) 1061 ? SectSize 1062 : std::get<0>(Symbols[SI + 1]) - SectionAddr; 1063 // Don't try to disassemble beyond the end of section contents. 1064 if (End > SectSize) 1065 End = SectSize; 1066 // If this symbol has the same address as the next symbol, then skip it. 1067 if (Start >= End) 1068 continue; 1069 1070 // Check if we need to skip symbol 1071 // Skip if the symbol's data is not between StartAddress and StopAddress 1072 if (End + SectionAddr < StartAddress || 1073 Start + SectionAddr > StopAddress) { 1074 continue; 1075 } 1076 1077 /// Skip if user requested specific symbols and this is not in the list 1078 if (!DisasmFuncsSet.empty() && 1079 !DisasmFuncsSet.count(std::get<1>(Symbols[SI]))) 1080 continue; 1081 1082 if (!PrintedSection) { 1083 PrintedSection = true; 1084 outs() << "Disassembly of section "; 1085 if (!SegmentName.empty()) 1086 outs() << SegmentName << ","; 1087 outs() << SectionName << ':'; 1088 } 1089 1090 // Stop disassembly at the stop address specified 1091 if (End + SectionAddr > StopAddress) 1092 End = StopAddress - SectionAddr; 1093 1094 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1095 if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) { 1096 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes) 1097 Start += 256; 1098 } 1099 if (SI == SE - 1 || 1100 std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) { 1101 // cut trailing zeroes at the end of kernel 1102 // cut up to 256 bytes 1103 const uint64_t EndAlign = 256; 1104 const auto Limit = End - (std::min)(EndAlign, End - Start); 1105 while (End > Limit && 1106 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0) 1107 End -= 4; 1108 } 1109 } 1110 1111 outs() << '\n'; 1112 if (!NoLeadingAddr) 1113 outs() << format("%016" PRIx64 " ", SectionAddr + Start); 1114 1115 StringRef SymbolName = std::get<1>(Symbols[SI]); 1116 if (Demangle) 1117 outs() << demangle(SymbolName) << ":\n"; 1118 else 1119 outs() << SymbolName << ":\n"; 1120 1121 // Don't print raw contents of a virtual section. A virtual section 1122 // doesn't have any contents in the file. 1123 if (Section.isVirtual()) { 1124 outs() << "...\n"; 1125 continue; 1126 } 1127 1128 #ifndef NDEBUG 1129 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); 1130 #else 1131 raw_ostream &DebugOut = nulls(); 1132 #endif 1133 1134 // Some targets (like WebAssembly) have a special prelude at the start 1135 // of each symbol. 1136 DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start), 1137 SectionAddr + Start, DebugOut, CommentStream); 1138 Start += Size; 1139 1140 for (Index = Start; Index < End; Index += Size) { 1141 MCInst Inst; 1142 1143 if (Index + SectionAddr < StartAddress || 1144 Index + SectionAddr > StopAddress) { 1145 // skip byte by byte till StartAddress is reached 1146 Size = 1; 1147 continue; 1148 } 1149 // AArch64 ELF binaries can interleave data and text in the 1150 // same section. We rely on the markers introduced to 1151 // understand what we need to dump. If the data marker is within a 1152 // function, it is denoted as a word/short etc 1153 if (isArmElf(Obj) && std::get<2>(Symbols[SI]) != ELF::STT_OBJECT && 1154 !DisassembleAll) { 1155 uint64_t Stride = 0; 1156 1157 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(), 1158 DataMappingSymsAddr.end(), Index); 1159 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) { 1160 // Switch to data. 1161 while (Index < End) { 1162 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 1163 outs() << "\t"; 1164 if (Index + 4 <= End) { 1165 Stride = 4; 1166 dumpBytes(Bytes.slice(Index, 4), outs()); 1167 outs() << "\t.word\t"; 1168 uint32_t Data = 0; 1169 if (Obj->isLittleEndian()) { 1170 const auto Word = 1171 reinterpret_cast<const support::ulittle32_t *>( 1172 Bytes.data() + Index); 1173 Data = *Word; 1174 } else { 1175 const auto Word = reinterpret_cast<const support::ubig32_t *>( 1176 Bytes.data() + Index); 1177 Data = *Word; 1178 } 1179 outs() << "0x" << format("%08" PRIx32, Data); 1180 } else if (Index + 2 <= End) { 1181 Stride = 2; 1182 dumpBytes(Bytes.slice(Index, 2), outs()); 1183 outs() << "\t\t.short\t"; 1184 uint16_t Data = 0; 1185 if (Obj->isLittleEndian()) { 1186 const auto Short = 1187 reinterpret_cast<const support::ulittle16_t *>( 1188 Bytes.data() + Index); 1189 Data = *Short; 1190 } else { 1191 const auto Short = 1192 reinterpret_cast<const support::ubig16_t *>(Bytes.data() + 1193 Index); 1194 Data = *Short; 1195 } 1196 outs() << "0x" << format("%04" PRIx16, Data); 1197 } else { 1198 Stride = 1; 1199 dumpBytes(Bytes.slice(Index, 1), outs()); 1200 outs() << "\t\t.byte\t"; 1201 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]); 1202 } 1203 Index += Stride; 1204 outs() << "\n"; 1205 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(), 1206 TextMappingSymsAddr.end(), Index); 1207 if (TAI != TextMappingSymsAddr.end() && *TAI == Index) 1208 break; 1209 } 1210 } 1211 } 1212 1213 // If there is a data symbol inside an ELF text section and we are only 1214 // disassembling text (applicable all architectures), 1215 // we are in a situation where we must print the data and not 1216 // disassemble it. 1217 if (Obj->isELF() && std::get<2>(Symbols[SI]) == ELF::STT_OBJECT && 1218 !DisassembleAll && Section.isText()) { 1219 // print out data up to 8 bytes at a time in hex and ascii 1220 uint8_t AsciiData[9] = {'\0'}; 1221 uint8_t Byte; 1222 int NumBytes = 0; 1223 1224 for (Index = Start; Index < End; Index += 1) { 1225 if (((SectionAddr + Index) < StartAddress) || 1226 ((SectionAddr + Index) > StopAddress)) 1227 continue; 1228 if (NumBytes == 0) { 1229 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 1230 outs() << "\t"; 1231 } 1232 Byte = Bytes.slice(Index)[0]; 1233 outs() << format(" %02x", Byte); 1234 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.'; 1235 1236 uint8_t IndentOffset = 0; 1237 NumBytes++; 1238 if (Index == End - 1 || NumBytes > 8) { 1239 // Indent the space for less than 8 bytes data. 1240 // 2 spaces for byte and one for space between bytes 1241 IndentOffset = 3 * (8 - NumBytes); 1242 for (int Excess = 8 - NumBytes; Excess < 8; Excess++) 1243 AsciiData[Excess] = '\0'; 1244 NumBytes = 8; 1245 } 1246 if (NumBytes == 8) { 1247 AsciiData[8] = '\0'; 1248 outs() << std::string(IndentOffset, ' ') << " "; 1249 outs() << reinterpret_cast<char *>(AsciiData); 1250 outs() << '\n'; 1251 NumBytes = 0; 1252 } 1253 } 1254 } 1255 if (Index >= End) 1256 break; 1257 1258 if (size_t N = 1259 countSkippableZeroBytes(Bytes.slice(Index, End - Index))) { 1260 outs() << "\t\t..." << '\n'; 1261 Index += N; 1262 if (Index >= End) 1263 break; 1264 } 1265 1266 // Disassemble a real instruction or a data when disassemble all is 1267 // provided 1268 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), 1269 SectionAddr + Index, DebugOut, 1270 CommentStream); 1271 if (Size == 0) 1272 Size = 1; 1273 1274 PIP.printInst(*IP, Disassembled ? &Inst : nullptr, 1275 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "", 1276 *STI, &SP, &Rels); 1277 outs() << CommentStream.str(); 1278 Comments.clear(); 1279 1280 // Try to resolve the target of a call, tail call, etc. to a specific 1281 // symbol. 1282 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) || 1283 MIA->isConditionalBranch(Inst))) { 1284 uint64_t Target; 1285 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) { 1286 // In a relocatable object, the target's section must reside in 1287 // the same section as the call instruction or it is accessed 1288 // through a relocation. 1289 // 1290 // In a non-relocatable object, the target may be in any section. 1291 // 1292 // N.B. We don't walk the relocations in the relocatable case yet. 1293 auto *TargetSectionSymbols = &Symbols; 1294 if (!Obj->isRelocatableObject()) { 1295 auto SectionAddress = std::upper_bound( 1296 SectionAddresses.begin(), SectionAddresses.end(), Target, 1297 [](uint64_t LHS, 1298 const std::pair<uint64_t, SectionRef> &RHS) { 1299 return LHS < RHS.first; 1300 }); 1301 if (SectionAddress != SectionAddresses.begin()) { 1302 --SectionAddress; 1303 TargetSectionSymbols = &AllSymbols[SectionAddress->second]; 1304 } else { 1305 TargetSectionSymbols = &AbsoluteSymbols; 1306 } 1307 } 1308 1309 // Find the first symbol in the section whose offset is less than 1310 // or equal to the target. If there isn't a section that contains 1311 // the target, find the nearest preceding absolute symbol. 1312 auto TargetSym = std::upper_bound( 1313 TargetSectionSymbols->begin(), TargetSectionSymbols->end(), 1314 Target, [](uint64_t LHS, 1315 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) { 1316 return LHS < std::get<0>(RHS); 1317 }); 1318 if (TargetSym == TargetSectionSymbols->begin()) { 1319 TargetSectionSymbols = &AbsoluteSymbols; 1320 TargetSym = std::upper_bound( 1321 AbsoluteSymbols.begin(), AbsoluteSymbols.end(), 1322 Target, [](uint64_t LHS, 1323 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) { 1324 return LHS < std::get<0>(RHS); 1325 }); 1326 } 1327 if (TargetSym != TargetSectionSymbols->begin()) { 1328 --TargetSym; 1329 uint64_t TargetAddress = std::get<0>(*TargetSym); 1330 StringRef TargetName = std::get<1>(*TargetSym); 1331 outs() << " <" << TargetName; 1332 uint64_t Disp = Target - TargetAddress; 1333 if (Disp) 1334 outs() << "+0x" << Twine::utohexstr(Disp); 1335 outs() << '>'; 1336 } 1337 } 1338 } 1339 outs() << "\n"; 1340 1341 // Hexagon does this in pretty printer 1342 if (Obj->getArch() != Triple::hexagon) { 1343 // Print relocation for instruction. 1344 while (RelCur != RelEnd) { 1345 uint64_t Offset = RelCur->getOffset(); 1346 // If this relocation is hidden, skip it. 1347 if (getHidden(*RelCur) || ((SectionAddr + Offset) < StartAddress)) { 1348 ++RelCur; 1349 continue; 1350 } 1351 1352 // Stop when rel_cur's address is past the current instruction. 1353 if (Offset >= Index + Size) 1354 break; 1355 1356 printRelocation(*RelCur, SectionAddr + Offset, 1357 Obj->getBytesInAddress()); 1358 ++RelCur; 1359 } 1360 } 1361 } 1362 } 1363 } 1364 } 1365 1366 static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) { 1367 if (StartAddress > StopAddress) 1368 error("Start address should be less than stop address"); 1369 1370 const Target *TheTarget = getTarget(Obj); 1371 1372 // Package up features to be passed to target/subtarget 1373 SubtargetFeatures Features = Obj->getFeatures(); 1374 if (!MAttrs.empty()) 1375 for (unsigned I = 0; I != MAttrs.size(); ++I) 1376 Features.AddFeature(MAttrs[I]); 1377 1378 std::unique_ptr<const MCRegisterInfo> MRI( 1379 TheTarget->createMCRegInfo(TripleName)); 1380 if (!MRI) 1381 report_error(Obj->getFileName(), 1382 "no register info for target " + TripleName); 1383 1384 // Set up disassembler. 1385 std::unique_ptr<const MCAsmInfo> AsmInfo( 1386 TheTarget->createMCAsmInfo(*MRI, TripleName)); 1387 if (!AsmInfo) 1388 report_error(Obj->getFileName(), 1389 "no assembly info for target " + TripleName); 1390 std::unique_ptr<const MCSubtargetInfo> STI( 1391 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString())); 1392 if (!STI) 1393 report_error(Obj->getFileName(), 1394 "no subtarget info for target " + TripleName); 1395 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); 1396 if (!MII) 1397 report_error(Obj->getFileName(), 1398 "no instruction info for target " + TripleName); 1399 MCObjectFileInfo MOFI; 1400 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI); 1401 // FIXME: for now initialize MCObjectFileInfo with default values 1402 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx); 1403 1404 std::unique_ptr<MCDisassembler> DisAsm( 1405 TheTarget->createMCDisassembler(*STI, Ctx)); 1406 if (!DisAsm) 1407 report_error(Obj->getFileName(), 1408 "no disassembler for target " + TripleName); 1409 1410 std::unique_ptr<const MCInstrAnalysis> MIA( 1411 TheTarget->createMCInstrAnalysis(MII.get())); 1412 1413 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 1414 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 1415 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI)); 1416 if (!IP) 1417 report_error(Obj->getFileName(), 1418 "no instruction printer for target " + TripleName); 1419 IP->setPrintImmHex(PrintImmHex); 1420 1421 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName)); 1422 SourcePrinter SP(Obj, TheTarget->getName()); 1423 1424 disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), MIA.get(), IP.get(), 1425 STI.get(), PIP, SP, InlineRelocs); 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