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