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