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