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