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