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 if (SymbolType == ELF::STT_SECTION) 947 continue; 948 } 949 950 section_iterator SecI = *SectionOrErr; 951 if (SecI != Obj->section_end()) 952 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType); 953 else 954 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType); 955 956 957 } 958 if (AllSymbols.empty() && Obj->isELF()) 959 addDynamicElfSymbols(Obj, AllSymbols); 960 961 BumpPtrAllocator A; 962 StringSaver Saver(A); 963 addPltEntries(Obj, AllSymbols, Saver); 964 965 // Create a mapping from virtual address to section. 966 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses; 967 for (SectionRef Sec : Obj->sections()) 968 SectionAddresses.emplace_back(Sec.getAddress(), Sec); 969 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end()); 970 971 // Linked executables (.exe and .dll files) typically don't include a real 972 // symbol table but they might contain an export table. 973 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) { 974 for (const auto &ExportEntry : COFFObj->export_directories()) { 975 StringRef Name; 976 error(ExportEntry.getSymbolName(Name)); 977 if (Name.empty()) 978 continue; 979 uint32_t RVA; 980 error(ExportEntry.getExportRVA(RVA)); 981 982 uint64_t VA = COFFObj->getImageBase() + RVA; 983 auto Sec = std::upper_bound( 984 SectionAddresses.begin(), SectionAddresses.end(), VA, 985 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) { 986 return LHS < RHS.first; 987 }); 988 if (Sec != SectionAddresses.begin()) 989 --Sec; 990 else 991 Sec = SectionAddresses.end(); 992 993 if (Sec != SectionAddresses.end()) 994 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE); 995 else 996 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE); 997 } 998 } 999 1000 // Sort all the symbols, this allows us to use a simple binary search to find 1001 // a symbol near an address. 1002 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols) 1003 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end()); 1004 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end()); 1005 1006 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1007 if (!DisassembleAll && (!Section.isText() || Section.isVirtual())) 1008 continue; 1009 1010 uint64_t SectionAddr = Section.getAddress(); 1011 uint64_t SectSize = Section.getSize(); 1012 if (!SectSize) 1013 continue; 1014 1015 // Get the list of all the symbols in this section. 1016 SectionSymbolsTy &Symbols = AllSymbols[Section]; 1017 std::vector<uint64_t> DataMappingSymsAddr; 1018 std::vector<uint64_t> TextMappingSymsAddr; 1019 if (isArmElf(Obj)) { 1020 for (const auto &Symb : Symbols) { 1021 uint64_t Address = std::get<0>(Symb); 1022 StringRef Name = std::get<1>(Symb); 1023 if (Name.startswith("$d")) 1024 DataMappingSymsAddr.push_back(Address - SectionAddr); 1025 if (Name.startswith("$x")) 1026 TextMappingSymsAddr.push_back(Address - SectionAddr); 1027 if (Name.startswith("$a")) 1028 TextMappingSymsAddr.push_back(Address - SectionAddr); 1029 if (Name.startswith("$t")) 1030 TextMappingSymsAddr.push_back(Address - SectionAddr); 1031 } 1032 } 1033 1034 llvm::sort(DataMappingSymsAddr); 1035 llvm::sort(TextMappingSymsAddr); 1036 1037 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1038 // AMDGPU disassembler uses symbolizer for printing labels 1039 std::unique_ptr<MCRelocationInfo> RelInfo( 1040 TheTarget->createMCRelocationInfo(TripleName, Ctx)); 1041 if (RelInfo) { 1042 std::unique_ptr<MCSymbolizer> Symbolizer( 1043 TheTarget->createMCSymbolizer( 1044 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo))); 1045 DisAsm->setSymbolizer(std::move(Symbolizer)); 1046 } 1047 } 1048 1049 StringRef SegmentName = ""; 1050 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) { 1051 DataRefImpl DR = Section.getRawDataRefImpl(); 1052 SegmentName = MachO->getSectionFinalSegmentName(DR); 1053 } 1054 StringRef SectionName; 1055 error(Section.getName(SectionName)); 1056 1057 // If the section has no symbol at the start, just insert a dummy one. 1058 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) { 1059 Symbols.insert( 1060 Symbols.begin(), 1061 std::make_tuple(SectionAddr, SectionName, 1062 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT)); 1063 } 1064 1065 SmallString<40> Comments; 1066 raw_svector_ostream CommentStream(Comments); 1067 1068 StringRef BytesStr; 1069 error(Section.getContents(BytesStr)); 1070 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()), 1071 BytesStr.size()); 1072 1073 uint64_t VMAAdjustment = 0; 1074 if (shouldAdjustVA(Section)) 1075 VMAAdjustment = AdjustVMA; 1076 1077 uint64_t Size; 1078 uint64_t Index; 1079 bool PrintedSection = false; 1080 std::vector<RelocationRef> Rels = RelocMap[Section]; 1081 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin(); 1082 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end(); 1083 // Disassemble symbol by symbol. 1084 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) { 1085 uint64_t Start = std::get<0>(Symbols[SI]) - SectionAddr; 1086 // The end is either the section end or the beginning of the next 1087 // symbol. 1088 uint64_t End = (SI == SE - 1) 1089 ? SectSize 1090 : std::get<0>(Symbols[SI + 1]) - SectionAddr; 1091 // Don't try to disassemble beyond the end of section contents. 1092 if (End > SectSize) 1093 End = SectSize; 1094 // If this symbol has the same address as the next symbol, then skip it. 1095 if (Start >= End) 1096 continue; 1097 1098 // Check if we need to skip symbol 1099 // Skip if the symbol's data is not between StartAddress and StopAddress 1100 if (End + SectionAddr < StartAddress || 1101 Start + SectionAddr > StopAddress) { 1102 continue; 1103 } 1104 1105 /// Skip if user requested specific symbols and this is not in the list 1106 if (!DisasmFuncsSet.empty() && 1107 !DisasmFuncsSet.count(std::get<1>(Symbols[SI]))) 1108 continue; 1109 1110 if (!PrintedSection) { 1111 PrintedSection = true; 1112 outs() << "Disassembly of section "; 1113 if (!SegmentName.empty()) 1114 outs() << SegmentName << ","; 1115 outs() << SectionName << ':'; 1116 } 1117 1118 // Stop disassembly at the stop address specified 1119 if (End + SectionAddr > StopAddress) 1120 End = StopAddress - SectionAddr; 1121 1122 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1123 if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) { 1124 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes) 1125 Start += 256; 1126 } 1127 if (SI == SE - 1 || 1128 std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) { 1129 // cut trailing zeroes at the end of kernel 1130 // cut up to 256 bytes 1131 const uint64_t EndAlign = 256; 1132 const auto Limit = End - (std::min)(EndAlign, End - Start); 1133 while (End > Limit && 1134 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0) 1135 End -= 4; 1136 } 1137 } 1138 1139 outs() << '\n'; 1140 if (!NoLeadingAddr) 1141 outs() << format("%016" PRIx64 " ", 1142 SectionAddr + Start + VMAAdjustment); 1143 1144 StringRef SymbolName = std::get<1>(Symbols[SI]); 1145 if (Demangle) 1146 outs() << demangle(SymbolName) << ":\n"; 1147 else 1148 outs() << SymbolName << ":\n"; 1149 1150 // Don't print raw contents of a virtual section. A virtual section 1151 // doesn't have any contents in the file. 1152 if (Section.isVirtual()) { 1153 outs() << "...\n"; 1154 continue; 1155 } 1156 1157 #ifndef NDEBUG 1158 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); 1159 #else 1160 raw_ostream &DebugOut = nulls(); 1161 #endif 1162 1163 // Some targets (like WebAssembly) have a special prelude at the start 1164 // of each symbol. 1165 DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start), 1166 SectionAddr + Start, DebugOut, CommentStream); 1167 Start += Size; 1168 1169 for (Index = Start; Index < End; Index += Size) { 1170 MCInst Inst; 1171 1172 if (Index + SectionAddr < StartAddress || 1173 Index + SectionAddr > StopAddress) { 1174 // skip byte by byte till StartAddress is reached 1175 Size = 1; 1176 continue; 1177 } 1178 // AArch64 ELF binaries can interleave data and text in the 1179 // same section. We rely on the markers introduced to 1180 // understand what we need to dump. If the data marker is within a 1181 // function, it is denoted as a word/short etc 1182 if (isArmElf(Obj) && std::get<2>(Symbols[SI]) != ELF::STT_OBJECT && 1183 !DisassembleAll) { 1184 uint64_t Stride = 0; 1185 1186 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(), 1187 DataMappingSymsAddr.end(), Index); 1188 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) { 1189 // Switch to data. 1190 while (Index < End) { 1191 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 1192 outs() << "\t"; 1193 if (Index + 4 <= End) { 1194 Stride = 4; 1195 dumpBytes(Bytes.slice(Index, 4), outs()); 1196 outs() << "\t.word\t"; 1197 uint32_t Data = 0; 1198 if (Obj->isLittleEndian()) { 1199 const auto Word = 1200 reinterpret_cast<const support::ulittle32_t *>( 1201 Bytes.data() + Index); 1202 Data = *Word; 1203 } else { 1204 const auto Word = reinterpret_cast<const support::ubig32_t *>( 1205 Bytes.data() + Index); 1206 Data = *Word; 1207 } 1208 outs() << "0x" << format("%08" PRIx32, Data); 1209 } else if (Index + 2 <= End) { 1210 Stride = 2; 1211 dumpBytes(Bytes.slice(Index, 2), outs()); 1212 outs() << "\t\t.short\t"; 1213 uint16_t Data = 0; 1214 if (Obj->isLittleEndian()) { 1215 const auto Short = 1216 reinterpret_cast<const support::ulittle16_t *>( 1217 Bytes.data() + Index); 1218 Data = *Short; 1219 } else { 1220 const auto Short = 1221 reinterpret_cast<const support::ubig16_t *>(Bytes.data() + 1222 Index); 1223 Data = *Short; 1224 } 1225 outs() << "0x" << format("%04" PRIx16, Data); 1226 } else { 1227 Stride = 1; 1228 dumpBytes(Bytes.slice(Index, 1), outs()); 1229 outs() << "\t\t.byte\t"; 1230 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]); 1231 } 1232 Index += Stride; 1233 outs() << "\n"; 1234 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(), 1235 TextMappingSymsAddr.end(), Index); 1236 if (TAI != TextMappingSymsAddr.end() && *TAI == Index) 1237 break; 1238 } 1239 } 1240 } 1241 1242 // If there is a data symbol inside an ELF text section and we are only 1243 // disassembling text (applicable all architectures), 1244 // we are in a situation where we must print the data and not 1245 // disassemble it. 1246 if (Obj->isELF() && std::get<2>(Symbols[SI]) == ELF::STT_OBJECT && 1247 !DisassembleAll && Section.isText()) { 1248 // print out data up to 8 bytes at a time in hex and ascii 1249 uint8_t AsciiData[9] = {'\0'}; 1250 uint8_t Byte; 1251 int NumBytes = 0; 1252 1253 for (Index = Start; Index < End; Index += 1) { 1254 if (((SectionAddr + Index) < StartAddress) || 1255 ((SectionAddr + Index) > StopAddress)) 1256 continue; 1257 if (NumBytes == 0) { 1258 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 1259 outs() << "\t"; 1260 } 1261 Byte = Bytes.slice(Index)[0]; 1262 outs() << format(" %02x", Byte); 1263 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.'; 1264 1265 uint8_t IndentOffset = 0; 1266 NumBytes++; 1267 if (Index == End - 1 || NumBytes > 8) { 1268 // Indent the space for less than 8 bytes data. 1269 // 2 spaces for byte and one for space between bytes 1270 IndentOffset = 3 * (8 - NumBytes); 1271 for (int Excess = NumBytes; Excess < 8; Excess++) 1272 AsciiData[Excess] = '\0'; 1273 NumBytes = 8; 1274 } 1275 if (NumBytes == 8) { 1276 AsciiData[8] = '\0'; 1277 outs() << std::string(IndentOffset, ' ') << " "; 1278 outs() << reinterpret_cast<char *>(AsciiData); 1279 outs() << '\n'; 1280 NumBytes = 0; 1281 } 1282 } 1283 } 1284 if (Index >= End) 1285 break; 1286 1287 if (size_t N = 1288 countSkippableZeroBytes(Bytes.slice(Index, End - Index))) { 1289 outs() << "\t\t..." << '\n'; 1290 Index += N; 1291 if (Index >= End) 1292 break; 1293 } 1294 1295 // Disassemble a real instruction or a data when disassemble all is 1296 // provided 1297 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), 1298 SectionAddr + Index, DebugOut, 1299 CommentStream); 1300 if (Size == 0) 1301 Size = 1; 1302 1303 PIP.printInst( 1304 *IP, Disassembled ? &Inst : nullptr, Bytes.slice(Index, Size), 1305 SectionAddr + Index + VMAAdjustment, outs(), "", *STI, &SP, &Rels); 1306 outs() << CommentStream.str(); 1307 Comments.clear(); 1308 1309 // Try to resolve the target of a call, tail call, etc. to a specific 1310 // symbol. 1311 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) || 1312 MIA->isConditionalBranch(Inst))) { 1313 uint64_t Target; 1314 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) { 1315 // In a relocatable object, the target's section must reside in 1316 // the same section as the call instruction or it is accessed 1317 // through a relocation. 1318 // 1319 // In a non-relocatable object, the target may be in any section. 1320 // 1321 // N.B. We don't walk the relocations in the relocatable case yet. 1322 auto *TargetSectionSymbols = &Symbols; 1323 if (!Obj->isRelocatableObject()) { 1324 auto SectionAddress = std::upper_bound( 1325 SectionAddresses.begin(), SectionAddresses.end(), Target, 1326 [](uint64_t LHS, 1327 const std::pair<uint64_t, SectionRef> &RHS) { 1328 return LHS < RHS.first; 1329 }); 1330 if (SectionAddress != SectionAddresses.begin()) { 1331 --SectionAddress; 1332 TargetSectionSymbols = &AllSymbols[SectionAddress->second]; 1333 } else { 1334 TargetSectionSymbols = &AbsoluteSymbols; 1335 } 1336 } 1337 1338 // Find the first symbol in the section whose offset is less than 1339 // or equal to the target. If there isn't a section that contains 1340 // the target, find the nearest preceding absolute symbol. 1341 auto TargetSym = std::upper_bound( 1342 TargetSectionSymbols->begin(), TargetSectionSymbols->end(), 1343 Target, [](uint64_t LHS, 1344 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) { 1345 return LHS < std::get<0>(RHS); 1346 }); 1347 if (TargetSym == TargetSectionSymbols->begin()) { 1348 TargetSectionSymbols = &AbsoluteSymbols; 1349 TargetSym = std::upper_bound( 1350 AbsoluteSymbols.begin(), AbsoluteSymbols.end(), 1351 Target, [](uint64_t LHS, 1352 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) { 1353 return LHS < std::get<0>(RHS); 1354 }); 1355 } 1356 if (TargetSym != TargetSectionSymbols->begin()) { 1357 --TargetSym; 1358 uint64_t TargetAddress = std::get<0>(*TargetSym); 1359 StringRef TargetName = std::get<1>(*TargetSym); 1360 outs() << " <" << TargetName; 1361 uint64_t Disp = Target - TargetAddress; 1362 if (Disp) 1363 outs() << "+0x" << Twine::utohexstr(Disp); 1364 outs() << '>'; 1365 } 1366 } 1367 } 1368 outs() << "\n"; 1369 1370 // Hexagon does this in pretty printer 1371 if (Obj->getArch() != Triple::hexagon) { 1372 // Print relocation for instruction. 1373 while (RelCur != RelEnd) { 1374 uint64_t Offset = RelCur->getOffset(); 1375 // If this relocation is hidden, skip it. 1376 if (getHidden(*RelCur) || ((SectionAddr + Offset) < StartAddress)) { 1377 ++RelCur; 1378 continue; 1379 } 1380 1381 // Stop when RelCur's offset is past the current instruction. 1382 if (Offset >= Index + Size) 1383 break; 1384 1385 // When --adjust-vma is used, update the address printed. 1386 if (RelCur->getSymbol() != Obj->symbol_end()) { 1387 Expected<section_iterator> SymSI = 1388 RelCur->getSymbol()->getSection(); 1389 if (SymSI && *SymSI != Obj->section_end() && 1390 (shouldAdjustVA(**SymSI))) 1391 Offset += AdjustVMA; 1392 } 1393 1394 printRelocation(*RelCur, SectionAddr + Offset, 1395 Obj->getBytesInAddress()); 1396 ++RelCur; 1397 } 1398 } 1399 } 1400 } 1401 } 1402 } 1403 1404 static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) { 1405 if (StartAddress > StopAddress) 1406 error("Start address should be less than stop address"); 1407 1408 const Target *TheTarget = getTarget(Obj); 1409 1410 // Package up features to be passed to target/subtarget 1411 SubtargetFeatures Features = Obj->getFeatures(); 1412 if (!MAttrs.empty()) 1413 for (unsigned I = 0; I != MAttrs.size(); ++I) 1414 Features.AddFeature(MAttrs[I]); 1415 1416 std::unique_ptr<const MCRegisterInfo> MRI( 1417 TheTarget->createMCRegInfo(TripleName)); 1418 if (!MRI) 1419 report_error(Obj->getFileName(), 1420 "no register info for target " + TripleName); 1421 1422 // Set up disassembler. 1423 std::unique_ptr<const MCAsmInfo> AsmInfo( 1424 TheTarget->createMCAsmInfo(*MRI, TripleName)); 1425 if (!AsmInfo) 1426 report_error(Obj->getFileName(), 1427 "no assembly info for target " + TripleName); 1428 std::unique_ptr<const MCSubtargetInfo> STI( 1429 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString())); 1430 if (!STI) 1431 report_error(Obj->getFileName(), 1432 "no subtarget info for target " + TripleName); 1433 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); 1434 if (!MII) 1435 report_error(Obj->getFileName(), 1436 "no instruction info for target " + TripleName); 1437 MCObjectFileInfo MOFI; 1438 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI); 1439 // FIXME: for now initialize MCObjectFileInfo with default values 1440 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx); 1441 1442 std::unique_ptr<MCDisassembler> DisAsm( 1443 TheTarget->createMCDisassembler(*STI, Ctx)); 1444 if (!DisAsm) 1445 report_error(Obj->getFileName(), 1446 "no disassembler for target " + TripleName); 1447 1448 std::unique_ptr<const MCInstrAnalysis> MIA( 1449 TheTarget->createMCInstrAnalysis(MII.get())); 1450 1451 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 1452 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 1453 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI)); 1454 if (!IP) 1455 report_error(Obj->getFileName(), 1456 "no instruction printer for target " + TripleName); 1457 IP->setPrintImmHex(PrintImmHex); 1458 1459 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName)); 1460 SourcePrinter SP(Obj, TheTarget->getName()); 1461 1462 disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), MIA.get(), IP.get(), 1463 STI.get(), PIP, SP, InlineRelocs); 1464 } 1465 1466 void llvm::printRelocations(const ObjectFile *Obj) { 1467 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : 1468 "%08" PRIx64; 1469 // Regular objdump doesn't print relocations in non-relocatable object 1470 // files. 1471 if (!Obj->isRelocatableObject()) 1472 return; 1473 1474 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1475 if (Section.relocation_begin() == Section.relocation_end()) 1476 continue; 1477 StringRef SecName; 1478 error(Section.getName(SecName)); 1479 outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n"; 1480 for (const RelocationRef &Reloc : Section.relocations()) { 1481 uint64_t Address = Reloc.getOffset(); 1482 SmallString<32> RelocName; 1483 SmallString<32> ValueStr; 1484 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc)) 1485 continue; 1486 Reloc.getTypeName(RelocName); 1487 error(getRelocationValueString(Reloc, ValueStr)); 1488 outs() << format(Fmt.data(), Address) << " " << RelocName << " " 1489 << ValueStr << "\n"; 1490 } 1491 outs() << "\n"; 1492 } 1493 } 1494 1495 void llvm::printDynamicRelocations(const ObjectFile *Obj) { 1496 // For the moment, this option is for ELF only 1497 if (!Obj->isELF()) 1498 return; 1499 1500 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj); 1501 if (!Elf || Elf->getEType() != ELF::ET_DYN) { 1502 error("not a dynamic object"); 1503 return; 1504 } 1505 1506 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections(); 1507 if (DynRelSec.empty()) 1508 return; 1509 1510 outs() << "DYNAMIC RELOCATION RECORDS\n"; 1511 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 1512 for (const SectionRef &Section : DynRelSec) { 1513 if (Section.relocation_begin() == Section.relocation_end()) 1514 continue; 1515 for (const RelocationRef &Reloc : Section.relocations()) { 1516 uint64_t Address = Reloc.getOffset(); 1517 SmallString<32> RelocName; 1518 SmallString<32> ValueStr; 1519 Reloc.getTypeName(RelocName); 1520 error(getRelocationValueString(Reloc, ValueStr)); 1521 outs() << format(Fmt.data(), Address) << " " << RelocName << " " 1522 << ValueStr << "\n"; 1523 } 1524 } 1525 } 1526 1527 // Returns true if we need to show LMA column when dumping section headers. We 1528 // show it only when the platform is ELF and either we have at least one section 1529 // whose VMA and LMA are different and/or when --show-lma flag is used. 1530 static bool shouldDisplayLMA(const ObjectFile *Obj) { 1531 if (!Obj->isELF()) 1532 return false; 1533 for (const SectionRef &S : ToolSectionFilter(*Obj)) 1534 if (S.getAddress() != getELFSectionLMA(S)) 1535 return true; 1536 return ShowLMA; 1537 } 1538 1539 void llvm::printSectionHeaders(const ObjectFile *Obj) { 1540 bool HasLMAColumn = shouldDisplayLMA(Obj); 1541 if (HasLMAColumn) 1542 outs() << "Sections:\n" 1543 "Idx Name Size VMA LMA " 1544 "Type\n"; 1545 else 1546 outs() << "Sections:\n" 1547 "Idx Name Size VMA Type\n"; 1548 1549 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1550 StringRef Name; 1551 error(Section.getName(Name)); 1552 uint64_t VMA = Section.getAddress(); 1553 if (shouldAdjustVA(Section)) 1554 VMA += AdjustVMA; 1555 1556 uint64_t Size = Section.getSize(); 1557 bool Text = Section.isText(); 1558 bool Data = Section.isData(); 1559 bool BSS = Section.isBSS(); 1560 std::string Type = (std::string(Text ? "TEXT " : "") + 1561 (Data ? "DATA " : "") + (BSS ? "BSS" : "")); 1562 1563 if (HasLMAColumn) 1564 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %016" PRIx64 1565 " %s\n", 1566 (unsigned)Section.getIndex(), Name.str().c_str(), Size, 1567 VMA, getELFSectionLMA(Section), Type.c_str()); 1568 else 1569 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", 1570 (unsigned)Section.getIndex(), Name.str().c_str(), Size, 1571 VMA, Type.c_str()); 1572 } 1573 outs() << "\n"; 1574 } 1575 1576 void llvm::printSectionContents(const ObjectFile *Obj) { 1577 std::error_code EC; 1578 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1579 StringRef Name; 1580 StringRef Contents; 1581 error(Section.getName(Name)); 1582 uint64_t BaseAddr = Section.getAddress(); 1583 uint64_t Size = Section.getSize(); 1584 if (!Size) 1585 continue; 1586 1587 outs() << "Contents of section " << Name << ":\n"; 1588 if (Section.isBSS()) { 1589 outs() << format("<skipping contents of bss section at [%04" PRIx64 1590 ", %04" PRIx64 ")>\n", 1591 BaseAddr, BaseAddr + Size); 1592 continue; 1593 } 1594 1595 error(Section.getContents(Contents)); 1596 1597 // Dump out the content as hex and printable ascii characters. 1598 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) { 1599 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr); 1600 // Dump line of hex. 1601 for (std::size_t I = 0; I < 16; ++I) { 1602 if (I != 0 && I % 4 == 0) 1603 outs() << ' '; 1604 if (Addr + I < End) 1605 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true) 1606 << hexdigit(Contents[Addr + I] & 0xF, true); 1607 else 1608 outs() << " "; 1609 } 1610 // Print ascii. 1611 outs() << " "; 1612 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) { 1613 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF)) 1614 outs() << Contents[Addr + I]; 1615 else 1616 outs() << "."; 1617 } 1618 outs() << "\n"; 1619 } 1620 } 1621 } 1622 1623 void llvm::printSymbolTable(const ObjectFile *O, StringRef ArchiveName, 1624 StringRef ArchitectureName) { 1625 outs() << "SYMBOL TABLE:\n"; 1626 1627 if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) { 1628 printCOFFSymbolTable(Coff); 1629 return; 1630 } 1631 1632 for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) { 1633 // Skip printing the special zero symbol when dumping an ELF file. 1634 // This makes the output consistent with the GNU objdump. 1635 if (I == O->symbol_begin() && isa<ELFObjectFileBase>(O)) 1636 continue; 1637 1638 const SymbolRef &Symbol = *I; 1639 Expected<uint64_t> AddressOrError = Symbol.getAddress(); 1640 if (!AddressOrError) 1641 report_error(ArchiveName, O->getFileName(), AddressOrError.takeError(), 1642 ArchitectureName); 1643 uint64_t Address = *AddressOrError; 1644 if ((Address < StartAddress) || (Address > StopAddress)) 1645 continue; 1646 Expected<SymbolRef::Type> TypeOrError = Symbol.getType(); 1647 if (!TypeOrError) 1648 report_error(ArchiveName, O->getFileName(), TypeOrError.takeError(), 1649 ArchitectureName); 1650 SymbolRef::Type Type = *TypeOrError; 1651 uint32_t Flags = Symbol.getFlags(); 1652 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 1653 if (!SectionOrErr) 1654 report_error(ArchiveName, O->getFileName(), SectionOrErr.takeError(), 1655 ArchitectureName); 1656 section_iterator Section = *SectionOrErr; 1657 StringRef Name; 1658 if (Type == SymbolRef::ST_Debug && Section != O->section_end()) { 1659 Section->getName(Name); 1660 } else { 1661 Expected<StringRef> NameOrErr = Symbol.getName(); 1662 if (!NameOrErr) 1663 report_error(ArchiveName, O->getFileName(), NameOrErr.takeError(), 1664 ArchitectureName); 1665 Name = *NameOrErr; 1666 } 1667 1668 bool Global = Flags & SymbolRef::SF_Global; 1669 bool Weak = Flags & SymbolRef::SF_Weak; 1670 bool Absolute = Flags & SymbolRef::SF_Absolute; 1671 bool Common = Flags & SymbolRef::SF_Common; 1672 bool Hidden = Flags & SymbolRef::SF_Hidden; 1673 1674 char GlobLoc = ' '; 1675 if (Type != SymbolRef::ST_Unknown) 1676 GlobLoc = Global ? 'g' : 'l'; 1677 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 1678 ? 'd' : ' '; 1679 char FileFunc = ' '; 1680 if (Type == SymbolRef::ST_File) 1681 FileFunc = 'f'; 1682 else if (Type == SymbolRef::ST_Function) 1683 FileFunc = 'F'; 1684 else if (Type == SymbolRef::ST_Data) 1685 FileFunc = 'O'; 1686 1687 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : 1688 "%08" PRIx64; 1689 1690 outs() << format(Fmt, Address) << " " 1691 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 1692 << (Weak ? 'w' : ' ') // Weak? 1693 << ' ' // Constructor. Not supported yet. 1694 << ' ' // Warning. Not supported yet. 1695 << ' ' // Indirect reference to another symbol. 1696 << Debug // Debugging (d) or dynamic (D) symbol. 1697 << FileFunc // Name of function (F), file (f) or object (O). 1698 << ' '; 1699 if (Absolute) { 1700 outs() << "*ABS*"; 1701 } else if (Common) { 1702 outs() << "*COM*"; 1703 } else if (Section == O->section_end()) { 1704 outs() << "*UND*"; 1705 } else { 1706 if (const MachOObjectFile *MachO = 1707 dyn_cast<const MachOObjectFile>(O)) { 1708 DataRefImpl DR = Section->getRawDataRefImpl(); 1709 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 1710 outs() << SegmentName << ","; 1711 } 1712 StringRef SectionName; 1713 error(Section->getName(SectionName)); 1714 outs() << SectionName; 1715 } 1716 1717 outs() << '\t'; 1718 if (Common || isa<ELFObjectFileBase>(O)) { 1719 uint64_t Val = 1720 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize(); 1721 outs() << format("\t %08" PRIx64 " ", Val); 1722 } 1723 1724 if (Hidden) 1725 outs() << ".hidden "; 1726 1727 if (Demangle) 1728 outs() << demangle(Name) << '\n'; 1729 else 1730 outs() << Name << '\n'; 1731 } 1732 } 1733 1734 static void printUnwindInfo(const ObjectFile *O) { 1735 outs() << "Unwind info:\n\n"; 1736 1737 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O)) 1738 printCOFFUnwindInfo(Coff); 1739 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O)) 1740 printMachOUnwindInfo(MachO); 1741 else 1742 // TODO: Extract DWARF dump tool to objdump. 1743 WithColor::error(errs(), ToolName) 1744 << "This operation is only currently supported " 1745 "for COFF and MachO object files.\n"; 1746 } 1747 1748 void llvm::printExportsTrie(const ObjectFile *o) { 1749 outs() << "Exports trie:\n"; 1750 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1751 printMachOExportsTrie(MachO); 1752 else 1753 WithColor::error(errs(), ToolName) 1754 << "This operation is only currently supported " 1755 "for Mach-O executable files.\n"; 1756 } 1757 1758 void llvm::printRebaseTable(ObjectFile *o) { 1759 outs() << "Rebase table:\n"; 1760 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1761 printMachORebaseTable(MachO); 1762 else 1763 WithColor::error(errs(), ToolName) 1764 << "This operation is only currently supported " 1765 "for Mach-O executable files.\n"; 1766 } 1767 1768 void llvm::printBindTable(ObjectFile *o) { 1769 outs() << "Bind table:\n"; 1770 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1771 printMachOBindTable(MachO); 1772 else 1773 WithColor::error(errs(), ToolName) 1774 << "This operation is only currently supported " 1775 "for Mach-O executable files.\n"; 1776 } 1777 1778 void llvm::printLazyBindTable(ObjectFile *o) { 1779 outs() << "Lazy bind table:\n"; 1780 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1781 printMachOLazyBindTable(MachO); 1782 else 1783 WithColor::error(errs(), ToolName) 1784 << "This operation is only currently supported " 1785 "for Mach-O executable files.\n"; 1786 } 1787 1788 void llvm::printWeakBindTable(ObjectFile *o) { 1789 outs() << "Weak bind table:\n"; 1790 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1791 printMachOWeakBindTable(MachO); 1792 else 1793 WithColor::error(errs(), ToolName) 1794 << "This operation is only currently supported " 1795 "for Mach-O executable files.\n"; 1796 } 1797 1798 /// Dump the raw contents of the __clangast section so the output can be piped 1799 /// into llvm-bcanalyzer. 1800 void llvm::printRawClangAST(const ObjectFile *Obj) { 1801 if (outs().is_displayed()) { 1802 WithColor::error(errs(), ToolName) 1803 << "The -raw-clang-ast option will dump the raw binary contents of " 1804 "the clang ast section.\n" 1805 "Please redirect the output to a file or another program such as " 1806 "llvm-bcanalyzer.\n"; 1807 return; 1808 } 1809 1810 StringRef ClangASTSectionName("__clangast"); 1811 if (isa<COFFObjectFile>(Obj)) { 1812 ClangASTSectionName = "clangast"; 1813 } 1814 1815 Optional<object::SectionRef> ClangASTSection; 1816 for (auto Sec : ToolSectionFilter(*Obj)) { 1817 StringRef Name; 1818 Sec.getName(Name); 1819 if (Name == ClangASTSectionName) { 1820 ClangASTSection = Sec; 1821 break; 1822 } 1823 } 1824 if (!ClangASTSection) 1825 return; 1826 1827 StringRef ClangASTContents; 1828 error(ClangASTSection.getValue().getContents(ClangASTContents)); 1829 outs().write(ClangASTContents.data(), ClangASTContents.size()); 1830 } 1831 1832 static void printFaultMaps(const ObjectFile *Obj) { 1833 StringRef FaultMapSectionName; 1834 1835 if (isa<ELFObjectFileBase>(Obj)) { 1836 FaultMapSectionName = ".llvm_faultmaps"; 1837 } else if (isa<MachOObjectFile>(Obj)) { 1838 FaultMapSectionName = "__llvm_faultmaps"; 1839 } else { 1840 WithColor::error(errs(), ToolName) 1841 << "This operation is only currently supported " 1842 "for ELF and Mach-O executable files.\n"; 1843 return; 1844 } 1845 1846 Optional<object::SectionRef> FaultMapSection; 1847 1848 for (auto Sec : ToolSectionFilter(*Obj)) { 1849 StringRef Name; 1850 Sec.getName(Name); 1851 if (Name == FaultMapSectionName) { 1852 FaultMapSection = Sec; 1853 break; 1854 } 1855 } 1856 1857 outs() << "FaultMap table:\n"; 1858 1859 if (!FaultMapSection.hasValue()) { 1860 outs() << "<not found>\n"; 1861 return; 1862 } 1863 1864 StringRef FaultMapContents; 1865 error(FaultMapSection.getValue().getContents(FaultMapContents)); 1866 1867 FaultMapParser FMP(FaultMapContents.bytes_begin(), 1868 FaultMapContents.bytes_end()); 1869 1870 outs() << FMP; 1871 } 1872 1873 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) { 1874 if (O->isELF()) { 1875 printELFFileHeader(O); 1876 return printELFDynamicSection(O); 1877 } 1878 if (O->isCOFF()) 1879 return printCOFFFileHeader(O); 1880 if (O->isWasm()) 1881 return printWasmFileHeader(O); 1882 if (O->isMachO()) { 1883 printMachOFileHeader(O); 1884 if (!OnlyFirst) 1885 printMachOLoadCommands(O); 1886 return; 1887 } 1888 report_error(O->getFileName(), "Invalid/Unsupported object file format"); 1889 } 1890 1891 static void printFileHeaders(const ObjectFile *O) { 1892 if (!O->isELF() && !O->isCOFF()) 1893 report_error(O->getFileName(), "Invalid/Unsupported object file format"); 1894 1895 Triple::ArchType AT = O->getArch(); 1896 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n"; 1897 Expected<uint64_t> StartAddrOrErr = O->getStartAddress(); 1898 if (!StartAddrOrErr) 1899 report_error(O->getFileName(), StartAddrOrErr.takeError()); 1900 1901 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 1902 uint64_t Address = StartAddrOrErr.get(); 1903 outs() << "start address: " 1904 << "0x" << format(Fmt.data(), Address) << "\n\n"; 1905 } 1906 1907 static void printArchiveChild(StringRef Filename, const Archive::Child &C) { 1908 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode(); 1909 if (!ModeOrErr) { 1910 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n"; 1911 consumeError(ModeOrErr.takeError()); 1912 return; 1913 } 1914 sys::fs::perms Mode = ModeOrErr.get(); 1915 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-"); 1916 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-"); 1917 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-"); 1918 outs() << ((Mode & sys::fs::group_read) ? "r" : "-"); 1919 outs() << ((Mode & sys::fs::group_write) ? "w" : "-"); 1920 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-"); 1921 outs() << ((Mode & sys::fs::others_read) ? "r" : "-"); 1922 outs() << ((Mode & sys::fs::others_write) ? "w" : "-"); 1923 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-"); 1924 1925 outs() << " "; 1926 1927 Expected<unsigned> UIDOrErr = C.getUID(); 1928 if (!UIDOrErr) 1929 report_error(Filename, UIDOrErr.takeError()); 1930 unsigned UID = UIDOrErr.get(); 1931 outs() << format("%d/", UID); 1932 1933 Expected<unsigned> GIDOrErr = C.getGID(); 1934 if (!GIDOrErr) 1935 report_error(Filename, GIDOrErr.takeError()); 1936 unsigned GID = GIDOrErr.get(); 1937 outs() << format("%-d ", GID); 1938 1939 Expected<uint64_t> Size = C.getRawSize(); 1940 if (!Size) 1941 report_error(Filename, Size.takeError()); 1942 outs() << format("%6" PRId64, Size.get()) << " "; 1943 1944 StringRef RawLastModified = C.getRawLastModified(); 1945 unsigned Seconds; 1946 if (RawLastModified.getAsInteger(10, Seconds)) 1947 outs() << "(date: \"" << RawLastModified 1948 << "\" contains non-decimal chars) "; 1949 else { 1950 // Since ctime(3) returns a 26 character string of the form: 1951 // "Sun Sep 16 01:03:52 1973\n\0" 1952 // just print 24 characters. 1953 time_t t = Seconds; 1954 outs() << format("%.24s ", ctime(&t)); 1955 } 1956 1957 StringRef Name = ""; 1958 Expected<StringRef> NameOrErr = C.getName(); 1959 if (!NameOrErr) { 1960 consumeError(NameOrErr.takeError()); 1961 Expected<StringRef> RawNameOrErr = C.getRawName(); 1962 if (!RawNameOrErr) 1963 report_error(Filename, NameOrErr.takeError()); 1964 Name = RawNameOrErr.get(); 1965 } else { 1966 Name = NameOrErr.get(); 1967 } 1968 outs() << Name << "\n"; 1969 } 1970 1971 static void dumpObject(ObjectFile *O, const Archive *A = nullptr, 1972 const Archive::Child *C = nullptr) { 1973 // Avoid other output when using a raw option. 1974 if (!RawClangAST) { 1975 outs() << '\n'; 1976 if (A) 1977 outs() << A->getFileName() << "(" << O->getFileName() << ")"; 1978 else 1979 outs() << O->getFileName(); 1980 outs() << ":\tfile format " << O->getFileFormatName() << "\n\n"; 1981 } 1982 1983 StringRef ArchiveName = A ? A->getFileName() : ""; 1984 if (FileHeaders) 1985 printFileHeaders(O); 1986 if (ArchiveHeaders && !MachOOpt && C) 1987 printArchiveChild(ArchiveName, *C); 1988 if (Disassemble) 1989 disassembleObject(O, Relocations); 1990 if (Relocations && !Disassemble) 1991 printRelocations(O); 1992 if (DynamicRelocations) 1993 printDynamicRelocations(O); 1994 if (SectionHeaders) 1995 printSectionHeaders(O); 1996 if (SectionContents) 1997 printSectionContents(O); 1998 if (SymbolTable) 1999 printSymbolTable(O, ArchiveName); 2000 if (UnwindInfo) 2001 printUnwindInfo(O); 2002 if (PrivateHeaders || FirstPrivateHeader) 2003 printPrivateFileHeaders(O, FirstPrivateHeader); 2004 if (ExportsTrie) 2005 printExportsTrie(O); 2006 if (Rebase) 2007 printRebaseTable(O); 2008 if (Bind) 2009 printBindTable(O); 2010 if (LazyBind) 2011 printLazyBindTable(O); 2012 if (WeakBind) 2013 printWeakBindTable(O); 2014 if (RawClangAST) 2015 printRawClangAST(O); 2016 if (PrintFaultMaps) 2017 printFaultMaps(O); 2018 if (DwarfDumpType != DIDT_Null) { 2019 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O); 2020 // Dump the complete DWARF structure. 2021 DIDumpOptions DumpOpts; 2022 DumpOpts.DumpType = DwarfDumpType; 2023 DICtx->dump(outs(), DumpOpts); 2024 } 2025 } 2026 2027 static void dumpObject(const COFFImportFile *I, const Archive *A, 2028 const Archive::Child *C = nullptr) { 2029 StringRef ArchiveName = A ? A->getFileName() : ""; 2030 2031 // Avoid other output when using a raw option. 2032 if (!RawClangAST) 2033 outs() << '\n' 2034 << ArchiveName << "(" << I->getFileName() << ")" 2035 << ":\tfile format COFF-import-file" 2036 << "\n\n"; 2037 2038 if (ArchiveHeaders && !MachOOpt && C) 2039 printArchiveChild(ArchiveName, *C); 2040 if (SymbolTable) 2041 printCOFFSymbolTable(I); 2042 } 2043 2044 /// Dump each object file in \a a; 2045 static void dumpArchive(const Archive *A) { 2046 Error Err = Error::success(); 2047 for (auto &C : A->children(Err)) { 2048 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2049 if (!ChildOrErr) { 2050 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2051 report_error(A->getFileName(), C, std::move(E)); 2052 continue; 2053 } 2054 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 2055 dumpObject(O, A, &C); 2056 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get())) 2057 dumpObject(I, A, &C); 2058 else 2059 report_error(A->getFileName(), object_error::invalid_file_type); 2060 } 2061 if (Err) 2062 report_error(A->getFileName(), std::move(Err)); 2063 } 2064 2065 /// Open file and figure out how to dump it. 2066 static void dumpInput(StringRef file) { 2067 // If we are using the Mach-O specific object file parser, then let it parse 2068 // the file and process the command line options. So the -arch flags can 2069 // be used to select specific slices, etc. 2070 if (MachOOpt) { 2071 parseInputMachO(file); 2072 return; 2073 } 2074 2075 // Attempt to open the binary. 2076 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file); 2077 if (!BinaryOrErr) 2078 report_error(file, BinaryOrErr.takeError()); 2079 Binary &Binary = *BinaryOrErr.get().getBinary(); 2080 2081 if (Archive *A = dyn_cast<Archive>(&Binary)) 2082 dumpArchive(A); 2083 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary)) 2084 dumpObject(O); 2085 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary)) 2086 parseInputMachO(UB); 2087 else 2088 report_error(file, object_error::invalid_file_type); 2089 } 2090 2091 int main(int argc, char **argv) { 2092 InitLLVM X(argc, argv); 2093 2094 // Initialize targets and assembly printers/parsers. 2095 llvm::InitializeAllTargetInfos(); 2096 llvm::InitializeAllTargetMCs(); 2097 llvm::InitializeAllDisassemblers(); 2098 2099 // Register the target printer for --version. 2100 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 2101 2102 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 2103 2104 ToolName = argv[0]; 2105 2106 // Defaults to a.out if no filenames specified. 2107 if (InputFilenames.empty()) 2108 InputFilenames.push_back("a.out"); 2109 2110 if (AllHeaders) 2111 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations = 2112 SectionHeaders = SymbolTable = true; 2113 2114 if (DisassembleAll || PrintSource || PrintLines) 2115 Disassemble = true; 2116 2117 if (!Disassemble 2118 && !Relocations 2119 && !DynamicRelocations 2120 && !SectionHeaders 2121 && !SectionContents 2122 && !SymbolTable 2123 && !UnwindInfo 2124 && !PrivateHeaders 2125 && !FileHeaders 2126 && !FirstPrivateHeader 2127 && !ExportsTrie 2128 && !Rebase 2129 && !Bind 2130 && !LazyBind 2131 && !WeakBind 2132 && !RawClangAST 2133 && !(UniversalHeaders && MachOOpt) 2134 && !ArchiveHeaders 2135 && !(IndirectSymbols && MachOOpt) 2136 && !(DataInCode && MachOOpt) 2137 && !(LinkOptHints && MachOOpt) 2138 && !(InfoPlist && MachOOpt) 2139 && !(DylibsUsed && MachOOpt) 2140 && !(DylibId && MachOOpt) 2141 && !(ObjcMetaData && MachOOpt) 2142 && !(!FilterSections.empty() && MachOOpt) 2143 && !PrintFaultMaps 2144 && DwarfDumpType == DIDT_Null) { 2145 cl::PrintHelpMessage(); 2146 return 2; 2147 } 2148 2149 DisasmFuncsSet.insert(DisassembleFunctions.begin(), 2150 DisassembleFunctions.end()); 2151 2152 llvm::for_each(InputFilenames, dumpInput); 2153 2154 return EXIT_SUCCESS; 2155 } 2156