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 if (shouldAdjustVA(Section)) 1551 VMA += AdjustVMA; 1552 1553 uint64_t Size = Section.getSize(); 1554 bool Text = Section.isText(); 1555 bool Data = Section.isData(); 1556 bool BSS = Section.isBSS(); 1557 std::string Type = (std::string(Text ? "TEXT " : "") + 1558 (Data ? "DATA " : "") + (BSS ? "BSS" : "")); 1559 1560 if (HasLMAColumn) 1561 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %016" PRIx64 1562 " %s\n", 1563 (unsigned)Section.getIndex(), Name.str().c_str(), Size, 1564 VMA, getELFSectionLMA(Section), Type.c_str()); 1565 else 1566 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", 1567 (unsigned)Section.getIndex(), Name.str().c_str(), Size, 1568 VMA, Type.c_str()); 1569 } 1570 outs() << "\n"; 1571 } 1572 1573 void llvm::printSectionContents(const ObjectFile *Obj) { 1574 std::error_code EC; 1575 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1576 StringRef Name; 1577 StringRef Contents; 1578 error(Section.getName(Name)); 1579 uint64_t BaseAddr = Section.getAddress(); 1580 uint64_t Size = Section.getSize(); 1581 if (!Size) 1582 continue; 1583 1584 outs() << "Contents of section " << Name << ":\n"; 1585 if (Section.isBSS()) { 1586 outs() << format("<skipping contents of bss section at [%04" PRIx64 1587 ", %04" PRIx64 ")>\n", 1588 BaseAddr, BaseAddr + Size); 1589 continue; 1590 } 1591 1592 error(Section.getContents(Contents)); 1593 1594 // Dump out the content as hex and printable ascii characters. 1595 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) { 1596 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr); 1597 // Dump line of hex. 1598 for (std::size_t I = 0; I < 16; ++I) { 1599 if (I != 0 && I % 4 == 0) 1600 outs() << ' '; 1601 if (Addr + I < End) 1602 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true) 1603 << hexdigit(Contents[Addr + I] & 0xF, true); 1604 else 1605 outs() << " "; 1606 } 1607 // Print ascii. 1608 outs() << " "; 1609 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) { 1610 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF)) 1611 outs() << Contents[Addr + I]; 1612 else 1613 outs() << "."; 1614 } 1615 outs() << "\n"; 1616 } 1617 } 1618 } 1619 1620 void llvm::printSymbolTable(const ObjectFile *O, StringRef ArchiveName, 1621 StringRef ArchitectureName) { 1622 outs() << "SYMBOL TABLE:\n"; 1623 1624 if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) { 1625 printCOFFSymbolTable(Coff); 1626 return; 1627 } 1628 1629 for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) { 1630 // Skip printing the special zero symbol when dumping an ELF file. 1631 // This makes the output consistent with the GNU objdump. 1632 if (I == O->symbol_begin() && isa<ELFObjectFileBase>(O)) 1633 continue; 1634 1635 const SymbolRef &Symbol = *I; 1636 Expected<uint64_t> AddressOrError = Symbol.getAddress(); 1637 if (!AddressOrError) 1638 report_error(ArchiveName, O->getFileName(), AddressOrError.takeError(), 1639 ArchitectureName); 1640 uint64_t Address = *AddressOrError; 1641 if ((Address < StartAddress) || (Address > StopAddress)) 1642 continue; 1643 Expected<SymbolRef::Type> TypeOrError = Symbol.getType(); 1644 if (!TypeOrError) 1645 report_error(ArchiveName, O->getFileName(), TypeOrError.takeError(), 1646 ArchitectureName); 1647 SymbolRef::Type Type = *TypeOrError; 1648 uint32_t Flags = Symbol.getFlags(); 1649 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 1650 if (!SectionOrErr) 1651 report_error(ArchiveName, O->getFileName(), SectionOrErr.takeError(), 1652 ArchitectureName); 1653 section_iterator Section = *SectionOrErr; 1654 StringRef Name; 1655 if (Type == SymbolRef::ST_Debug && Section != O->section_end()) { 1656 Section->getName(Name); 1657 } else { 1658 Expected<StringRef> NameOrErr = Symbol.getName(); 1659 if (!NameOrErr) 1660 report_error(ArchiveName, O->getFileName(), NameOrErr.takeError(), 1661 ArchitectureName); 1662 Name = *NameOrErr; 1663 } 1664 1665 bool Global = Flags & SymbolRef::SF_Global; 1666 bool Weak = Flags & SymbolRef::SF_Weak; 1667 bool Absolute = Flags & SymbolRef::SF_Absolute; 1668 bool Common = Flags & SymbolRef::SF_Common; 1669 bool Hidden = Flags & SymbolRef::SF_Hidden; 1670 1671 char GlobLoc = ' '; 1672 if (Type != SymbolRef::ST_Unknown) 1673 GlobLoc = Global ? 'g' : 'l'; 1674 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 1675 ? 'd' : ' '; 1676 char FileFunc = ' '; 1677 if (Type == SymbolRef::ST_File) 1678 FileFunc = 'f'; 1679 else if (Type == SymbolRef::ST_Function) 1680 FileFunc = 'F'; 1681 else if (Type == SymbolRef::ST_Data) 1682 FileFunc = 'O'; 1683 1684 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : 1685 "%08" PRIx64; 1686 1687 outs() << format(Fmt, Address) << " " 1688 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 1689 << (Weak ? 'w' : ' ') // Weak? 1690 << ' ' // Constructor. Not supported yet. 1691 << ' ' // Warning. Not supported yet. 1692 << ' ' // Indirect reference to another symbol. 1693 << Debug // Debugging (d) or dynamic (D) symbol. 1694 << FileFunc // Name of function (F), file (f) or object (O). 1695 << ' '; 1696 if (Absolute) { 1697 outs() << "*ABS*"; 1698 } else if (Common) { 1699 outs() << "*COM*"; 1700 } else if (Section == O->section_end()) { 1701 outs() << "*UND*"; 1702 } else { 1703 if (const MachOObjectFile *MachO = 1704 dyn_cast<const MachOObjectFile>(O)) { 1705 DataRefImpl DR = Section->getRawDataRefImpl(); 1706 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 1707 outs() << SegmentName << ","; 1708 } 1709 StringRef SectionName; 1710 error(Section->getName(SectionName)); 1711 outs() << SectionName; 1712 } 1713 1714 outs() << '\t'; 1715 if (Common || isa<ELFObjectFileBase>(O)) { 1716 uint64_t Val = 1717 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize(); 1718 outs() << format("\t %08" PRIx64 " ", Val); 1719 } 1720 1721 if (Hidden) 1722 outs() << ".hidden "; 1723 1724 if (Demangle) 1725 outs() << demangle(Name) << '\n'; 1726 else 1727 outs() << Name << '\n'; 1728 } 1729 } 1730 1731 static void printUnwindInfo(const ObjectFile *O) { 1732 outs() << "Unwind info:\n\n"; 1733 1734 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O)) 1735 printCOFFUnwindInfo(Coff); 1736 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O)) 1737 printMachOUnwindInfo(MachO); 1738 else 1739 // TODO: Extract DWARF dump tool to objdump. 1740 WithColor::error(errs(), ToolName) 1741 << "This operation is only currently supported " 1742 "for COFF and MachO object files.\n"; 1743 } 1744 1745 void llvm::printExportsTrie(const ObjectFile *o) { 1746 outs() << "Exports trie:\n"; 1747 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1748 printMachOExportsTrie(MachO); 1749 else 1750 WithColor::error(errs(), ToolName) 1751 << "This operation is only currently supported " 1752 "for Mach-O executable files.\n"; 1753 } 1754 1755 void llvm::printRebaseTable(ObjectFile *o) { 1756 outs() << "Rebase table:\n"; 1757 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1758 printMachORebaseTable(MachO); 1759 else 1760 WithColor::error(errs(), ToolName) 1761 << "This operation is only currently supported " 1762 "for Mach-O executable files.\n"; 1763 } 1764 1765 void llvm::printBindTable(ObjectFile *o) { 1766 outs() << "Bind table:\n"; 1767 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1768 printMachOBindTable(MachO); 1769 else 1770 WithColor::error(errs(), ToolName) 1771 << "This operation is only currently supported " 1772 "for Mach-O executable files.\n"; 1773 } 1774 1775 void llvm::printLazyBindTable(ObjectFile *o) { 1776 outs() << "Lazy bind table:\n"; 1777 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1778 printMachOLazyBindTable(MachO); 1779 else 1780 WithColor::error(errs(), ToolName) 1781 << "This operation is only currently supported " 1782 "for Mach-O executable files.\n"; 1783 } 1784 1785 void llvm::printWeakBindTable(ObjectFile *o) { 1786 outs() << "Weak bind table:\n"; 1787 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1788 printMachOWeakBindTable(MachO); 1789 else 1790 WithColor::error(errs(), ToolName) 1791 << "This operation is only currently supported " 1792 "for Mach-O executable files.\n"; 1793 } 1794 1795 /// Dump the raw contents of the __clangast section so the output can be piped 1796 /// into llvm-bcanalyzer. 1797 void llvm::printRawClangAST(const ObjectFile *Obj) { 1798 if (outs().is_displayed()) { 1799 WithColor::error(errs(), ToolName) 1800 << "The -raw-clang-ast option will dump the raw binary contents of " 1801 "the clang ast section.\n" 1802 "Please redirect the output to a file or another program such as " 1803 "llvm-bcanalyzer.\n"; 1804 return; 1805 } 1806 1807 StringRef ClangASTSectionName("__clangast"); 1808 if (isa<COFFObjectFile>(Obj)) { 1809 ClangASTSectionName = "clangast"; 1810 } 1811 1812 Optional<object::SectionRef> ClangASTSection; 1813 for (auto Sec : ToolSectionFilter(*Obj)) { 1814 StringRef Name; 1815 Sec.getName(Name); 1816 if (Name == ClangASTSectionName) { 1817 ClangASTSection = Sec; 1818 break; 1819 } 1820 } 1821 if (!ClangASTSection) 1822 return; 1823 1824 StringRef ClangASTContents; 1825 error(ClangASTSection.getValue().getContents(ClangASTContents)); 1826 outs().write(ClangASTContents.data(), ClangASTContents.size()); 1827 } 1828 1829 static void printFaultMaps(const ObjectFile *Obj) { 1830 StringRef FaultMapSectionName; 1831 1832 if (isa<ELFObjectFileBase>(Obj)) { 1833 FaultMapSectionName = ".llvm_faultmaps"; 1834 } else if (isa<MachOObjectFile>(Obj)) { 1835 FaultMapSectionName = "__llvm_faultmaps"; 1836 } else { 1837 WithColor::error(errs(), ToolName) 1838 << "This operation is only currently supported " 1839 "for ELF and Mach-O executable files.\n"; 1840 return; 1841 } 1842 1843 Optional<object::SectionRef> FaultMapSection; 1844 1845 for (auto Sec : ToolSectionFilter(*Obj)) { 1846 StringRef Name; 1847 Sec.getName(Name); 1848 if (Name == FaultMapSectionName) { 1849 FaultMapSection = Sec; 1850 break; 1851 } 1852 } 1853 1854 outs() << "FaultMap table:\n"; 1855 1856 if (!FaultMapSection.hasValue()) { 1857 outs() << "<not found>\n"; 1858 return; 1859 } 1860 1861 StringRef FaultMapContents; 1862 error(FaultMapSection.getValue().getContents(FaultMapContents)); 1863 1864 FaultMapParser FMP(FaultMapContents.bytes_begin(), 1865 FaultMapContents.bytes_end()); 1866 1867 outs() << FMP; 1868 } 1869 1870 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) { 1871 if (O->isELF()) { 1872 printELFFileHeader(O); 1873 return printELFDynamicSection(O); 1874 } 1875 if (O->isCOFF()) 1876 return printCOFFFileHeader(O); 1877 if (O->isWasm()) 1878 return printWasmFileHeader(O); 1879 if (O->isMachO()) { 1880 printMachOFileHeader(O); 1881 if (!OnlyFirst) 1882 printMachOLoadCommands(O); 1883 return; 1884 } 1885 report_error(O->getFileName(), "Invalid/Unsupported object file format"); 1886 } 1887 1888 static void printFileHeaders(const ObjectFile *O) { 1889 if (!O->isELF() && !O->isCOFF()) 1890 report_error(O->getFileName(), "Invalid/Unsupported object file format"); 1891 1892 Triple::ArchType AT = O->getArch(); 1893 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n"; 1894 Expected<uint64_t> StartAddrOrErr = O->getStartAddress(); 1895 if (!StartAddrOrErr) 1896 report_error(O->getFileName(), StartAddrOrErr.takeError()); 1897 1898 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 1899 uint64_t Address = StartAddrOrErr.get(); 1900 outs() << "start address: " 1901 << "0x" << format(Fmt.data(), Address) << "\n\n"; 1902 } 1903 1904 static void printArchiveChild(StringRef Filename, const Archive::Child &C) { 1905 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode(); 1906 if (!ModeOrErr) { 1907 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n"; 1908 consumeError(ModeOrErr.takeError()); 1909 return; 1910 } 1911 sys::fs::perms Mode = ModeOrErr.get(); 1912 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-"); 1913 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-"); 1914 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-"); 1915 outs() << ((Mode & sys::fs::group_read) ? "r" : "-"); 1916 outs() << ((Mode & sys::fs::group_write) ? "w" : "-"); 1917 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-"); 1918 outs() << ((Mode & sys::fs::others_read) ? "r" : "-"); 1919 outs() << ((Mode & sys::fs::others_write) ? "w" : "-"); 1920 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-"); 1921 1922 outs() << " "; 1923 1924 Expected<unsigned> UIDOrErr = C.getUID(); 1925 if (!UIDOrErr) 1926 report_error(Filename, UIDOrErr.takeError()); 1927 unsigned UID = UIDOrErr.get(); 1928 outs() << format("%d/", UID); 1929 1930 Expected<unsigned> GIDOrErr = C.getGID(); 1931 if (!GIDOrErr) 1932 report_error(Filename, GIDOrErr.takeError()); 1933 unsigned GID = GIDOrErr.get(); 1934 outs() << format("%-d ", GID); 1935 1936 Expected<uint64_t> Size = C.getRawSize(); 1937 if (!Size) 1938 report_error(Filename, Size.takeError()); 1939 outs() << format("%6" PRId64, Size.get()) << " "; 1940 1941 StringRef RawLastModified = C.getRawLastModified(); 1942 unsigned Seconds; 1943 if (RawLastModified.getAsInteger(10, Seconds)) 1944 outs() << "(date: \"" << RawLastModified 1945 << "\" contains non-decimal chars) "; 1946 else { 1947 // Since ctime(3) returns a 26 character string of the form: 1948 // "Sun Sep 16 01:03:52 1973\n\0" 1949 // just print 24 characters. 1950 time_t t = Seconds; 1951 outs() << format("%.24s ", ctime(&t)); 1952 } 1953 1954 StringRef Name = ""; 1955 Expected<StringRef> NameOrErr = C.getName(); 1956 if (!NameOrErr) { 1957 consumeError(NameOrErr.takeError()); 1958 Expected<StringRef> RawNameOrErr = C.getRawName(); 1959 if (!RawNameOrErr) 1960 report_error(Filename, NameOrErr.takeError()); 1961 Name = RawNameOrErr.get(); 1962 } else { 1963 Name = NameOrErr.get(); 1964 } 1965 outs() << Name << "\n"; 1966 } 1967 1968 static void dumpObject(ObjectFile *O, const Archive *A = nullptr, 1969 const Archive::Child *C = nullptr) { 1970 // Avoid other output when using a raw option. 1971 if (!RawClangAST) { 1972 outs() << '\n'; 1973 if (A) 1974 outs() << A->getFileName() << "(" << O->getFileName() << ")"; 1975 else 1976 outs() << O->getFileName(); 1977 outs() << ":\tfile format " << O->getFileFormatName() << "\n\n"; 1978 } 1979 1980 StringRef ArchiveName = A ? A->getFileName() : ""; 1981 if (FileHeaders) 1982 printFileHeaders(O); 1983 if (ArchiveHeaders && !MachOOpt && C) 1984 printArchiveChild(ArchiveName, *C); 1985 if (Disassemble) 1986 disassembleObject(O, Relocations); 1987 if (Relocations && !Disassemble) 1988 printRelocations(O); 1989 if (DynamicRelocations) 1990 printDynamicRelocations(O); 1991 if (SectionHeaders) 1992 printSectionHeaders(O); 1993 if (SectionContents) 1994 printSectionContents(O); 1995 if (SymbolTable) 1996 printSymbolTable(O, ArchiveName); 1997 if (UnwindInfo) 1998 printUnwindInfo(O); 1999 if (PrivateHeaders || FirstPrivateHeader) 2000 printPrivateFileHeaders(O, FirstPrivateHeader); 2001 if (ExportsTrie) 2002 printExportsTrie(O); 2003 if (Rebase) 2004 printRebaseTable(O); 2005 if (Bind) 2006 printBindTable(O); 2007 if (LazyBind) 2008 printLazyBindTable(O); 2009 if (WeakBind) 2010 printWeakBindTable(O); 2011 if (RawClangAST) 2012 printRawClangAST(O); 2013 if (PrintFaultMaps) 2014 printFaultMaps(O); 2015 if (DwarfDumpType != DIDT_Null) { 2016 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O); 2017 // Dump the complete DWARF structure. 2018 DIDumpOptions DumpOpts; 2019 DumpOpts.DumpType = DwarfDumpType; 2020 DICtx->dump(outs(), DumpOpts); 2021 } 2022 } 2023 2024 static void dumpObject(const COFFImportFile *I, const Archive *A, 2025 const Archive::Child *C = nullptr) { 2026 StringRef ArchiveName = A ? A->getFileName() : ""; 2027 2028 // Avoid other output when using a raw option. 2029 if (!RawClangAST) 2030 outs() << '\n' 2031 << ArchiveName << "(" << I->getFileName() << ")" 2032 << ":\tfile format COFF-import-file" 2033 << "\n\n"; 2034 2035 if (ArchiveHeaders && !MachOOpt && C) 2036 printArchiveChild(ArchiveName, *C); 2037 if (SymbolTable) 2038 printCOFFSymbolTable(I); 2039 } 2040 2041 /// Dump each object file in \a a; 2042 static void dumpArchive(const Archive *A) { 2043 Error Err = Error::success(); 2044 for (auto &C : A->children(Err)) { 2045 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2046 if (!ChildOrErr) { 2047 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2048 report_error(A->getFileName(), C, std::move(E)); 2049 continue; 2050 } 2051 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 2052 dumpObject(O, A, &C); 2053 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get())) 2054 dumpObject(I, A, &C); 2055 else 2056 report_error(A->getFileName(), object_error::invalid_file_type); 2057 } 2058 if (Err) 2059 report_error(A->getFileName(), std::move(Err)); 2060 } 2061 2062 /// Open file and figure out how to dump it. 2063 static void dumpInput(StringRef file) { 2064 // If we are using the Mach-O specific object file parser, then let it parse 2065 // the file and process the command line options. So the -arch flags can 2066 // be used to select specific slices, etc. 2067 if (MachOOpt) { 2068 parseInputMachO(file); 2069 return; 2070 } 2071 2072 // Attempt to open the binary. 2073 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file); 2074 if (!BinaryOrErr) 2075 report_error(file, BinaryOrErr.takeError()); 2076 Binary &Binary = *BinaryOrErr.get().getBinary(); 2077 2078 if (Archive *A = dyn_cast<Archive>(&Binary)) 2079 dumpArchive(A); 2080 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary)) 2081 dumpObject(O); 2082 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary)) 2083 parseInputMachO(UB); 2084 else 2085 report_error(file, object_error::invalid_file_type); 2086 } 2087 2088 int main(int argc, char **argv) { 2089 InitLLVM X(argc, argv); 2090 2091 // Initialize targets and assembly printers/parsers. 2092 llvm::InitializeAllTargetInfos(); 2093 llvm::InitializeAllTargetMCs(); 2094 llvm::InitializeAllDisassemblers(); 2095 2096 // Register the target printer for --version. 2097 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 2098 2099 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 2100 2101 ToolName = argv[0]; 2102 2103 // Defaults to a.out if no filenames specified. 2104 if (InputFilenames.empty()) 2105 InputFilenames.push_back("a.out"); 2106 2107 if (AllHeaders) 2108 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations = 2109 SectionHeaders = SymbolTable = true; 2110 2111 if (DisassembleAll || PrintSource || PrintLines) 2112 Disassemble = true; 2113 2114 if (!Disassemble 2115 && !Relocations 2116 && !DynamicRelocations 2117 && !SectionHeaders 2118 && !SectionContents 2119 && !SymbolTable 2120 && !UnwindInfo 2121 && !PrivateHeaders 2122 && !FileHeaders 2123 && !FirstPrivateHeader 2124 && !ExportsTrie 2125 && !Rebase 2126 && !Bind 2127 && !LazyBind 2128 && !WeakBind 2129 && !RawClangAST 2130 && !(UniversalHeaders && MachOOpt) 2131 && !ArchiveHeaders 2132 && !(IndirectSymbols && MachOOpt) 2133 && !(DataInCode && MachOOpt) 2134 && !(LinkOptHints && MachOOpt) 2135 && !(InfoPlist && MachOOpt) 2136 && !(DylibsUsed && MachOOpt) 2137 && !(DylibId && MachOOpt) 2138 && !(ObjcMetaData && MachOOpt) 2139 && !(!FilterSections.empty() && MachOOpt) 2140 && !PrintFaultMaps 2141 && DwarfDumpType == DIDT_Null) { 2142 cl::PrintHelpMessage(); 2143 return 2; 2144 } 2145 2146 DisasmFuncsSet.insert(DisassembleFunctions.begin(), 2147 DisassembleFunctions.end()); 2148 2149 llvm::for_each(InputFilenames, dumpInput); 2150 2151 return EXIT_SUCCESS; 2152 } 2153