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