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