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