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