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 "COFFDump.h" 20 #include "ELFDump.h" 21 #include "MachODump.h" 22 #include "ObjdumpOptID.h" 23 #include "OffloadDump.h" 24 #include "SourcePrinter.h" 25 #include "WasmDump.h" 26 #include "XCOFFDump.h" 27 #include "llvm/ADT/IndexedMap.h" 28 #include "llvm/ADT/Optional.h" 29 #include "llvm/ADT/STLExtras.h" 30 #include "llvm/ADT/SetOperations.h" 31 #include "llvm/ADT/SmallSet.h" 32 #include "llvm/ADT/StringExtras.h" 33 #include "llvm/ADT/StringSet.h" 34 #include "llvm/ADT/Triple.h" 35 #include "llvm/ADT/Twine.h" 36 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 37 #include "llvm/DebugInfo/Symbolize/SymbolizableModule.h" 38 #include "llvm/DebugInfo/Symbolize/Symbolize.h" 39 #include "llvm/Debuginfod/BuildIDFetcher.h" 40 #include "llvm/Debuginfod/Debuginfod.h" 41 #include "llvm/Debuginfod/HTTPClient.h" 42 #include "llvm/Demangle/Demangle.h" 43 #include "llvm/MC/MCAsmInfo.h" 44 #include "llvm/MC/MCContext.h" 45 #include "llvm/MC/MCDisassembler/MCDisassembler.h" 46 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h" 47 #include "llvm/MC/MCInst.h" 48 #include "llvm/MC/MCInstPrinter.h" 49 #include "llvm/MC/MCInstrAnalysis.h" 50 #include "llvm/MC/MCInstrInfo.h" 51 #include "llvm/MC/MCObjectFileInfo.h" 52 #include "llvm/MC/MCRegisterInfo.h" 53 #include "llvm/MC/MCSubtargetInfo.h" 54 #include "llvm/MC/MCTargetOptions.h" 55 #include "llvm/MC/TargetRegistry.h" 56 #include "llvm/Object/Archive.h" 57 #include "llvm/Object/BuildID.h" 58 #include "llvm/Object/COFF.h" 59 #include "llvm/Object/COFFImportFile.h" 60 #include "llvm/Object/ELFObjectFile.h" 61 #include "llvm/Object/ELFTypes.h" 62 #include "llvm/Object/FaultMapParser.h" 63 #include "llvm/Object/MachO.h" 64 #include "llvm/Object/MachOUniversal.h" 65 #include "llvm/Object/ObjectFile.h" 66 #include "llvm/Object/OffloadBinary.h" 67 #include "llvm/Object/Wasm.h" 68 #include "llvm/Option/Arg.h" 69 #include "llvm/Option/ArgList.h" 70 #include "llvm/Option/Option.h" 71 #include "llvm/Support/Casting.h" 72 #include "llvm/Support/Debug.h" 73 #include "llvm/Support/Errc.h" 74 #include "llvm/Support/FileSystem.h" 75 #include "llvm/Support/Format.h" 76 #include "llvm/Support/FormatVariadic.h" 77 #include "llvm/Support/GraphWriter.h" 78 #include "llvm/Support/Host.h" 79 #include "llvm/Support/InitLLVM.h" 80 #include "llvm/Support/MemoryBuffer.h" 81 #include "llvm/Support/SourceMgr.h" 82 #include "llvm/Support/StringSaver.h" 83 #include "llvm/Support/TargetSelect.h" 84 #include "llvm/Support/WithColor.h" 85 #include "llvm/Support/raw_ostream.h" 86 #include <algorithm> 87 #include <cctype> 88 #include <cstring> 89 #include <system_error> 90 #include <unordered_map> 91 #include <utility> 92 93 using namespace llvm; 94 using namespace llvm::object; 95 using namespace llvm::objdump; 96 using namespace llvm::opt; 97 98 namespace { 99 100 class CommonOptTable : public opt::OptTable { 101 public: 102 CommonOptTable(ArrayRef<Info> OptionInfos, const char *Usage, 103 const char *Description) 104 : OptTable(OptionInfos), Usage(Usage), Description(Description) { 105 setGroupedShortOptions(true); 106 } 107 108 void printHelp(StringRef Argv0, bool ShowHidden = false) const { 109 Argv0 = sys::path::filename(Argv0); 110 opt::OptTable::printHelp(outs(), (Argv0 + Usage).str().c_str(), Description, 111 ShowHidden, ShowHidden); 112 // TODO Replace this with OptTable API once it adds extrahelp support. 113 outs() << "\nPass @FILE as argument to read options from FILE.\n"; 114 } 115 116 private: 117 const char *Usage; 118 const char *Description; 119 }; 120 121 // ObjdumpOptID is in ObjdumpOptID.h 122 123 #define PREFIX(NAME, VALUE) const char *const OBJDUMP_##NAME[] = VALUE; 124 #include "ObjdumpOpts.inc" 125 #undef PREFIX 126 127 static constexpr opt::OptTable::Info ObjdumpInfoTable[] = { 128 #define OBJDUMP_nullptr nullptr 129 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 130 HELPTEXT, METAVAR, VALUES) \ 131 {OBJDUMP_##PREFIX, NAME, HELPTEXT, \ 132 METAVAR, OBJDUMP_##ID, opt::Option::KIND##Class, \ 133 PARAM, FLAGS, OBJDUMP_##GROUP, \ 134 OBJDUMP_##ALIAS, ALIASARGS, VALUES}, 135 #include "ObjdumpOpts.inc" 136 #undef OPTION 137 #undef OBJDUMP_nullptr 138 }; 139 140 class ObjdumpOptTable : public CommonOptTable { 141 public: 142 ObjdumpOptTable() 143 : CommonOptTable(ObjdumpInfoTable, " [options] <input object files>", 144 "llvm object file dumper") {} 145 }; 146 147 enum OtoolOptID { 148 OTOOL_INVALID = 0, // This is not an option ID. 149 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 150 HELPTEXT, METAVAR, VALUES) \ 151 OTOOL_##ID, 152 #include "OtoolOpts.inc" 153 #undef OPTION 154 }; 155 156 #define PREFIX(NAME, VALUE) const char *const OTOOL_##NAME[] = VALUE; 157 #include "OtoolOpts.inc" 158 #undef PREFIX 159 160 static constexpr opt::OptTable::Info OtoolInfoTable[] = { 161 #define OTOOL_nullptr nullptr 162 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 163 HELPTEXT, METAVAR, VALUES) \ 164 {OTOOL_##PREFIX, NAME, HELPTEXT, \ 165 METAVAR, OTOOL_##ID, opt::Option::KIND##Class, \ 166 PARAM, FLAGS, OTOOL_##GROUP, \ 167 OTOOL_##ALIAS, ALIASARGS, VALUES}, 168 #include "OtoolOpts.inc" 169 #undef OPTION 170 #undef OTOOL_nullptr 171 }; 172 173 class OtoolOptTable : public CommonOptTable { 174 public: 175 OtoolOptTable() 176 : CommonOptTable(OtoolInfoTable, " [option...] [file...]", 177 "Mach-O object file displaying tool") {} 178 }; 179 180 } // namespace 181 182 #define DEBUG_TYPE "objdump" 183 184 static uint64_t AdjustVMA; 185 static bool AllHeaders; 186 static std::string ArchName; 187 bool objdump::ArchiveHeaders; 188 bool objdump::Demangle; 189 bool objdump::Disassemble; 190 bool objdump::DisassembleAll; 191 bool objdump::SymbolDescription; 192 static std::vector<std::string> DisassembleSymbols; 193 static bool DisassembleZeroes; 194 static std::vector<std::string> DisassemblerOptions; 195 DIDumpType objdump::DwarfDumpType; 196 static bool DynamicRelocations; 197 static bool FaultMapSection; 198 static bool FileHeaders; 199 bool objdump::SectionContents; 200 static std::vector<std::string> InputFilenames; 201 bool objdump::PrintLines; 202 static bool MachOOpt; 203 std::string objdump::MCPU; 204 std::vector<std::string> objdump::MAttrs; 205 bool objdump::ShowRawInsn; 206 bool objdump::LeadingAddr; 207 static bool Offloading; 208 static bool RawClangAST; 209 bool objdump::Relocations; 210 bool objdump::PrintImmHex; 211 bool objdump::PrivateHeaders; 212 std::vector<std::string> objdump::FilterSections; 213 bool objdump::SectionHeaders; 214 static bool ShowAllSymbols; 215 static bool ShowLMA; 216 bool objdump::PrintSource; 217 218 static uint64_t StartAddress; 219 static bool HasStartAddressFlag; 220 static uint64_t StopAddress = UINT64_MAX; 221 static bool HasStopAddressFlag; 222 223 bool objdump::SymbolTable; 224 static bool SymbolizeOperands; 225 static bool DynamicSymbolTable; 226 std::string objdump::TripleName; 227 bool objdump::UnwindInfo; 228 static bool Wide; 229 std::string objdump::Prefix; 230 uint32_t objdump::PrefixStrip; 231 232 DebugVarsFormat objdump::DbgVariables = DVDisabled; 233 234 int objdump::DbgIndent = 52; 235 236 static StringSet<> DisasmSymbolSet; 237 StringSet<> objdump::FoundSectionSet; 238 static StringRef ToolName; 239 240 std::unique_ptr<BuildIDFetcher> BIDFetcher; 241 ExitOnError ExitOnErr; 242 243 namespace { 244 struct FilterResult { 245 // True if the section should not be skipped. 246 bool Keep; 247 248 // True if the index counter should be incremented, even if the section should 249 // be skipped. For example, sections may be skipped if they are not included 250 // in the --section flag, but we still want those to count toward the section 251 // count. 252 bool IncrementIndex; 253 }; 254 } // namespace 255 256 static FilterResult checkSectionFilter(object::SectionRef S) { 257 if (FilterSections.empty()) 258 return {/*Keep=*/true, /*IncrementIndex=*/true}; 259 260 Expected<StringRef> SecNameOrErr = S.getName(); 261 if (!SecNameOrErr) { 262 consumeError(SecNameOrErr.takeError()); 263 return {/*Keep=*/false, /*IncrementIndex=*/false}; 264 } 265 StringRef SecName = *SecNameOrErr; 266 267 // StringSet does not allow empty key so avoid adding sections with 268 // no name (such as the section with index 0) here. 269 if (!SecName.empty()) 270 FoundSectionSet.insert(SecName); 271 272 // Only show the section if it's in the FilterSections list, but always 273 // increment so the indexing is stable. 274 return {/*Keep=*/is_contained(FilterSections, SecName), 275 /*IncrementIndex=*/true}; 276 } 277 278 SectionFilter objdump::ToolSectionFilter(object::ObjectFile const &O, 279 uint64_t *Idx) { 280 // Start at UINT64_MAX so that the first index returned after an increment is 281 // zero (after the unsigned wrap). 282 if (Idx) 283 *Idx = UINT64_MAX; 284 return SectionFilter( 285 [Idx](object::SectionRef S) { 286 FilterResult Result = checkSectionFilter(S); 287 if (Idx != nullptr && Result.IncrementIndex) 288 *Idx += 1; 289 return Result.Keep; 290 }, 291 O); 292 } 293 294 std::string objdump::getFileNameForError(const object::Archive::Child &C, 295 unsigned Index) { 296 Expected<StringRef> NameOrErr = C.getName(); 297 if (NameOrErr) 298 return std::string(NameOrErr.get()); 299 // If we have an error getting the name then we print the index of the archive 300 // member. Since we are already in an error state, we just ignore this error. 301 consumeError(NameOrErr.takeError()); 302 return "<file index: " + std::to_string(Index) + ">"; 303 } 304 305 void objdump::reportWarning(const Twine &Message, StringRef File) { 306 // Output order between errs() and outs() matters especially for archive 307 // files where the output is per member object. 308 outs().flush(); 309 WithColor::warning(errs(), ToolName) 310 << "'" << File << "': " << Message << "\n"; 311 } 312 313 [[noreturn]] void objdump::reportError(StringRef File, const Twine &Message) { 314 outs().flush(); 315 WithColor::error(errs(), ToolName) << "'" << File << "': " << Message << "\n"; 316 exit(1); 317 } 318 319 [[noreturn]] void objdump::reportError(Error E, StringRef FileName, 320 StringRef ArchiveName, 321 StringRef ArchitectureName) { 322 assert(E); 323 outs().flush(); 324 WithColor::error(errs(), ToolName); 325 if (ArchiveName != "") 326 errs() << ArchiveName << "(" << FileName << ")"; 327 else 328 errs() << "'" << FileName << "'"; 329 if (!ArchitectureName.empty()) 330 errs() << " (for architecture " << ArchitectureName << ")"; 331 errs() << ": "; 332 logAllUnhandledErrors(std::move(E), errs()); 333 exit(1); 334 } 335 336 static void reportCmdLineWarning(const Twine &Message) { 337 WithColor::warning(errs(), ToolName) << Message << "\n"; 338 } 339 340 [[noreturn]] static void reportCmdLineError(const Twine &Message) { 341 WithColor::error(errs(), ToolName) << Message << "\n"; 342 exit(1); 343 } 344 345 static void warnOnNoMatchForSections() { 346 SetVector<StringRef> MissingSections; 347 for (StringRef S : FilterSections) { 348 if (FoundSectionSet.count(S)) 349 return; 350 // User may specify a unnamed section. Don't warn for it. 351 if (!S.empty()) 352 MissingSections.insert(S); 353 } 354 355 // Warn only if no section in FilterSections is matched. 356 for (StringRef S : MissingSections) 357 reportCmdLineWarning("section '" + S + 358 "' mentioned in a -j/--section option, but not " 359 "found in any input file"); 360 } 361 362 static const Target *getTarget(const ObjectFile *Obj) { 363 // Figure out the target triple. 364 Triple TheTriple("unknown-unknown-unknown"); 365 if (TripleName.empty()) { 366 TheTriple = Obj->makeTriple(); 367 } else { 368 TheTriple.setTriple(Triple::normalize(TripleName)); 369 auto Arch = Obj->getArch(); 370 if (Arch == Triple::arm || Arch == Triple::armeb) 371 Obj->setARMSubArch(TheTriple); 372 } 373 374 // Get the target specific parser. 375 std::string Error; 376 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, 377 Error); 378 if (!TheTarget) 379 reportError(Obj->getFileName(), "can't find target: " + Error); 380 381 // Update the triple name and return the found target. 382 TripleName = TheTriple.getTriple(); 383 return TheTarget; 384 } 385 386 bool objdump::isRelocAddressLess(RelocationRef A, RelocationRef B) { 387 return A.getOffset() < B.getOffset(); 388 } 389 390 static Error getRelocationValueString(const RelocationRef &Rel, 391 SmallVectorImpl<char> &Result) { 392 const ObjectFile *Obj = Rel.getObject(); 393 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj)) 394 return getELFRelocationValueString(ELF, Rel, Result); 395 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj)) 396 return getCOFFRelocationValueString(COFF, Rel, Result); 397 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj)) 398 return getWasmRelocationValueString(Wasm, Rel, Result); 399 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj)) 400 return getMachORelocationValueString(MachO, Rel, Result); 401 if (auto *XCOFF = dyn_cast<XCOFFObjectFile>(Obj)) 402 return getXCOFFRelocationValueString(*XCOFF, Rel, Result); 403 llvm_unreachable("unknown object file format"); 404 } 405 406 /// Indicates whether this relocation should hidden when listing 407 /// relocations, usually because it is the trailing part of a multipart 408 /// relocation that will be printed as part of the leading relocation. 409 static bool getHidden(RelocationRef RelRef) { 410 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject()); 411 if (!MachO) 412 return false; 413 414 unsigned Arch = MachO->getArch(); 415 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 416 uint64_t Type = MachO->getRelocationType(Rel); 417 418 // On arches that use the generic relocations, GENERIC_RELOC_PAIR 419 // is always hidden. 420 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) 421 return Type == MachO::GENERIC_RELOC_PAIR; 422 423 if (Arch == Triple::x86_64) { 424 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows 425 // an X86_64_RELOC_SUBTRACTOR. 426 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) { 427 DataRefImpl RelPrev = Rel; 428 RelPrev.d.a--; 429 uint64_t PrevType = MachO->getRelocationType(RelPrev); 430 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR) 431 return true; 432 } 433 } 434 435 return false; 436 } 437 438 namespace { 439 440 /// Get the column at which we want to start printing the instruction 441 /// disassembly, taking into account anything which appears to the left of it. 442 unsigned getInstStartColumn(const MCSubtargetInfo &STI) { 443 return !ShowRawInsn ? 16 : STI.getTargetTriple().isX86() ? 40 : 24; 444 } 445 446 static bool isAArch64Elf(const ObjectFile &Obj) { 447 const auto *Elf = dyn_cast<ELFObjectFileBase>(&Obj); 448 return Elf && Elf->getEMachine() == ELF::EM_AARCH64; 449 } 450 451 static bool isArmElf(const ObjectFile &Obj) { 452 const auto *Elf = dyn_cast<ELFObjectFileBase>(&Obj); 453 return Elf && Elf->getEMachine() == ELF::EM_ARM; 454 } 455 456 static bool isCSKYElf(const ObjectFile &Obj) { 457 const auto *Elf = dyn_cast<ELFObjectFileBase>(&Obj); 458 return Elf && Elf->getEMachine() == ELF::EM_CSKY; 459 } 460 461 static bool hasMappingSymbols(const ObjectFile &Obj) { 462 return isArmElf(Obj) || isAArch64Elf(Obj) || isCSKYElf(Obj) ; 463 } 464 465 static void printRelocation(formatted_raw_ostream &OS, StringRef FileName, 466 const RelocationRef &Rel, uint64_t Address, 467 bool Is64Bits) { 468 StringRef Fmt = Is64Bits ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": "; 469 SmallString<16> Name; 470 SmallString<32> Val; 471 Rel.getTypeName(Name); 472 if (Error E = getRelocationValueString(Rel, Val)) 473 reportError(std::move(E), FileName); 474 OS << format(Fmt.data(), Address) << Name << "\t" << Val; 475 } 476 477 static void AlignToInstStartColumn(size_t Start, const MCSubtargetInfo &STI, 478 raw_ostream &OS) { 479 // The output of printInst starts with a tab. Print some spaces so that 480 // the tab has 1 column and advances to the target tab stop. 481 unsigned TabStop = getInstStartColumn(STI); 482 unsigned Column = OS.tell() - Start; 483 OS.indent(Column < TabStop - 1 ? TabStop - 1 - Column : 7 - Column % 8); 484 } 485 486 class PrettyPrinter { 487 public: 488 virtual ~PrettyPrinter() = default; 489 virtual void 490 printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 491 object::SectionedAddress Address, formatted_raw_ostream &OS, 492 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, 493 StringRef ObjectFilename, std::vector<RelocationRef> *Rels, 494 LiveVariablePrinter &LVP) { 495 if (SP && (PrintSource || PrintLines)) 496 SP->printSourceLine(OS, Address, ObjectFilename, LVP); 497 LVP.printBetweenInsts(OS, false); 498 499 size_t Start = OS.tell(); 500 if (LeadingAddr) 501 OS << format("%8" PRIx64 ":", Address.Address); 502 if (ShowRawInsn) { 503 OS << ' '; 504 dumpBytes(Bytes, OS); 505 } 506 507 AlignToInstStartColumn(Start, STI, OS); 508 509 if (MI) { 510 // See MCInstPrinter::printInst. On targets where a PC relative immediate 511 // is relative to the next instruction and the length of a MCInst is 512 // difficult to measure (x86), this is the address of the next 513 // instruction. 514 uint64_t Addr = 515 Address.Address + (STI.getTargetTriple().isX86() ? Bytes.size() : 0); 516 IP.printInst(MI, Addr, "", STI, OS); 517 } else 518 OS << "\t<unknown>"; 519 } 520 }; 521 PrettyPrinter PrettyPrinterInst; 522 523 class HexagonPrettyPrinter : public PrettyPrinter { 524 public: 525 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address, 526 formatted_raw_ostream &OS) { 527 uint32_t opcode = 528 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0]; 529 if (LeadingAddr) 530 OS << format("%8" PRIx64 ":", Address); 531 if (ShowRawInsn) { 532 OS << "\t"; 533 dumpBytes(Bytes.slice(0, 4), OS); 534 OS << format("\t%08" PRIx32, opcode); 535 } 536 } 537 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 538 object::SectionedAddress Address, formatted_raw_ostream &OS, 539 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, 540 StringRef ObjectFilename, std::vector<RelocationRef> *Rels, 541 LiveVariablePrinter &LVP) override { 542 if (SP && (PrintSource || PrintLines)) 543 SP->printSourceLine(OS, Address, ObjectFilename, LVP, ""); 544 if (!MI) { 545 printLead(Bytes, Address.Address, OS); 546 OS << " <unknown>"; 547 return; 548 } 549 std::string Buffer; 550 { 551 raw_string_ostream TempStream(Buffer); 552 IP.printInst(MI, Address.Address, "", STI, TempStream); 553 } 554 StringRef Contents(Buffer); 555 // Split off bundle attributes 556 auto PacketBundle = Contents.rsplit('\n'); 557 // Split off first instruction from the rest 558 auto HeadTail = PacketBundle.first.split('\n'); 559 auto Preamble = " { "; 560 auto Separator = ""; 561 562 // Hexagon's packets require relocations to be inline rather than 563 // clustered at the end of the packet. 564 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin(); 565 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end(); 566 auto PrintReloc = [&]() -> void { 567 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address.Address)) { 568 if (RelCur->getOffset() == Address.Address) { 569 printRelocation(OS, ObjectFilename, *RelCur, Address.Address, false); 570 return; 571 } 572 ++RelCur; 573 } 574 }; 575 576 while (!HeadTail.first.empty()) { 577 OS << Separator; 578 Separator = "\n"; 579 if (SP && (PrintSource || PrintLines)) 580 SP->printSourceLine(OS, Address, ObjectFilename, LVP, ""); 581 printLead(Bytes, Address.Address, OS); 582 OS << Preamble; 583 Preamble = " "; 584 StringRef Inst; 585 auto Duplex = HeadTail.first.split('\v'); 586 if (!Duplex.second.empty()) { 587 OS << Duplex.first; 588 OS << "; "; 589 Inst = Duplex.second; 590 } 591 else 592 Inst = HeadTail.first; 593 OS << Inst; 594 HeadTail = HeadTail.second.split('\n'); 595 if (HeadTail.first.empty()) 596 OS << " } " << PacketBundle.second; 597 PrintReloc(); 598 Bytes = Bytes.slice(4); 599 Address.Address += 4; 600 } 601 } 602 }; 603 HexagonPrettyPrinter HexagonPrettyPrinterInst; 604 605 class AMDGCNPrettyPrinter : public PrettyPrinter { 606 public: 607 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 608 object::SectionedAddress Address, formatted_raw_ostream &OS, 609 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, 610 StringRef ObjectFilename, std::vector<RelocationRef> *Rels, 611 LiveVariablePrinter &LVP) override { 612 if (SP && (PrintSource || PrintLines)) 613 SP->printSourceLine(OS, Address, ObjectFilename, LVP); 614 615 if (MI) { 616 SmallString<40> InstStr; 617 raw_svector_ostream IS(InstStr); 618 619 IP.printInst(MI, Address.Address, "", STI, IS); 620 621 OS << left_justify(IS.str(), 60); 622 } else { 623 // an unrecognized encoding - this is probably data so represent it 624 // using the .long directive, or .byte directive if fewer than 4 bytes 625 // remaining 626 if (Bytes.size() >= 4) { 627 OS << format("\t.long 0x%08" PRIx32 " ", 628 support::endian::read32<support::little>(Bytes.data())); 629 OS.indent(42); 630 } else { 631 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]); 632 for (unsigned int i = 1; i < Bytes.size(); i++) 633 OS << format(", 0x%02" PRIx8, Bytes[i]); 634 OS.indent(55 - (6 * Bytes.size())); 635 } 636 } 637 638 OS << format("// %012" PRIX64 ":", Address.Address); 639 if (Bytes.size() >= 4) { 640 // D should be casted to uint32_t here as it is passed by format to 641 // snprintf as vararg. 642 for (uint32_t D : makeArrayRef( 643 reinterpret_cast<const support::little32_t *>(Bytes.data()), 644 Bytes.size() / 4)) 645 OS << format(" %08" PRIX32, D); 646 } else { 647 for (unsigned char B : Bytes) 648 OS << format(" %02" PRIX8, B); 649 } 650 651 if (!Annot.empty()) 652 OS << " // " << Annot; 653 } 654 }; 655 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst; 656 657 class BPFPrettyPrinter : public PrettyPrinter { 658 public: 659 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 660 object::SectionedAddress Address, formatted_raw_ostream &OS, 661 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, 662 StringRef ObjectFilename, std::vector<RelocationRef> *Rels, 663 LiveVariablePrinter &LVP) override { 664 if (SP && (PrintSource || PrintLines)) 665 SP->printSourceLine(OS, Address, ObjectFilename, LVP); 666 if (LeadingAddr) 667 OS << format("%8" PRId64 ":", Address.Address / 8); 668 if (ShowRawInsn) { 669 OS << "\t"; 670 dumpBytes(Bytes, OS); 671 } 672 if (MI) 673 IP.printInst(MI, Address.Address, "", STI, OS); 674 else 675 OS << "\t<unknown>"; 676 } 677 }; 678 BPFPrettyPrinter BPFPrettyPrinterInst; 679 680 class ARMPrettyPrinter : public PrettyPrinter { 681 public: 682 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 683 object::SectionedAddress Address, formatted_raw_ostream &OS, 684 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, 685 StringRef ObjectFilename, std::vector<RelocationRef> *Rels, 686 LiveVariablePrinter &LVP) override { 687 if (SP && (PrintSource || PrintLines)) 688 SP->printSourceLine(OS, Address, ObjectFilename, LVP); 689 LVP.printBetweenInsts(OS, false); 690 691 size_t Start = OS.tell(); 692 if (LeadingAddr) 693 OS << format("%8" PRIx64 ":", Address.Address); 694 if (ShowRawInsn) { 695 size_t Pos = 0, End = Bytes.size(); 696 if (STI.checkFeatures("+thumb-mode")) { 697 for (; Pos + 2 <= End; Pos += 2) 698 OS << ' ' 699 << format_hex_no_prefix( 700 llvm::support::endian::read<uint16_t>( 701 Bytes.data() + Pos, InstructionEndianness), 702 4); 703 } else { 704 for (; Pos + 4 <= End; Pos += 4) 705 OS << ' ' 706 << format_hex_no_prefix( 707 llvm::support::endian::read<uint32_t>( 708 Bytes.data() + Pos, InstructionEndianness), 709 8); 710 } 711 if (Pos < End) { 712 OS << ' '; 713 dumpBytes(Bytes.slice(Pos), OS); 714 } 715 } 716 717 AlignToInstStartColumn(Start, STI, OS); 718 719 if (MI) { 720 IP.printInst(MI, Address.Address, "", STI, OS); 721 } else 722 OS << "\t<unknown>"; 723 } 724 725 void setInstructionEndianness(llvm::support::endianness Endianness) { 726 InstructionEndianness = Endianness; 727 } 728 729 private: 730 llvm::support::endianness InstructionEndianness = llvm::support::little; 731 }; 732 ARMPrettyPrinter ARMPrettyPrinterInst; 733 734 class AArch64PrettyPrinter : public PrettyPrinter { 735 public: 736 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 737 object::SectionedAddress Address, formatted_raw_ostream &OS, 738 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, 739 StringRef ObjectFilename, std::vector<RelocationRef> *Rels, 740 LiveVariablePrinter &LVP) override { 741 if (SP && (PrintSource || PrintLines)) 742 SP->printSourceLine(OS, Address, ObjectFilename, LVP); 743 LVP.printBetweenInsts(OS, false); 744 745 size_t Start = OS.tell(); 746 if (LeadingAddr) 747 OS << format("%8" PRIx64 ":", Address.Address); 748 if (ShowRawInsn) { 749 size_t Pos = 0, End = Bytes.size(); 750 for (; Pos + 4 <= End; Pos += 4) 751 OS << ' ' 752 << format_hex_no_prefix( 753 llvm::support::endian::read<uint32_t>(Bytes.data() + Pos, 754 llvm::support::little), 755 8); 756 if (Pos < End) { 757 OS << ' '; 758 dumpBytes(Bytes.slice(Pos), OS); 759 } 760 } 761 762 AlignToInstStartColumn(Start, STI, OS); 763 764 if (MI) { 765 IP.printInst(MI, Address.Address, "", STI, OS); 766 } else 767 OS << "\t<unknown>"; 768 } 769 }; 770 AArch64PrettyPrinter AArch64PrettyPrinterInst; 771 772 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) { 773 switch(Triple.getArch()) { 774 default: 775 return PrettyPrinterInst; 776 case Triple::hexagon: 777 return HexagonPrettyPrinterInst; 778 case Triple::amdgcn: 779 return AMDGCNPrettyPrinterInst; 780 case Triple::bpfel: 781 case Triple::bpfeb: 782 return BPFPrettyPrinterInst; 783 case Triple::arm: 784 case Triple::armeb: 785 case Triple::thumb: 786 case Triple::thumbeb: 787 return ARMPrettyPrinterInst; 788 case Triple::aarch64: 789 case Triple::aarch64_be: 790 case Triple::aarch64_32: 791 return AArch64PrettyPrinterInst; 792 } 793 } 794 } 795 796 static uint8_t getElfSymbolType(const ObjectFile &Obj, const SymbolRef &Sym) { 797 assert(Obj.isELF()); 798 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(&Obj)) 799 return unwrapOrError(Elf32LEObj->getSymbol(Sym.getRawDataRefImpl()), 800 Obj.getFileName()) 801 ->getType(); 802 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(&Obj)) 803 return unwrapOrError(Elf64LEObj->getSymbol(Sym.getRawDataRefImpl()), 804 Obj.getFileName()) 805 ->getType(); 806 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(&Obj)) 807 return unwrapOrError(Elf32BEObj->getSymbol(Sym.getRawDataRefImpl()), 808 Obj.getFileName()) 809 ->getType(); 810 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(&Obj)) 811 return unwrapOrError(Elf64BEObj->getSymbol(Sym.getRawDataRefImpl()), 812 Obj.getFileName()) 813 ->getType(); 814 llvm_unreachable("Unsupported binary format"); 815 } 816 817 template <class ELFT> 818 static void 819 addDynamicElfSymbols(const ELFObjectFile<ELFT> &Obj, 820 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { 821 for (auto Symbol : Obj.getDynamicSymbolIterators()) { 822 uint8_t SymbolType = Symbol.getELFType(); 823 if (SymbolType == ELF::STT_SECTION) 824 continue; 825 826 uint64_t Address = unwrapOrError(Symbol.getAddress(), Obj.getFileName()); 827 // ELFSymbolRef::getAddress() returns size instead of value for common 828 // symbols which is not desirable for disassembly output. Overriding. 829 if (SymbolType == ELF::STT_COMMON) 830 Address = unwrapOrError(Obj.getSymbol(Symbol.getRawDataRefImpl()), 831 Obj.getFileName()) 832 ->st_value; 833 834 StringRef Name = unwrapOrError(Symbol.getName(), Obj.getFileName()); 835 if (Name.empty()) 836 continue; 837 838 section_iterator SecI = 839 unwrapOrError(Symbol.getSection(), Obj.getFileName()); 840 if (SecI == Obj.section_end()) 841 continue; 842 843 AllSymbols[*SecI].emplace_back(Address, Name, SymbolType); 844 } 845 } 846 847 static void 848 addDynamicElfSymbols(const ELFObjectFileBase &Obj, 849 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { 850 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(&Obj)) 851 addDynamicElfSymbols(*Elf32LEObj, AllSymbols); 852 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(&Obj)) 853 addDynamicElfSymbols(*Elf64LEObj, AllSymbols); 854 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(&Obj)) 855 addDynamicElfSymbols(*Elf32BEObj, AllSymbols); 856 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(&Obj)) 857 addDynamicElfSymbols(*Elf64BEObj, AllSymbols); 858 else 859 llvm_unreachable("Unsupported binary format"); 860 } 861 862 static Optional<SectionRef> getWasmCodeSection(const WasmObjectFile &Obj) { 863 for (auto SecI : Obj.sections()) { 864 const WasmSection &Section = Obj.getWasmSection(SecI); 865 if (Section.Type == wasm::WASM_SEC_CODE) 866 return SecI; 867 } 868 return None; 869 } 870 871 static void 872 addMissingWasmCodeSymbols(const WasmObjectFile &Obj, 873 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { 874 Optional<SectionRef> Section = getWasmCodeSection(Obj); 875 if (!Section) 876 return; 877 SectionSymbolsTy &Symbols = AllSymbols[*Section]; 878 879 std::set<uint64_t> SymbolAddresses; 880 for (const auto &Sym : Symbols) 881 SymbolAddresses.insert(Sym.Addr); 882 883 for (const wasm::WasmFunction &Function : Obj.functions()) { 884 uint64_t Address = Function.CodeSectionOffset; 885 // Only add fallback symbols for functions not already present in the symbol 886 // table. 887 if (SymbolAddresses.count(Address)) 888 continue; 889 // This function has no symbol, so it should have no SymbolName. 890 assert(Function.SymbolName.empty()); 891 // We use DebugName for the name, though it may be empty if there is no 892 // "name" custom section, or that section is missing a name for this 893 // function. 894 StringRef Name = Function.DebugName; 895 Symbols.emplace_back(Address, Name, ELF::STT_NOTYPE); 896 } 897 } 898 899 static void addPltEntries(const ObjectFile &Obj, 900 std::map<SectionRef, SectionSymbolsTy> &AllSymbols, 901 StringSaver &Saver) { 902 Optional<SectionRef> Plt; 903 for (const SectionRef &Section : Obj.sections()) { 904 Expected<StringRef> SecNameOrErr = Section.getName(); 905 if (!SecNameOrErr) { 906 consumeError(SecNameOrErr.takeError()); 907 continue; 908 } 909 if (*SecNameOrErr == ".plt") 910 Plt = Section; 911 } 912 if (!Plt) 913 return; 914 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(&Obj)) { 915 for (auto PltEntry : ElfObj->getPltAddresses()) { 916 if (PltEntry.first) { 917 SymbolRef Symbol(*PltEntry.first, ElfObj); 918 uint8_t SymbolType = getElfSymbolType(Obj, Symbol); 919 if (Expected<StringRef> NameOrErr = Symbol.getName()) { 920 if (!NameOrErr->empty()) 921 AllSymbols[*Plt].emplace_back( 922 PltEntry.second, Saver.save((*NameOrErr + "@plt").str()), 923 SymbolType); 924 continue; 925 } else { 926 // The warning has been reported in disassembleObject(). 927 consumeError(NameOrErr.takeError()); 928 } 929 } 930 reportWarning("PLT entry at 0x" + Twine::utohexstr(PltEntry.second) + 931 " references an invalid symbol", 932 Obj.getFileName()); 933 } 934 } 935 } 936 937 // Normally the disassembly output will skip blocks of zeroes. This function 938 // returns the number of zero bytes that can be skipped when dumping the 939 // disassembly of the instructions in Buf. 940 static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) { 941 // Find the number of leading zeroes. 942 size_t N = 0; 943 while (N < Buf.size() && !Buf[N]) 944 ++N; 945 946 // We may want to skip blocks of zero bytes, but unless we see 947 // at least 8 of them in a row. 948 if (N < 8) 949 return 0; 950 951 // We skip zeroes in multiples of 4 because do not want to truncate an 952 // instruction if it starts with a zero byte. 953 return N & ~0x3; 954 } 955 956 // Returns a map from sections to their relocations. 957 static std::map<SectionRef, std::vector<RelocationRef>> 958 getRelocsMap(object::ObjectFile const &Obj) { 959 std::map<SectionRef, std::vector<RelocationRef>> Ret; 960 uint64_t I = (uint64_t)-1; 961 for (SectionRef Sec : Obj.sections()) { 962 ++I; 963 Expected<section_iterator> RelocatedOrErr = Sec.getRelocatedSection(); 964 if (!RelocatedOrErr) 965 reportError(Obj.getFileName(), 966 "section (" + Twine(I) + 967 "): failed to get a relocated section: " + 968 toString(RelocatedOrErr.takeError())); 969 970 section_iterator Relocated = *RelocatedOrErr; 971 if (Relocated == Obj.section_end() || !checkSectionFilter(*Relocated).Keep) 972 continue; 973 std::vector<RelocationRef> &V = Ret[*Relocated]; 974 append_range(V, Sec.relocations()); 975 // Sort relocations by address. 976 llvm::stable_sort(V, isRelocAddressLess); 977 } 978 return Ret; 979 } 980 981 // Used for --adjust-vma to check if address should be adjusted by the 982 // specified value for a given section. 983 // For ELF we do not adjust non-allocatable sections like debug ones, 984 // because they are not loadable. 985 // TODO: implement for other file formats. 986 static bool shouldAdjustVA(const SectionRef &Section) { 987 const ObjectFile *Obj = Section.getObject(); 988 if (Obj->isELF()) 989 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC; 990 return false; 991 } 992 993 994 typedef std::pair<uint64_t, char> MappingSymbolPair; 995 static char getMappingSymbolKind(ArrayRef<MappingSymbolPair> MappingSymbols, 996 uint64_t Address) { 997 auto It = 998 partition_point(MappingSymbols, [Address](const MappingSymbolPair &Val) { 999 return Val.first <= Address; 1000 }); 1001 // Return zero for any address before the first mapping symbol; this means 1002 // we should use the default disassembly mode, depending on the target. 1003 if (It == MappingSymbols.begin()) 1004 return '\x00'; 1005 return (It - 1)->second; 1006 } 1007 1008 static uint64_t dumpARMELFData(uint64_t SectionAddr, uint64_t Index, 1009 uint64_t End, const ObjectFile &Obj, 1010 ArrayRef<uint8_t> Bytes, 1011 ArrayRef<MappingSymbolPair> MappingSymbols, 1012 const MCSubtargetInfo &STI, raw_ostream &OS) { 1013 support::endianness Endian = 1014 Obj.isLittleEndian() ? support::little : support::big; 1015 size_t Start = OS.tell(); 1016 OS << format("%8" PRIx64 ": ", SectionAddr + Index); 1017 if (Index + 4 <= End) { 1018 dumpBytes(Bytes.slice(Index, 4), OS); 1019 AlignToInstStartColumn(Start, STI, OS); 1020 OS << "\t.word\t" 1021 << format_hex(support::endian::read32(Bytes.data() + Index, Endian), 1022 10); 1023 return 4; 1024 } 1025 if (Index + 2 <= End) { 1026 dumpBytes(Bytes.slice(Index, 2), OS); 1027 AlignToInstStartColumn(Start, STI, OS); 1028 OS << "\t.short\t" 1029 << format_hex(support::endian::read16(Bytes.data() + Index, Endian), 6); 1030 return 2; 1031 } 1032 dumpBytes(Bytes.slice(Index, 1), OS); 1033 AlignToInstStartColumn(Start, STI, OS); 1034 OS << "\t.byte\t" << format_hex(Bytes[Index], 4); 1035 return 1; 1036 } 1037 1038 static void dumpELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End, 1039 ArrayRef<uint8_t> Bytes) { 1040 // print out data up to 8 bytes at a time in hex and ascii 1041 uint8_t AsciiData[9] = {'\0'}; 1042 uint8_t Byte; 1043 int NumBytes = 0; 1044 1045 for (; Index < End; ++Index) { 1046 if (NumBytes == 0) 1047 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 1048 Byte = Bytes.slice(Index)[0]; 1049 outs() << format(" %02x", Byte); 1050 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.'; 1051 1052 uint8_t IndentOffset = 0; 1053 NumBytes++; 1054 if (Index == End - 1 || NumBytes > 8) { 1055 // Indent the space for less than 8 bytes data. 1056 // 2 spaces for byte and one for space between bytes 1057 IndentOffset = 3 * (8 - NumBytes); 1058 for (int Excess = NumBytes; Excess < 8; Excess++) 1059 AsciiData[Excess] = '\0'; 1060 NumBytes = 8; 1061 } 1062 if (NumBytes == 8) { 1063 AsciiData[8] = '\0'; 1064 outs() << std::string(IndentOffset, ' ') << " "; 1065 outs() << reinterpret_cast<char *>(AsciiData); 1066 outs() << '\n'; 1067 NumBytes = 0; 1068 } 1069 } 1070 } 1071 1072 SymbolInfoTy objdump::createSymbolInfo(const ObjectFile &Obj, 1073 const SymbolRef &Symbol) { 1074 const StringRef FileName = Obj.getFileName(); 1075 const uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName); 1076 const StringRef Name = unwrapOrError(Symbol.getName(), FileName); 1077 1078 if (Obj.isXCOFF() && SymbolDescription) { 1079 const auto &XCOFFObj = cast<XCOFFObjectFile>(Obj); 1080 DataRefImpl SymbolDRI = Symbol.getRawDataRefImpl(); 1081 1082 const uint32_t SymbolIndex = XCOFFObj.getSymbolIndex(SymbolDRI.p); 1083 Optional<XCOFF::StorageMappingClass> Smc = 1084 getXCOFFSymbolCsectSMC(XCOFFObj, Symbol); 1085 return SymbolInfoTy(Addr, Name, Smc, SymbolIndex, 1086 isLabel(XCOFFObj, Symbol)); 1087 } else if (Obj.isXCOFF()) { 1088 const SymbolRef::Type SymType = unwrapOrError(Symbol.getType(), FileName); 1089 return SymbolInfoTy(Addr, Name, SymType, true); 1090 } else 1091 return SymbolInfoTy(Addr, Name, 1092 Obj.isELF() ? getElfSymbolType(Obj, Symbol) 1093 : (uint8_t)ELF::STT_NOTYPE); 1094 } 1095 1096 static SymbolInfoTy createDummySymbolInfo(const ObjectFile &Obj, 1097 const uint64_t Addr, StringRef &Name, 1098 uint8_t Type) { 1099 if (Obj.isXCOFF() && SymbolDescription) 1100 return SymbolInfoTy(Addr, Name, None, None, false); 1101 else 1102 return SymbolInfoTy(Addr, Name, Type); 1103 } 1104 1105 static void 1106 collectBBAddrMapLabels(const std::unordered_map<uint64_t, BBAddrMap> &AddrToBBAddrMap, 1107 uint64_t SectionAddr, uint64_t Start, uint64_t End, 1108 std::unordered_map<uint64_t, std::vector<std::string>> &Labels) { 1109 if (AddrToBBAddrMap.empty()) 1110 return; 1111 Labels.clear(); 1112 uint64_t StartAddress = SectionAddr + Start; 1113 uint64_t EndAddress = SectionAddr + End; 1114 auto Iter = AddrToBBAddrMap.find(StartAddress); 1115 if (Iter == AddrToBBAddrMap.end()) 1116 return; 1117 for (unsigned I = 0, Size = Iter->second.BBEntries.size(); I < Size; ++I) { 1118 uint64_t BBAddress = Iter->second.BBEntries[I].Offset + Iter->second.Addr; 1119 if (BBAddress >= EndAddress) 1120 continue; 1121 Labels[BBAddress].push_back(("BB" + Twine(I)).str()); 1122 } 1123 } 1124 1125 static void collectLocalBranchTargets( 1126 ArrayRef<uint8_t> Bytes, const MCInstrAnalysis *MIA, MCDisassembler *DisAsm, 1127 MCInstPrinter *IP, const MCSubtargetInfo *STI, uint64_t SectionAddr, 1128 uint64_t Start, uint64_t End, std::unordered_map<uint64_t, std::string> &Labels) { 1129 // So far only supports PowerPC and X86. 1130 if (!STI->getTargetTriple().isPPC() && !STI->getTargetTriple().isX86()) 1131 return; 1132 1133 Labels.clear(); 1134 unsigned LabelCount = 0; 1135 Start += SectionAddr; 1136 End += SectionAddr; 1137 uint64_t Index = Start; 1138 while (Index < End) { 1139 // Disassemble a real instruction and record function-local branch labels. 1140 MCInst Inst; 1141 uint64_t Size; 1142 ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index - SectionAddr); 1143 bool Disassembled = 1144 DisAsm->getInstruction(Inst, Size, ThisBytes, Index, nulls()); 1145 if (Size == 0) 1146 Size = std::min<uint64_t>(ThisBytes.size(), 1147 DisAsm->suggestBytesToSkip(ThisBytes, Index)); 1148 1149 if (Disassembled && MIA) { 1150 uint64_t Target; 1151 bool TargetKnown = MIA->evaluateBranch(Inst, Index, Size, Target); 1152 // On PowerPC, if the address of a branch is the same as the target, it 1153 // means that it's a function call. Do not mark the label for this case. 1154 if (TargetKnown && (Target >= Start && Target < End) && 1155 !Labels.count(Target) && 1156 !(STI->getTargetTriple().isPPC() && Target == Index)) 1157 Labels[Target] = ("L" + Twine(LabelCount++)).str(); 1158 } 1159 Index += Size; 1160 } 1161 } 1162 1163 // Create an MCSymbolizer for the target and add it to the MCDisassembler. 1164 // This is currently only used on AMDGPU, and assumes the format of the 1165 // void * argument passed to AMDGPU's createMCSymbolizer. 1166 static void addSymbolizer( 1167 MCContext &Ctx, const Target *Target, StringRef TripleName, 1168 MCDisassembler *DisAsm, uint64_t SectionAddr, ArrayRef<uint8_t> Bytes, 1169 SectionSymbolsTy &Symbols, 1170 std::vector<std::unique_ptr<std::string>> &SynthesizedLabelNames) { 1171 1172 std::unique_ptr<MCRelocationInfo> RelInfo( 1173 Target->createMCRelocationInfo(TripleName, Ctx)); 1174 if (!RelInfo) 1175 return; 1176 std::unique_ptr<MCSymbolizer> Symbolizer(Target->createMCSymbolizer( 1177 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo))); 1178 MCSymbolizer *SymbolizerPtr = &*Symbolizer; 1179 DisAsm->setSymbolizer(std::move(Symbolizer)); 1180 1181 if (!SymbolizeOperands) 1182 return; 1183 1184 // Synthesize labels referenced by branch instructions by 1185 // disassembling, discarding the output, and collecting the referenced 1186 // addresses from the symbolizer. 1187 for (size_t Index = 0; Index != Bytes.size();) { 1188 MCInst Inst; 1189 uint64_t Size; 1190 ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index - SectionAddr); 1191 DisAsm->getInstruction(Inst, Size, ThisBytes, Index, nulls()); 1192 if (Size == 0) 1193 Size = std::min<uint64_t>(ThisBytes.size(), 1194 DisAsm->suggestBytesToSkip(ThisBytes, Index)); 1195 Index += Size; 1196 } 1197 ArrayRef<uint64_t> LabelAddrsRef = SymbolizerPtr->getReferencedAddresses(); 1198 // Copy and sort to remove duplicates. 1199 std::vector<uint64_t> LabelAddrs; 1200 LabelAddrs.insert(LabelAddrs.end(), LabelAddrsRef.begin(), 1201 LabelAddrsRef.end()); 1202 llvm::sort(LabelAddrs); 1203 LabelAddrs.resize(std::unique(LabelAddrs.begin(), LabelAddrs.end()) - 1204 LabelAddrs.begin()); 1205 // Add the labels. 1206 for (unsigned LabelNum = 0; LabelNum != LabelAddrs.size(); ++LabelNum) { 1207 auto Name = std::make_unique<std::string>(); 1208 *Name = (Twine("L") + Twine(LabelNum)).str(); 1209 SynthesizedLabelNames.push_back(std::move(Name)); 1210 Symbols.push_back(SymbolInfoTy( 1211 LabelAddrs[LabelNum], *SynthesizedLabelNames.back(), ELF::STT_NOTYPE)); 1212 } 1213 llvm::stable_sort(Symbols); 1214 // Recreate the symbolizer with the new symbols list. 1215 RelInfo.reset(Target->createMCRelocationInfo(TripleName, Ctx)); 1216 Symbolizer.reset(Target->createMCSymbolizer( 1217 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo))); 1218 DisAsm->setSymbolizer(std::move(Symbolizer)); 1219 } 1220 1221 static StringRef getSegmentName(const MachOObjectFile *MachO, 1222 const SectionRef &Section) { 1223 if (MachO) { 1224 DataRefImpl DR = Section.getRawDataRefImpl(); 1225 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 1226 return SegmentName; 1227 } 1228 return ""; 1229 } 1230 1231 static void emitPostInstructionInfo(formatted_raw_ostream &FOS, 1232 const MCAsmInfo &MAI, 1233 const MCSubtargetInfo &STI, 1234 StringRef Comments, 1235 LiveVariablePrinter &LVP) { 1236 do { 1237 if (!Comments.empty()) { 1238 // Emit a line of comments. 1239 StringRef Comment; 1240 std::tie(Comment, Comments) = Comments.split('\n'); 1241 // MAI.getCommentColumn() assumes that instructions are printed at the 1242 // position of 8, while getInstStartColumn() returns the actual position. 1243 unsigned CommentColumn = 1244 MAI.getCommentColumn() - 8 + getInstStartColumn(STI); 1245 FOS.PadToColumn(CommentColumn); 1246 FOS << MAI.getCommentString() << ' ' << Comment; 1247 } 1248 LVP.printAfterInst(FOS); 1249 FOS << '\n'; 1250 } while (!Comments.empty()); 1251 FOS.flush(); 1252 } 1253 1254 static void createFakeELFSections(ObjectFile &Obj) { 1255 assert(Obj.isELF()); 1256 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(&Obj)) 1257 Elf32LEObj->createFakeSections(); 1258 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(&Obj)) 1259 Elf64LEObj->createFakeSections(); 1260 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(&Obj)) 1261 Elf32BEObj->createFakeSections(); 1262 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(&Obj)) 1263 Elf64BEObj->createFakeSections(); 1264 else 1265 llvm_unreachable("Unsupported binary format"); 1266 } 1267 1268 // Tries to fetch a more complete version of the given object file using its 1269 // Build ID. Returns None if nothing was found. 1270 static Optional<OwningBinary<Binary>> 1271 fetchBinaryByBuildID(const ObjectFile &Obj) { 1272 Optional<object::BuildIDRef> BuildID = getBuildID(&Obj); 1273 if (!BuildID) 1274 return None; 1275 Optional<std::string> Path = BIDFetcher->fetch(*BuildID); 1276 if (!Path) 1277 return None; 1278 Expected<OwningBinary<Binary>> DebugBinary = createBinary(*Path); 1279 if (!DebugBinary) { 1280 reportWarning(toString(DebugBinary.takeError()), *Path); 1281 return None; 1282 } 1283 return std::move(*DebugBinary); 1284 } 1285 1286 static void disassembleObject(const Target *TheTarget, ObjectFile &Obj, 1287 MCContext &Ctx, MCDisassembler *PrimaryDisAsm, 1288 MCDisassembler *SecondaryDisAsm, 1289 const MCInstrAnalysis *MIA, MCInstPrinter *IP, 1290 const MCSubtargetInfo *PrimarySTI, 1291 const MCSubtargetInfo *SecondarySTI, 1292 PrettyPrinter &PIP, SourcePrinter &SP, 1293 bool InlineRelocs) { 1294 const MCSubtargetInfo *STI = PrimarySTI; 1295 MCDisassembler *DisAsm = PrimaryDisAsm; 1296 bool PrimaryIsThumb = false; 1297 if (isArmElf(Obj)) 1298 PrimaryIsThumb = STI->checkFeatures("+thumb-mode"); 1299 1300 std::map<SectionRef, std::vector<RelocationRef>> RelocMap; 1301 if (InlineRelocs) 1302 RelocMap = getRelocsMap(Obj); 1303 bool Is64Bits = Obj.getBytesInAddress() > 4; 1304 1305 // Create a mapping from virtual address to symbol name. This is used to 1306 // pretty print the symbols while disassembling. 1307 std::map<SectionRef, SectionSymbolsTy> AllSymbols; 1308 SectionSymbolsTy AbsoluteSymbols; 1309 const StringRef FileName = Obj.getFileName(); 1310 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(&Obj); 1311 for (const SymbolRef &Symbol : Obj.symbols()) { 1312 Expected<StringRef> NameOrErr = Symbol.getName(); 1313 if (!NameOrErr) { 1314 reportWarning(toString(NameOrErr.takeError()), FileName); 1315 continue; 1316 } 1317 if (NameOrErr->empty() && !(Obj.isXCOFF() && SymbolDescription)) 1318 continue; 1319 1320 if (Obj.isELF() && getElfSymbolType(Obj, Symbol) == ELF::STT_SECTION) 1321 continue; 1322 1323 if (MachO) { 1324 // __mh_(execute|dylib|dylinker|bundle|preload|object)_header are special 1325 // symbols that support MachO header introspection. They do not bind to 1326 // code locations and are irrelevant for disassembly. 1327 if (NameOrErr->startswith("__mh_") && NameOrErr->endswith("_header")) 1328 continue; 1329 // Don't ask a Mach-O STAB symbol for its section unless you know that 1330 // STAB symbol's section field refers to a valid section index. Otherwise 1331 // the symbol may error trying to load a section that does not exist. 1332 DataRefImpl SymDRI = Symbol.getRawDataRefImpl(); 1333 uint8_t NType = (MachO->is64Bit() ? 1334 MachO->getSymbol64TableEntry(SymDRI).n_type: 1335 MachO->getSymbolTableEntry(SymDRI).n_type); 1336 if (NType & MachO::N_STAB) 1337 continue; 1338 } 1339 1340 section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName); 1341 if (SecI != Obj.section_end()) 1342 AllSymbols[*SecI].push_back(createSymbolInfo(Obj, Symbol)); 1343 else 1344 AbsoluteSymbols.push_back(createSymbolInfo(Obj, Symbol)); 1345 } 1346 1347 if (AllSymbols.empty() && Obj.isELF()) 1348 addDynamicElfSymbols(cast<ELFObjectFileBase>(Obj), AllSymbols); 1349 1350 if (Obj.isWasm()) 1351 addMissingWasmCodeSymbols(cast<WasmObjectFile>(Obj), AllSymbols); 1352 1353 if (Obj.isELF() && Obj.sections().empty()) 1354 createFakeELFSections(Obj); 1355 1356 BumpPtrAllocator A; 1357 StringSaver Saver(A); 1358 addPltEntries(Obj, AllSymbols, Saver); 1359 1360 // Create a mapping from virtual address to section. An empty section can 1361 // cause more than one section at the same address. Sort such sections to be 1362 // before same-addressed non-empty sections so that symbol lookups prefer the 1363 // non-empty section. 1364 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses; 1365 for (SectionRef Sec : Obj.sections()) 1366 SectionAddresses.emplace_back(Sec.getAddress(), Sec); 1367 llvm::stable_sort(SectionAddresses, [](const auto &LHS, const auto &RHS) { 1368 if (LHS.first != RHS.first) 1369 return LHS.first < RHS.first; 1370 return LHS.second.getSize() < RHS.second.getSize(); 1371 }); 1372 1373 // Linked executables (.exe and .dll files) typically don't include a real 1374 // symbol table but they might contain an export table. 1375 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(&Obj)) { 1376 for (const auto &ExportEntry : COFFObj->export_directories()) { 1377 StringRef Name; 1378 if (Error E = ExportEntry.getSymbolName(Name)) 1379 reportError(std::move(E), Obj.getFileName()); 1380 if (Name.empty()) 1381 continue; 1382 1383 uint32_t RVA; 1384 if (Error E = ExportEntry.getExportRVA(RVA)) 1385 reportError(std::move(E), Obj.getFileName()); 1386 1387 uint64_t VA = COFFObj->getImageBase() + RVA; 1388 auto Sec = partition_point( 1389 SectionAddresses, [VA](const std::pair<uint64_t, SectionRef> &O) { 1390 return O.first <= VA; 1391 }); 1392 if (Sec != SectionAddresses.begin()) { 1393 --Sec; 1394 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE); 1395 } else 1396 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE); 1397 } 1398 } 1399 1400 // Sort all the symbols, this allows us to use a simple binary search to find 1401 // Multiple symbols can have the same address. Use a stable sort to stabilize 1402 // the output. 1403 StringSet<> FoundDisasmSymbolSet; 1404 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols) 1405 llvm::stable_sort(SecSyms.second); 1406 llvm::stable_sort(AbsoluteSymbols); 1407 1408 std::unique_ptr<DWARFContext> DICtx; 1409 LiveVariablePrinter LVP(*Ctx.getRegisterInfo(), *STI); 1410 1411 if (DbgVariables != DVDisabled) { 1412 DICtx = DWARFContext::create(Obj); 1413 for (const std::unique_ptr<DWARFUnit> &CU : DICtx->compile_units()) 1414 LVP.addCompileUnit(CU->getUnitDIE(false)); 1415 } 1416 1417 LLVM_DEBUG(LVP.dump()); 1418 1419 std::unordered_map<uint64_t, BBAddrMap> AddrToBBAddrMap; 1420 auto ReadBBAddrMap = [&](Optional<unsigned> SectionIndex = None) { 1421 AddrToBBAddrMap.clear(); 1422 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(&Obj)) { 1423 auto BBAddrMapsOrErr = Elf->readBBAddrMap(SectionIndex); 1424 if (!BBAddrMapsOrErr) 1425 reportWarning(toString(BBAddrMapsOrErr.takeError()), 1426 Obj.getFileName()); 1427 for (auto &FunctionBBAddrMap : *BBAddrMapsOrErr) 1428 AddrToBBAddrMap.emplace(FunctionBBAddrMap.Addr, 1429 std::move(FunctionBBAddrMap)); 1430 } 1431 }; 1432 1433 // For non-relocatable objects, Read all LLVM_BB_ADDR_MAP sections into a 1434 // single mapping, since they don't have any conflicts. 1435 if (SymbolizeOperands && !Obj.isRelocatableObject()) 1436 ReadBBAddrMap(); 1437 1438 for (const SectionRef &Section : ToolSectionFilter(Obj)) { 1439 if (FilterSections.empty() && !DisassembleAll && 1440 (!Section.isText() || Section.isVirtual())) 1441 continue; 1442 1443 uint64_t SectionAddr = Section.getAddress(); 1444 uint64_t SectSize = Section.getSize(); 1445 if (!SectSize) 1446 continue; 1447 1448 // For relocatable object files, read the LLVM_BB_ADDR_MAP section 1449 // corresponding to this section, if present. 1450 if (SymbolizeOperands && Obj.isRelocatableObject()) 1451 ReadBBAddrMap(Section.getIndex()); 1452 1453 // Get the list of all the symbols in this section. 1454 SectionSymbolsTy &Symbols = AllSymbols[Section]; 1455 std::vector<MappingSymbolPair> MappingSymbols; 1456 if (hasMappingSymbols(Obj)) { 1457 for (const auto &Symb : Symbols) { 1458 uint64_t Address = Symb.Addr; 1459 StringRef Name = Symb.Name; 1460 if (Name.startswith("$d")) 1461 MappingSymbols.emplace_back(Address - SectionAddr, 'd'); 1462 if (Name.startswith("$x")) 1463 MappingSymbols.emplace_back(Address - SectionAddr, 'x'); 1464 if (Name.startswith("$a")) 1465 MappingSymbols.emplace_back(Address - SectionAddr, 'a'); 1466 if (Name.startswith("$t")) 1467 MappingSymbols.emplace_back(Address - SectionAddr, 't'); 1468 } 1469 } 1470 1471 llvm::sort(MappingSymbols); 1472 1473 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef( 1474 unwrapOrError(Section.getContents(), Obj.getFileName())); 1475 1476 std::vector<std::unique_ptr<std::string>> SynthesizedLabelNames; 1477 if (Obj.isELF() && Obj.getArch() == Triple::amdgcn) { 1478 // AMDGPU disassembler uses symbolizer for printing labels 1479 addSymbolizer(Ctx, TheTarget, TripleName, DisAsm, SectionAddr, Bytes, 1480 Symbols, SynthesizedLabelNames); 1481 } 1482 1483 StringRef SegmentName = getSegmentName(MachO, Section); 1484 StringRef SectionName = unwrapOrError(Section.getName(), Obj.getFileName()); 1485 // If the section has no symbol at the start, just insert a dummy one. 1486 if (Symbols.empty() || Symbols[0].Addr != 0) { 1487 Symbols.insert(Symbols.begin(), 1488 createDummySymbolInfo(Obj, SectionAddr, SectionName, 1489 Section.isText() ? ELF::STT_FUNC 1490 : ELF::STT_OBJECT)); 1491 } 1492 1493 SmallString<40> Comments; 1494 raw_svector_ostream CommentStream(Comments); 1495 1496 uint64_t VMAAdjustment = 0; 1497 if (shouldAdjustVA(Section)) 1498 VMAAdjustment = AdjustVMA; 1499 1500 // In executable and shared objects, r_offset holds a virtual address. 1501 // Subtract SectionAddr from the r_offset field of a relocation to get 1502 // the section offset. 1503 uint64_t RelAdjustment = Obj.isRelocatableObject() ? 0 : SectionAddr; 1504 uint64_t Size; 1505 uint64_t Index; 1506 bool PrintedSection = false; 1507 std::vector<RelocationRef> Rels = RelocMap[Section]; 1508 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin(); 1509 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end(); 1510 1511 // Loop over each chunk of code between two points where at least 1512 // one symbol is defined. 1513 for (size_t SI = 0, SE = Symbols.size(); SI != SE;) { 1514 // Advance SI past all the symbols starting at the same address, 1515 // and make an ArrayRef of them. 1516 unsigned FirstSI = SI; 1517 uint64_t Start = Symbols[SI].Addr; 1518 ArrayRef<SymbolInfoTy> SymbolsHere; 1519 while (SI != SE && Symbols[SI].Addr == Start) 1520 ++SI; 1521 SymbolsHere = ArrayRef<SymbolInfoTy>(&Symbols[FirstSI], SI - FirstSI); 1522 1523 // Get the demangled names of all those symbols. We end up with a vector 1524 // of StringRef that holds the names we're going to use, and a vector of 1525 // std::string that stores the new strings returned by demangle(), if 1526 // any. If we don't call demangle() then that vector can stay empty. 1527 std::vector<StringRef> SymNamesHere; 1528 std::vector<std::string> DemangledSymNamesHere; 1529 if (Demangle) { 1530 // Fetch the demangled names and store them locally. 1531 for (const SymbolInfoTy &Symbol : SymbolsHere) 1532 DemangledSymNamesHere.push_back(demangle(Symbol.Name.str())); 1533 // Now we've finished modifying that vector, it's safe to make 1534 // a vector of StringRefs pointing into it. 1535 SymNamesHere.insert(SymNamesHere.begin(), DemangledSymNamesHere.begin(), 1536 DemangledSymNamesHere.end()); 1537 } else { 1538 for (const SymbolInfoTy &Symbol : SymbolsHere) 1539 SymNamesHere.push_back(Symbol.Name); 1540 } 1541 1542 // Distinguish ELF data from code symbols, which will be used later on to 1543 // decide whether to 'disassemble' this chunk as a data declaration via 1544 // dumpELFData(), or whether to treat it as code. 1545 // 1546 // If data _and_ code symbols are defined at the same address, the code 1547 // takes priority, on the grounds that disassembling code is our main 1548 // purpose here, and it would be a worse failure to _not_ interpret 1549 // something that _was_ meaningful as code than vice versa. 1550 // 1551 // Any ELF symbol type that is not clearly data will be regarded as code. 1552 // In particular, one of the uses of STT_NOTYPE is for branch targets 1553 // inside functions, for which STT_FUNC would be inaccurate. 1554 // 1555 // So here, we spot whether there's any non-data symbol present at all, 1556 // and only set the DisassembleAsData flag if there isn't. Also, we use 1557 // this distinction to inform the decision of which symbol to print at 1558 // the head of the section, so that if we're printing code, we print a 1559 // code-related symbol name to go with it. 1560 bool DisassembleAsData = false; 1561 size_t DisplaySymIndex = SymbolsHere.size() - 1; 1562 if (Obj.isELF() && !DisassembleAll && Section.isText()) { 1563 DisassembleAsData = true; // unless we find a code symbol below 1564 1565 for (size_t i = 0; i < SymbolsHere.size(); ++i) { 1566 uint8_t SymTy = SymbolsHere[i].Type; 1567 if (SymTy != ELF::STT_OBJECT && SymTy != ELF::STT_COMMON) { 1568 DisassembleAsData = false; 1569 DisplaySymIndex = i; 1570 } 1571 } 1572 } 1573 1574 // Decide which symbol(s) from this collection we're going to print. 1575 std::vector<bool> SymsToPrint(SymbolsHere.size(), false); 1576 // If the user has given the --disassemble-symbols option, then we must 1577 // display every symbol in that set, and no others. 1578 if (!DisasmSymbolSet.empty()) { 1579 bool FoundAny = false; 1580 for (size_t i = 0; i < SymbolsHere.size(); ++i) { 1581 if (DisasmSymbolSet.count(SymNamesHere[i])) { 1582 SymsToPrint[i] = true; 1583 FoundAny = true; 1584 } 1585 } 1586 1587 // And if none of the symbols here is one that the user asked for, skip 1588 // disassembling this entire chunk of code. 1589 if (!FoundAny) 1590 continue; 1591 } else { 1592 // Otherwise, print whichever symbol at this location is last in the 1593 // Symbols array, because that array is pre-sorted in a way intended to 1594 // correlate with priority of which symbol to display. 1595 SymsToPrint[DisplaySymIndex] = true; 1596 } 1597 1598 // Now that we know we're disassembling this section, override the choice 1599 // of which symbols to display by printing _all_ of them at this address 1600 // if the user asked for all symbols. 1601 // 1602 // That way, '--show-all-symbols --disassemble-symbol=foo' will print 1603 // only the chunk of code headed by 'foo', but also show any other 1604 // symbols defined at that address, such as aliases for 'foo', or the ARM 1605 // mapping symbol preceding its code. 1606 if (ShowAllSymbols) { 1607 for (size_t i = 0; i < SymbolsHere.size(); ++i) 1608 SymsToPrint[i] = true; 1609 } 1610 1611 if (Start < SectionAddr || StopAddress <= Start) 1612 continue; 1613 1614 for (size_t i = 0; i < SymbolsHere.size(); ++i) 1615 FoundDisasmSymbolSet.insert(SymNamesHere[i]); 1616 1617 // The end is the section end, the beginning of the next symbol, or 1618 // --stop-address. 1619 uint64_t End = std::min<uint64_t>(SectionAddr + SectSize, StopAddress); 1620 if (SI < SE) 1621 End = std::min(End, Symbols[SI].Addr); 1622 if (Start >= End || End <= StartAddress) 1623 continue; 1624 Start -= SectionAddr; 1625 End -= SectionAddr; 1626 1627 if (!PrintedSection) { 1628 PrintedSection = true; 1629 outs() << "\nDisassembly of section "; 1630 if (!SegmentName.empty()) 1631 outs() << SegmentName << ","; 1632 outs() << SectionName << ":\n"; 1633 } 1634 1635 outs() << '\n'; 1636 1637 for (size_t i = 0; i < SymbolsHere.size(); ++i) { 1638 if (!SymsToPrint[i]) 1639 continue; 1640 1641 const SymbolInfoTy &Symbol = SymbolsHere[i]; 1642 const StringRef SymbolName = SymNamesHere[i]; 1643 1644 if (LeadingAddr) 1645 outs() << format(Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " ", 1646 SectionAddr + Start + VMAAdjustment); 1647 if (Obj.isXCOFF() && SymbolDescription) { 1648 outs() << getXCOFFSymbolDescription(Symbol, SymbolName) << ":\n"; 1649 } else 1650 outs() << '<' << SymbolName << ">:\n"; 1651 } 1652 1653 // Don't print raw contents of a virtual section. A virtual section 1654 // doesn't have any contents in the file. 1655 if (Section.isVirtual()) { 1656 outs() << "...\n"; 1657 continue; 1658 } 1659 1660 // See if any of the symbols defined at this location triggers target- 1661 // specific disassembly behavior, e.g. of special descriptors or function 1662 // prelude information. 1663 // 1664 // We stop this loop at the first symbol that triggers some kind of 1665 // interesting behavior (if any), on the assumption that if two symbols 1666 // defined at the same address trigger two conflicting symbol handlers, 1667 // the object file is probably confused anyway, and it would make even 1668 // less sense to present the output of _both_ handlers, because that 1669 // would describe the same data twice. 1670 for (size_t SHI = 0; SHI < SymbolsHere.size(); ++SHI) { 1671 SymbolInfoTy Symbol = SymbolsHere[SHI]; 1672 1673 auto Status = 1674 DisAsm->onSymbolStart(Symbol, Size, Bytes.slice(Start, End - Start), 1675 SectionAddr + Start, CommentStream); 1676 1677 if (!Status) { 1678 // If onSymbolStart returns None, that means it didn't trigger any 1679 // interesting handling for this symbol. Try the other symbols 1680 // defined at this address. 1681 continue; 1682 } 1683 1684 if (Status.value() == MCDisassembler::Fail) { 1685 // If onSymbolStart returns Fail, that means it identified some kind 1686 // of special data at this address, but wasn't able to disassemble it 1687 // meaningfully. So we fall back to disassembling the failed region 1688 // as bytes, assuming that the target detected the failure before 1689 // printing anything. 1690 // 1691 // Return values Success or SoftFail (i.e no 'real' failure) are 1692 // expected to mean that the target has emitted its own output. 1693 // 1694 // Either way, 'Size' will have been set to the amount of data 1695 // covered by whatever prologue the target identified. So we advance 1696 // our own position to beyond that. Sometimes that will be the entire 1697 // distance to the next symbol, and sometimes it will be just a 1698 // prologue and we should start disassembling instructions from where 1699 // it left off. 1700 outs() << "// Error in decoding " << SymNamesHere[SHI] 1701 << " : Decoding failed region as bytes.\n"; 1702 for (uint64_t I = 0; I < Size; ++I) { 1703 outs() << "\t.byte\t " << format_hex(Bytes[I], 1, /*Upper=*/true) 1704 << "\n"; 1705 } 1706 } 1707 Start += Size; 1708 break; 1709 } 1710 1711 Index = Start; 1712 if (SectionAddr < StartAddress) 1713 Index = std::max<uint64_t>(Index, StartAddress - SectionAddr); 1714 1715 if (DisassembleAsData) { 1716 dumpELFData(SectionAddr, Index, End, Bytes); 1717 Index = End; 1718 continue; 1719 } 1720 1721 bool DumpARMELFData = false; 1722 formatted_raw_ostream FOS(outs()); 1723 1724 std::unordered_map<uint64_t, std::string> AllLabels; 1725 std::unordered_map<uint64_t, std::vector<std::string>> BBAddrMapLabels; 1726 if (SymbolizeOperands) { 1727 collectLocalBranchTargets(Bytes, MIA, DisAsm, IP, PrimarySTI, 1728 SectionAddr, Index, End, AllLabels); 1729 collectBBAddrMapLabels(AddrToBBAddrMap, SectionAddr, Index, End, 1730 BBAddrMapLabels); 1731 } 1732 1733 while (Index < End) { 1734 // ARM and AArch64 ELF binaries can interleave data and text in the 1735 // same section. We rely on the markers introduced to understand what 1736 // we need to dump. If the data marker is within a function, it is 1737 // denoted as a word/short etc. 1738 if (!MappingSymbols.empty()) { 1739 char Kind = getMappingSymbolKind(MappingSymbols, Index); 1740 DumpARMELFData = Kind == 'd'; 1741 if (SecondarySTI) { 1742 if (Kind == 'a') { 1743 STI = PrimaryIsThumb ? SecondarySTI : PrimarySTI; 1744 DisAsm = PrimaryIsThumb ? SecondaryDisAsm : PrimaryDisAsm; 1745 } else if (Kind == 't') { 1746 STI = PrimaryIsThumb ? PrimarySTI : SecondarySTI; 1747 DisAsm = PrimaryIsThumb ? PrimaryDisAsm : SecondaryDisAsm; 1748 } 1749 } 1750 } 1751 1752 if (DumpARMELFData) { 1753 Size = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes, 1754 MappingSymbols, *STI, FOS); 1755 } else { 1756 // When -z or --disassemble-zeroes are given we always dissasemble 1757 // them. Otherwise we might want to skip zero bytes we see. 1758 if (!DisassembleZeroes) { 1759 uint64_t MaxOffset = End - Index; 1760 // For --reloc: print zero blocks patched by relocations, so that 1761 // relocations can be shown in the dump. 1762 if (RelCur != RelEnd) 1763 MaxOffset = std::min(RelCur->getOffset() - RelAdjustment - Index, 1764 MaxOffset); 1765 1766 if (size_t N = 1767 countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) { 1768 FOS << "\t\t..." << '\n'; 1769 Index += N; 1770 continue; 1771 } 1772 } 1773 1774 // Print local label if there's any. 1775 auto Iter1 = BBAddrMapLabels.find(SectionAddr + Index); 1776 if (Iter1 != BBAddrMapLabels.end()) { 1777 for (StringRef Label : Iter1->second) 1778 FOS << "<" << Label << ">:\n"; 1779 } else { 1780 auto Iter2 = AllLabels.find(SectionAddr + Index); 1781 if (Iter2 != AllLabels.end()) 1782 FOS << "<" << Iter2->second << ">:\n"; 1783 } 1784 1785 // Disassemble a real instruction or a data when disassemble all is 1786 // provided 1787 MCInst Inst; 1788 ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index); 1789 uint64_t ThisAddr = SectionAddr + Index; 1790 bool Disassembled = DisAsm->getInstruction(Inst, Size, ThisBytes, 1791 ThisAddr, CommentStream); 1792 if (Size == 0) 1793 Size = std::min<uint64_t>( 1794 ThisBytes.size(), 1795 DisAsm->suggestBytesToSkip(ThisBytes, ThisAddr)); 1796 1797 LVP.update({Index, Section.getIndex()}, 1798 {Index + Size, Section.getIndex()}, Index + Size != End); 1799 1800 IP->setCommentStream(CommentStream); 1801 1802 PIP.printInst( 1803 *IP, Disassembled ? &Inst : nullptr, Bytes.slice(Index, Size), 1804 {SectionAddr + Index + VMAAdjustment, Section.getIndex()}, FOS, 1805 "", *STI, &SP, Obj.getFileName(), &Rels, LVP); 1806 1807 IP->setCommentStream(llvm::nulls()); 1808 1809 // If disassembly has failed, avoid analysing invalid/incomplete 1810 // instruction information. Otherwise, try to resolve the target 1811 // address (jump target or memory operand address) and print it on the 1812 // right of the instruction. 1813 if (Disassembled && MIA) { 1814 // Branch targets are printed just after the instructions. 1815 llvm::raw_ostream *TargetOS = &FOS; 1816 uint64_t Target; 1817 bool PrintTarget = 1818 MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target); 1819 if (!PrintTarget) 1820 if (Optional<uint64_t> MaybeTarget = 1821 MIA->evaluateMemoryOperandAddress( 1822 Inst, STI, SectionAddr + Index, Size)) { 1823 Target = *MaybeTarget; 1824 PrintTarget = true; 1825 // Do not print real address when symbolizing. 1826 if (!SymbolizeOperands) { 1827 // Memory operand addresses are printed as comments. 1828 TargetOS = &CommentStream; 1829 *TargetOS << "0x" << Twine::utohexstr(Target); 1830 } 1831 } 1832 if (PrintTarget) { 1833 // In a relocatable object, the target's section must reside in 1834 // the same section as the call instruction or it is accessed 1835 // through a relocation. 1836 // 1837 // In a non-relocatable object, the target may be in any section. 1838 // In that case, locate the section(s) containing the target 1839 // address and find the symbol in one of those, if possible. 1840 // 1841 // N.B. We don't walk the relocations in the relocatable case yet. 1842 std::vector<const SectionSymbolsTy *> TargetSectionSymbols; 1843 if (!Obj.isRelocatableObject()) { 1844 auto It = llvm::partition_point( 1845 SectionAddresses, 1846 [=](const std::pair<uint64_t, SectionRef> &O) { 1847 return O.first <= Target; 1848 }); 1849 uint64_t TargetSecAddr = 0; 1850 while (It != SectionAddresses.begin()) { 1851 --It; 1852 if (TargetSecAddr == 0) 1853 TargetSecAddr = It->first; 1854 if (It->first != TargetSecAddr) 1855 break; 1856 TargetSectionSymbols.push_back(&AllSymbols[It->second]); 1857 } 1858 } else { 1859 TargetSectionSymbols.push_back(&Symbols); 1860 } 1861 TargetSectionSymbols.push_back(&AbsoluteSymbols); 1862 1863 // Find the last symbol in the first candidate section whose 1864 // offset is less than or equal to the target. If there are no 1865 // such symbols, try in the next section and so on, before finally 1866 // using the nearest preceding absolute symbol (if any), if there 1867 // are no other valid symbols. 1868 const SymbolInfoTy *TargetSym = nullptr; 1869 for (const SectionSymbolsTy *TargetSymbols : 1870 TargetSectionSymbols) { 1871 auto It = llvm::partition_point( 1872 *TargetSymbols, 1873 [=](const SymbolInfoTy &O) { return O.Addr <= Target; }); 1874 if (It != TargetSymbols->begin()) { 1875 TargetSym = &*(It - 1); 1876 break; 1877 } 1878 } 1879 1880 // Print the labels corresponding to the target if there's any. 1881 bool BBAddrMapLabelAvailable = BBAddrMapLabels.count(Target); 1882 bool LabelAvailable = AllLabels.count(Target); 1883 if (TargetSym != nullptr) { 1884 uint64_t TargetAddress = TargetSym->Addr; 1885 uint64_t Disp = Target - TargetAddress; 1886 std::string TargetName = TargetSym->Name.str(); 1887 if (Demangle) 1888 TargetName = demangle(TargetName); 1889 1890 *TargetOS << " <"; 1891 if (!Disp) { 1892 // Always Print the binary symbol precisely corresponding to 1893 // the target address. 1894 *TargetOS << TargetName; 1895 } else if (BBAddrMapLabelAvailable) { 1896 *TargetOS << BBAddrMapLabels[Target].front(); 1897 } else if (LabelAvailable) { 1898 *TargetOS << AllLabels[Target]; 1899 } else { 1900 // Always Print the binary symbol plus an offset if there's no 1901 // local label corresponding to the target address. 1902 *TargetOS << TargetName << "+0x" << Twine::utohexstr(Disp); 1903 } 1904 *TargetOS << ">"; 1905 } else if (BBAddrMapLabelAvailable) { 1906 *TargetOS << " <" << BBAddrMapLabels[Target].front() << ">"; 1907 } else if (LabelAvailable) { 1908 *TargetOS << " <" << AllLabels[Target] << ">"; 1909 } 1910 // By convention, each record in the comment stream should be 1911 // terminated. 1912 if (TargetOS == &CommentStream) 1913 *TargetOS << "\n"; 1914 } 1915 } 1916 } 1917 1918 assert(Ctx.getAsmInfo()); 1919 emitPostInstructionInfo(FOS, *Ctx.getAsmInfo(), *STI, 1920 CommentStream.str(), LVP); 1921 Comments.clear(); 1922 1923 // Hexagon does this in pretty printer 1924 if (Obj.getArch() != Triple::hexagon) { 1925 // Print relocation for instruction and data. 1926 while (RelCur != RelEnd) { 1927 uint64_t Offset = RelCur->getOffset() - RelAdjustment; 1928 // If this relocation is hidden, skip it. 1929 if (getHidden(*RelCur) || SectionAddr + Offset < StartAddress) { 1930 ++RelCur; 1931 continue; 1932 } 1933 1934 // Stop when RelCur's offset is past the disassembled 1935 // instruction/data. Note that it's possible the disassembled data 1936 // is not the complete data: we might see the relocation printed in 1937 // the middle of the data, but this matches the binutils objdump 1938 // output. 1939 if (Offset >= Index + Size) 1940 break; 1941 1942 // When --adjust-vma is used, update the address printed. 1943 if (RelCur->getSymbol() != Obj.symbol_end()) { 1944 Expected<section_iterator> SymSI = 1945 RelCur->getSymbol()->getSection(); 1946 if (SymSI && *SymSI != Obj.section_end() && 1947 shouldAdjustVA(**SymSI)) 1948 Offset += AdjustVMA; 1949 } 1950 1951 printRelocation(FOS, Obj.getFileName(), *RelCur, 1952 SectionAddr + Offset, Is64Bits); 1953 LVP.printAfterOtherLine(FOS, true); 1954 ++RelCur; 1955 } 1956 } 1957 1958 Index += Size; 1959 } 1960 } 1961 } 1962 StringSet<> MissingDisasmSymbolSet = 1963 set_difference(DisasmSymbolSet, FoundDisasmSymbolSet); 1964 for (StringRef Sym : MissingDisasmSymbolSet.keys()) 1965 reportWarning("failed to disassemble missing symbol " + Sym, FileName); 1966 } 1967 1968 static void disassembleObject(ObjectFile *Obj, bool InlineRelocs) { 1969 const Target *TheTarget = getTarget(Obj); 1970 1971 // Package up features to be passed to target/subtarget 1972 SubtargetFeatures Features = Obj->getFeatures(); 1973 if (!MAttrs.empty()) { 1974 for (unsigned I = 0; I != MAttrs.size(); ++I) 1975 Features.AddFeature(MAttrs[I]); 1976 } else if (MCPU.empty() && Obj->getArch() == llvm::Triple::aarch64) { 1977 Features.AddFeature("+all"); 1978 } 1979 1980 std::unique_ptr<const MCRegisterInfo> MRI( 1981 TheTarget->createMCRegInfo(TripleName)); 1982 if (!MRI) 1983 reportError(Obj->getFileName(), 1984 "no register info for target " + TripleName); 1985 1986 // Set up disassembler. 1987 MCTargetOptions MCOptions; 1988 std::unique_ptr<const MCAsmInfo> AsmInfo( 1989 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions)); 1990 if (!AsmInfo) 1991 reportError(Obj->getFileName(), 1992 "no assembly info for target " + TripleName); 1993 1994 if (MCPU.empty()) 1995 MCPU = Obj->tryGetCPUName().value_or("").str(); 1996 1997 if (isArmElf(*Obj)) { 1998 // When disassembling big-endian Arm ELF, the instruction endianness is 1999 // determined in a complex way. In relocatable objects, AAELF32 mandates 2000 // that instruction endianness matches the ELF file endianness; in 2001 // executable images, that's true unless the file header has the EF_ARM_BE8 2002 // flag, in which case instructions are little-endian regardless of data 2003 // endianness. 2004 // 2005 // We must set the big-endian-instructions SubtargetFeature to make the 2006 // disassembler read the instructions the right way round, and also tell 2007 // our own prettyprinter to retrieve the encodings the same way to print in 2008 // hex. 2009 const auto *Elf32BE = dyn_cast<ELF32BEObjectFile>(Obj); 2010 2011 if (Elf32BE && (Elf32BE->isRelocatableObject() || 2012 !(Elf32BE->getPlatformFlags() & ELF::EF_ARM_BE8))) { 2013 Features.AddFeature("+big-endian-instructions"); 2014 ARMPrettyPrinterInst.setInstructionEndianness(llvm::support::big); 2015 } else { 2016 ARMPrettyPrinterInst.setInstructionEndianness(llvm::support::little); 2017 } 2018 } 2019 2020 std::unique_ptr<const MCSubtargetInfo> STI( 2021 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString())); 2022 if (!STI) 2023 reportError(Obj->getFileName(), 2024 "no subtarget info for target " + TripleName); 2025 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); 2026 if (!MII) 2027 reportError(Obj->getFileName(), 2028 "no instruction info for target " + TripleName); 2029 MCContext Ctx(Triple(TripleName), AsmInfo.get(), MRI.get(), STI.get()); 2030 // FIXME: for now initialize MCObjectFileInfo with default values 2031 std::unique_ptr<MCObjectFileInfo> MOFI( 2032 TheTarget->createMCObjectFileInfo(Ctx, /*PIC=*/false)); 2033 Ctx.setObjectFileInfo(MOFI.get()); 2034 2035 std::unique_ptr<MCDisassembler> DisAsm( 2036 TheTarget->createMCDisassembler(*STI, Ctx)); 2037 if (!DisAsm) 2038 reportError(Obj->getFileName(), "no disassembler for target " + TripleName); 2039 2040 // If we have an ARM object file, we need a second disassembler, because 2041 // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode. 2042 // We use mapping symbols to switch between the two assemblers, where 2043 // appropriate. 2044 std::unique_ptr<MCDisassembler> SecondaryDisAsm; 2045 std::unique_ptr<const MCSubtargetInfo> SecondarySTI; 2046 if (isArmElf(*Obj) && !STI->checkFeatures("+mclass")) { 2047 if (STI->checkFeatures("+thumb-mode")) 2048 Features.AddFeature("-thumb-mode"); 2049 else 2050 Features.AddFeature("+thumb-mode"); 2051 SecondarySTI.reset(TheTarget->createMCSubtargetInfo(TripleName, MCPU, 2052 Features.getString())); 2053 SecondaryDisAsm.reset(TheTarget->createMCDisassembler(*SecondarySTI, Ctx)); 2054 } 2055 2056 std::unique_ptr<const MCInstrAnalysis> MIA( 2057 TheTarget->createMCInstrAnalysis(MII.get())); 2058 2059 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 2060 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 2061 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI)); 2062 if (!IP) 2063 reportError(Obj->getFileName(), 2064 "no instruction printer for target " + TripleName); 2065 IP->setPrintImmHex(PrintImmHex); 2066 IP->setPrintBranchImmAsAddress(true); 2067 IP->setSymbolizeOperands(SymbolizeOperands); 2068 IP->setMCInstrAnalysis(MIA.get()); 2069 2070 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName)); 2071 ObjectFile *DbgObj = Obj; 2072 OwningBinary<Binary> DebugBinary; 2073 if (!Obj->hasDebugInfo()) { 2074 if (Optional<OwningBinary<Binary>> DebugBinaryOpt = 2075 fetchBinaryByBuildID(*Obj)) { 2076 if (ObjectFile *FetchedObj = 2077 dyn_cast<ObjectFile>(DebugBinaryOpt->getBinary())) { 2078 if (FetchedObj->hasDebugInfo()) { 2079 DebugBinary = std::move(*DebugBinaryOpt); 2080 DbgObj = FetchedObj; 2081 } 2082 } 2083 } 2084 } 2085 SourcePrinter SP(DbgObj, TheTarget->getName()); 2086 2087 for (StringRef Opt : DisassemblerOptions) 2088 if (!IP->applyTargetSpecificCLOption(Opt)) 2089 reportError(Obj->getFileName(), 2090 "Unrecognized disassembler option: " + Opt); 2091 2092 disassembleObject(TheTarget, *Obj, Ctx, DisAsm.get(), SecondaryDisAsm.get(), 2093 MIA.get(), IP.get(), STI.get(), SecondarySTI.get(), PIP, SP, 2094 InlineRelocs); 2095 } 2096 2097 void objdump::printRelocations(const ObjectFile *Obj) { 2098 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : 2099 "%08" PRIx64; 2100 2101 // Build a mapping from relocation target to a vector of relocation 2102 // sections. Usually, there is an only one relocation section for 2103 // each relocated section. 2104 MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec; 2105 uint64_t Ndx; 2106 for (const SectionRef &Section : ToolSectionFilter(*Obj, &Ndx)) { 2107 if (Obj->isELF() && (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC)) 2108 continue; 2109 if (Section.relocation_begin() == Section.relocation_end()) 2110 continue; 2111 Expected<section_iterator> SecOrErr = Section.getRelocatedSection(); 2112 if (!SecOrErr) 2113 reportError(Obj->getFileName(), 2114 "section (" + Twine(Ndx) + 2115 "): unable to get a relocation target: " + 2116 toString(SecOrErr.takeError())); 2117 SecToRelSec[**SecOrErr].push_back(Section); 2118 } 2119 2120 for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) { 2121 StringRef SecName = unwrapOrError(P.first.getName(), Obj->getFileName()); 2122 outs() << "\nRELOCATION RECORDS FOR [" << SecName << "]:\n"; 2123 uint32_t OffsetPadding = (Obj->getBytesInAddress() > 4 ? 16 : 8); 2124 uint32_t TypePadding = 24; 2125 outs() << left_justify("OFFSET", OffsetPadding) << " " 2126 << left_justify("TYPE", TypePadding) << " " 2127 << "VALUE\n"; 2128 2129 for (SectionRef Section : P.second) { 2130 for (const RelocationRef &Reloc : Section.relocations()) { 2131 uint64_t Address = Reloc.getOffset(); 2132 SmallString<32> RelocName; 2133 SmallString<32> ValueStr; 2134 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc)) 2135 continue; 2136 Reloc.getTypeName(RelocName); 2137 if (Error E = getRelocationValueString(Reloc, ValueStr)) 2138 reportError(std::move(E), Obj->getFileName()); 2139 2140 outs() << format(Fmt.data(), Address) << " " 2141 << left_justify(RelocName, TypePadding) << " " << ValueStr 2142 << "\n"; 2143 } 2144 } 2145 } 2146 } 2147 2148 void objdump::printDynamicRelocations(const ObjectFile *Obj) { 2149 // For the moment, this option is for ELF only 2150 if (!Obj->isELF()) 2151 return; 2152 2153 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj); 2154 if (!Elf || !any_of(Elf->sections(), [](const ELFSectionRef Sec) { 2155 return Sec.getType() == ELF::SHT_DYNAMIC; 2156 })) { 2157 reportError(Obj->getFileName(), "not a dynamic object"); 2158 return; 2159 } 2160 2161 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections(); 2162 if (DynRelSec.empty()) 2163 return; 2164 2165 outs() << "\nDYNAMIC RELOCATION RECORDS\n"; 2166 const uint32_t OffsetPadding = (Obj->getBytesInAddress() > 4 ? 16 : 8); 2167 const uint32_t TypePadding = 24; 2168 outs() << left_justify("OFFSET", OffsetPadding) << ' ' 2169 << left_justify("TYPE", TypePadding) << " VALUE\n"; 2170 2171 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 2172 for (const SectionRef &Section : DynRelSec) 2173 for (const RelocationRef &Reloc : Section.relocations()) { 2174 uint64_t Address = Reloc.getOffset(); 2175 SmallString<32> RelocName; 2176 SmallString<32> ValueStr; 2177 Reloc.getTypeName(RelocName); 2178 if (Error E = getRelocationValueString(Reloc, ValueStr)) 2179 reportError(std::move(E), Obj->getFileName()); 2180 outs() << format(Fmt.data(), Address) << ' ' 2181 << left_justify(RelocName, TypePadding) << ' ' << ValueStr << '\n'; 2182 } 2183 } 2184 2185 // Returns true if we need to show LMA column when dumping section headers. We 2186 // show it only when the platform is ELF and either we have at least one section 2187 // whose VMA and LMA are different and/or when --show-lma flag is used. 2188 static bool shouldDisplayLMA(const ObjectFile &Obj) { 2189 if (!Obj.isELF()) 2190 return false; 2191 for (const SectionRef &S : ToolSectionFilter(Obj)) 2192 if (S.getAddress() != getELFSectionLMA(S)) 2193 return true; 2194 return ShowLMA; 2195 } 2196 2197 static size_t getMaxSectionNameWidth(const ObjectFile &Obj) { 2198 // Default column width for names is 13 even if no names are that long. 2199 size_t MaxWidth = 13; 2200 for (const SectionRef &Section : ToolSectionFilter(Obj)) { 2201 StringRef Name = unwrapOrError(Section.getName(), Obj.getFileName()); 2202 MaxWidth = std::max(MaxWidth, Name.size()); 2203 } 2204 return MaxWidth; 2205 } 2206 2207 void objdump::printSectionHeaders(ObjectFile &Obj) { 2208 if (Obj.isELF() && Obj.sections().empty()) 2209 createFakeELFSections(Obj); 2210 2211 size_t NameWidth = getMaxSectionNameWidth(Obj); 2212 size_t AddressWidth = 2 * Obj.getBytesInAddress(); 2213 bool HasLMAColumn = shouldDisplayLMA(Obj); 2214 outs() << "\nSections:\n"; 2215 if (HasLMAColumn) 2216 outs() << "Idx " << left_justify("Name", NameWidth) << " Size " 2217 << left_justify("VMA", AddressWidth) << " " 2218 << left_justify("LMA", AddressWidth) << " Type\n"; 2219 else 2220 outs() << "Idx " << left_justify("Name", NameWidth) << " Size " 2221 << left_justify("VMA", AddressWidth) << " Type\n"; 2222 2223 uint64_t Idx; 2224 for (const SectionRef &Section : ToolSectionFilter(Obj, &Idx)) { 2225 StringRef Name = unwrapOrError(Section.getName(), Obj.getFileName()); 2226 uint64_t VMA = Section.getAddress(); 2227 if (shouldAdjustVA(Section)) 2228 VMA += AdjustVMA; 2229 2230 uint64_t Size = Section.getSize(); 2231 2232 std::string Type = Section.isText() ? "TEXT" : ""; 2233 if (Section.isData()) 2234 Type += Type.empty() ? "DATA" : ", DATA"; 2235 if (Section.isBSS()) 2236 Type += Type.empty() ? "BSS" : ", BSS"; 2237 if (Section.isDebugSection()) 2238 Type += Type.empty() ? "DEBUG" : ", DEBUG"; 2239 2240 if (HasLMAColumn) 2241 outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth, 2242 Name.str().c_str(), Size) 2243 << format_hex_no_prefix(VMA, AddressWidth) << " " 2244 << format_hex_no_prefix(getELFSectionLMA(Section), AddressWidth) 2245 << " " << Type << "\n"; 2246 else 2247 outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth, 2248 Name.str().c_str(), Size) 2249 << format_hex_no_prefix(VMA, AddressWidth) << " " << Type << "\n"; 2250 } 2251 } 2252 2253 void objdump::printSectionContents(const ObjectFile *Obj) { 2254 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj); 2255 2256 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 2257 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName()); 2258 uint64_t BaseAddr = Section.getAddress(); 2259 uint64_t Size = Section.getSize(); 2260 if (!Size) 2261 continue; 2262 2263 outs() << "Contents of section "; 2264 StringRef SegmentName = getSegmentName(MachO, Section); 2265 if (!SegmentName.empty()) 2266 outs() << SegmentName << ","; 2267 outs() << Name << ":\n"; 2268 if (Section.isBSS()) { 2269 outs() << format("<skipping contents of bss section at [%04" PRIx64 2270 ", %04" PRIx64 ")>\n", 2271 BaseAddr, BaseAddr + Size); 2272 continue; 2273 } 2274 2275 StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName()); 2276 2277 // Dump out the content as hex and printable ascii characters. 2278 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) { 2279 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr); 2280 // Dump line of hex. 2281 for (std::size_t I = 0; I < 16; ++I) { 2282 if (I != 0 && I % 4 == 0) 2283 outs() << ' '; 2284 if (Addr + I < End) 2285 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true) 2286 << hexdigit(Contents[Addr + I] & 0xF, true); 2287 else 2288 outs() << " "; 2289 } 2290 // Print ascii. 2291 outs() << " "; 2292 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) { 2293 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF)) 2294 outs() << Contents[Addr + I]; 2295 else 2296 outs() << "."; 2297 } 2298 outs() << "\n"; 2299 } 2300 } 2301 } 2302 2303 void objdump::printSymbolTable(const ObjectFile &O, StringRef ArchiveName, 2304 StringRef ArchitectureName, bool DumpDynamic) { 2305 if (O.isCOFF() && !DumpDynamic) { 2306 outs() << "\nSYMBOL TABLE:\n"; 2307 printCOFFSymbolTable(cast<const COFFObjectFile>(O)); 2308 return; 2309 } 2310 2311 const StringRef FileName = O.getFileName(); 2312 2313 if (!DumpDynamic) { 2314 outs() << "\nSYMBOL TABLE:\n"; 2315 for (auto I = O.symbol_begin(); I != O.symbol_end(); ++I) 2316 printSymbol(O, *I, {}, FileName, ArchiveName, ArchitectureName, 2317 DumpDynamic); 2318 return; 2319 } 2320 2321 outs() << "\nDYNAMIC SYMBOL TABLE:\n"; 2322 if (!O.isELF()) { 2323 reportWarning( 2324 "this operation is not currently supported for this file format", 2325 FileName); 2326 return; 2327 } 2328 2329 const ELFObjectFileBase *ELF = cast<const ELFObjectFileBase>(&O); 2330 auto Symbols = ELF->getDynamicSymbolIterators(); 2331 Expected<std::vector<VersionEntry>> SymbolVersionsOrErr = 2332 ELF->readDynsymVersions(); 2333 if (!SymbolVersionsOrErr) { 2334 reportWarning(toString(SymbolVersionsOrErr.takeError()), FileName); 2335 SymbolVersionsOrErr = std::vector<VersionEntry>(); 2336 (void)!SymbolVersionsOrErr; 2337 } 2338 for (auto &Sym : Symbols) 2339 printSymbol(O, Sym, *SymbolVersionsOrErr, FileName, ArchiveName, 2340 ArchitectureName, DumpDynamic); 2341 } 2342 2343 void objdump::printSymbol(const ObjectFile &O, const SymbolRef &Symbol, 2344 ArrayRef<VersionEntry> SymbolVersions, 2345 StringRef FileName, StringRef ArchiveName, 2346 StringRef ArchitectureName, bool DumpDynamic) { 2347 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(&O); 2348 uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName, ArchiveName, 2349 ArchitectureName); 2350 if ((Address < StartAddress) || (Address > StopAddress)) 2351 return; 2352 SymbolRef::Type Type = 2353 unwrapOrError(Symbol.getType(), FileName, ArchiveName, ArchitectureName); 2354 uint32_t Flags = 2355 unwrapOrError(Symbol.getFlags(), FileName, ArchiveName, ArchitectureName); 2356 2357 // Don't ask a Mach-O STAB symbol for its section unless you know that 2358 // STAB symbol's section field refers to a valid section index. Otherwise 2359 // the symbol may error trying to load a section that does not exist. 2360 bool IsSTAB = false; 2361 if (MachO) { 2362 DataRefImpl SymDRI = Symbol.getRawDataRefImpl(); 2363 uint8_t NType = 2364 (MachO->is64Bit() ? MachO->getSymbol64TableEntry(SymDRI).n_type 2365 : MachO->getSymbolTableEntry(SymDRI).n_type); 2366 if (NType & MachO::N_STAB) 2367 IsSTAB = true; 2368 } 2369 section_iterator Section = IsSTAB 2370 ? O.section_end() 2371 : unwrapOrError(Symbol.getSection(), FileName, 2372 ArchiveName, ArchitectureName); 2373 2374 StringRef Name; 2375 if (Type == SymbolRef::ST_Debug && Section != O.section_end()) { 2376 if (Expected<StringRef> NameOrErr = Section->getName()) 2377 Name = *NameOrErr; 2378 else 2379 consumeError(NameOrErr.takeError()); 2380 2381 } else { 2382 Name = unwrapOrError(Symbol.getName(), FileName, ArchiveName, 2383 ArchitectureName); 2384 } 2385 2386 bool Global = Flags & SymbolRef::SF_Global; 2387 bool Weak = Flags & SymbolRef::SF_Weak; 2388 bool Absolute = Flags & SymbolRef::SF_Absolute; 2389 bool Common = Flags & SymbolRef::SF_Common; 2390 bool Hidden = Flags & SymbolRef::SF_Hidden; 2391 2392 char GlobLoc = ' '; 2393 if ((Section != O.section_end() || Absolute) && !Weak) 2394 GlobLoc = Global ? 'g' : 'l'; 2395 char IFunc = ' '; 2396 if (O.isELF()) { 2397 if (ELFSymbolRef(Symbol).getELFType() == ELF::STT_GNU_IFUNC) 2398 IFunc = 'i'; 2399 if (ELFSymbolRef(Symbol).getBinding() == ELF::STB_GNU_UNIQUE) 2400 GlobLoc = 'u'; 2401 } 2402 2403 char Debug = ' '; 2404 if (DumpDynamic) 2405 Debug = 'D'; 2406 else if (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 2407 Debug = 'd'; 2408 2409 char FileFunc = ' '; 2410 if (Type == SymbolRef::ST_File) 2411 FileFunc = 'f'; 2412 else if (Type == SymbolRef::ST_Function) 2413 FileFunc = 'F'; 2414 else if (Type == SymbolRef::ST_Data) 2415 FileFunc = 'O'; 2416 2417 const char *Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 2418 2419 outs() << format(Fmt, Address) << " " 2420 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 2421 << (Weak ? 'w' : ' ') // Weak? 2422 << ' ' // Constructor. Not supported yet. 2423 << ' ' // Warning. Not supported yet. 2424 << IFunc // Indirect reference to another symbol. 2425 << Debug // Debugging (d) or dynamic (D) symbol. 2426 << FileFunc // Name of function (F), file (f) or object (O). 2427 << ' '; 2428 if (Absolute) { 2429 outs() << "*ABS*"; 2430 } else if (Common) { 2431 outs() << "*COM*"; 2432 } else if (Section == O.section_end()) { 2433 if (O.isXCOFF()) { 2434 XCOFFSymbolRef XCOFFSym = cast<const XCOFFObjectFile>(O).toSymbolRef( 2435 Symbol.getRawDataRefImpl()); 2436 if (XCOFF::N_DEBUG == XCOFFSym.getSectionNumber()) 2437 outs() << "*DEBUG*"; 2438 else 2439 outs() << "*UND*"; 2440 } else 2441 outs() << "*UND*"; 2442 } else { 2443 StringRef SegmentName = getSegmentName(MachO, *Section); 2444 if (!SegmentName.empty()) 2445 outs() << SegmentName << ","; 2446 StringRef SectionName = unwrapOrError(Section->getName(), FileName); 2447 outs() << SectionName; 2448 if (O.isXCOFF()) { 2449 Optional<SymbolRef> SymRef = 2450 getXCOFFSymbolContainingSymbolRef(cast<XCOFFObjectFile>(O), Symbol); 2451 if (SymRef) { 2452 2453 Expected<StringRef> NameOrErr = SymRef->getName(); 2454 2455 if (NameOrErr) { 2456 outs() << " (csect:"; 2457 std::string SymName(NameOrErr.get()); 2458 2459 if (Demangle) 2460 SymName = demangle(SymName); 2461 2462 if (SymbolDescription) 2463 SymName = getXCOFFSymbolDescription( 2464 createSymbolInfo(O, SymRef.value()), SymName); 2465 2466 outs() << ' ' << SymName; 2467 outs() << ") "; 2468 } else 2469 reportWarning(toString(NameOrErr.takeError()), FileName); 2470 } 2471 } 2472 } 2473 2474 if (Common) 2475 outs() << '\t' << format(Fmt, static_cast<uint64_t>(Symbol.getAlignment())); 2476 else if (O.isXCOFF()) 2477 outs() << '\t' 2478 << format(Fmt, cast<XCOFFObjectFile>(O).getSymbolSize( 2479 Symbol.getRawDataRefImpl())); 2480 else if (O.isELF()) 2481 outs() << '\t' << format(Fmt, ELFSymbolRef(Symbol).getSize()); 2482 2483 if (O.isELF()) { 2484 if (!SymbolVersions.empty()) { 2485 const VersionEntry &Ver = 2486 SymbolVersions[Symbol.getRawDataRefImpl().d.b - 1]; 2487 std::string Str; 2488 if (!Ver.Name.empty()) 2489 Str = Ver.IsVerDef ? ' ' + Ver.Name : '(' + Ver.Name + ')'; 2490 outs() << ' ' << left_justify(Str, 12); 2491 } 2492 2493 uint8_t Other = ELFSymbolRef(Symbol).getOther(); 2494 switch (Other) { 2495 case ELF::STV_DEFAULT: 2496 break; 2497 case ELF::STV_INTERNAL: 2498 outs() << " .internal"; 2499 break; 2500 case ELF::STV_HIDDEN: 2501 outs() << " .hidden"; 2502 break; 2503 case ELF::STV_PROTECTED: 2504 outs() << " .protected"; 2505 break; 2506 default: 2507 outs() << format(" 0x%02x", Other); 2508 break; 2509 } 2510 } else if (Hidden) { 2511 outs() << " .hidden"; 2512 } 2513 2514 std::string SymName(Name); 2515 if (Demangle) 2516 SymName = demangle(SymName); 2517 2518 if (O.isXCOFF() && SymbolDescription) 2519 SymName = getXCOFFSymbolDescription(createSymbolInfo(O, Symbol), SymName); 2520 2521 outs() << ' ' << SymName << '\n'; 2522 } 2523 2524 static void printUnwindInfo(const ObjectFile *O) { 2525 outs() << "Unwind info:\n\n"; 2526 2527 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O)) 2528 printCOFFUnwindInfo(Coff); 2529 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O)) 2530 printMachOUnwindInfo(MachO); 2531 else 2532 // TODO: Extract DWARF dump tool to objdump. 2533 WithColor::error(errs(), ToolName) 2534 << "This operation is only currently supported " 2535 "for COFF and MachO object files.\n"; 2536 } 2537 2538 /// Dump the raw contents of the __clangast section so the output can be piped 2539 /// into llvm-bcanalyzer. 2540 static void printRawClangAST(const ObjectFile *Obj) { 2541 if (outs().is_displayed()) { 2542 WithColor::error(errs(), ToolName) 2543 << "The -raw-clang-ast option will dump the raw binary contents of " 2544 "the clang ast section.\n" 2545 "Please redirect the output to a file or another program such as " 2546 "llvm-bcanalyzer.\n"; 2547 return; 2548 } 2549 2550 StringRef ClangASTSectionName("__clangast"); 2551 if (Obj->isCOFF()) { 2552 ClangASTSectionName = "clangast"; 2553 } 2554 2555 Optional<object::SectionRef> ClangASTSection; 2556 for (auto Sec : ToolSectionFilter(*Obj)) { 2557 StringRef Name; 2558 if (Expected<StringRef> NameOrErr = Sec.getName()) 2559 Name = *NameOrErr; 2560 else 2561 consumeError(NameOrErr.takeError()); 2562 2563 if (Name == ClangASTSectionName) { 2564 ClangASTSection = Sec; 2565 break; 2566 } 2567 } 2568 if (!ClangASTSection) 2569 return; 2570 2571 StringRef ClangASTContents = 2572 unwrapOrError(ClangASTSection.value().getContents(), Obj->getFileName()); 2573 outs().write(ClangASTContents.data(), ClangASTContents.size()); 2574 } 2575 2576 static void printFaultMaps(const ObjectFile *Obj) { 2577 StringRef FaultMapSectionName; 2578 2579 if (Obj->isELF()) { 2580 FaultMapSectionName = ".llvm_faultmaps"; 2581 } else if (Obj->isMachO()) { 2582 FaultMapSectionName = "__llvm_faultmaps"; 2583 } else { 2584 WithColor::error(errs(), ToolName) 2585 << "This operation is only currently supported " 2586 "for ELF and Mach-O executable files.\n"; 2587 return; 2588 } 2589 2590 Optional<object::SectionRef> FaultMapSection; 2591 2592 for (auto Sec : ToolSectionFilter(*Obj)) { 2593 StringRef Name; 2594 if (Expected<StringRef> NameOrErr = Sec.getName()) 2595 Name = *NameOrErr; 2596 else 2597 consumeError(NameOrErr.takeError()); 2598 2599 if (Name == FaultMapSectionName) { 2600 FaultMapSection = Sec; 2601 break; 2602 } 2603 } 2604 2605 outs() << "FaultMap table:\n"; 2606 2607 if (!FaultMapSection) { 2608 outs() << "<not found>\n"; 2609 return; 2610 } 2611 2612 StringRef FaultMapContents = 2613 unwrapOrError(FaultMapSection->getContents(), Obj->getFileName()); 2614 FaultMapParser FMP(FaultMapContents.bytes_begin(), 2615 FaultMapContents.bytes_end()); 2616 2617 outs() << FMP; 2618 } 2619 2620 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) { 2621 if (O->isELF()) { 2622 printELFFileHeader(O); 2623 printELFDynamicSection(O); 2624 printELFSymbolVersionInfo(O); 2625 return; 2626 } 2627 if (O->isCOFF()) 2628 return printCOFFFileHeader(cast<object::COFFObjectFile>(*O)); 2629 if (O->isWasm()) 2630 return printWasmFileHeader(O); 2631 if (O->isMachO()) { 2632 printMachOFileHeader(O); 2633 if (!OnlyFirst) 2634 printMachOLoadCommands(O); 2635 return; 2636 } 2637 reportError(O->getFileName(), "Invalid/Unsupported object file format"); 2638 } 2639 2640 static void printFileHeaders(const ObjectFile *O) { 2641 if (!O->isELF() && !O->isCOFF()) 2642 reportError(O->getFileName(), "Invalid/Unsupported object file format"); 2643 2644 Triple::ArchType AT = O->getArch(); 2645 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n"; 2646 uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName()); 2647 2648 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 2649 outs() << "start address: " 2650 << "0x" << format(Fmt.data(), Address) << "\n"; 2651 } 2652 2653 static void printArchiveChild(StringRef Filename, const Archive::Child &C) { 2654 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode(); 2655 if (!ModeOrErr) { 2656 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n"; 2657 consumeError(ModeOrErr.takeError()); 2658 return; 2659 } 2660 sys::fs::perms Mode = ModeOrErr.get(); 2661 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-"); 2662 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-"); 2663 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-"); 2664 outs() << ((Mode & sys::fs::group_read) ? "r" : "-"); 2665 outs() << ((Mode & sys::fs::group_write) ? "w" : "-"); 2666 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-"); 2667 outs() << ((Mode & sys::fs::others_read) ? "r" : "-"); 2668 outs() << ((Mode & sys::fs::others_write) ? "w" : "-"); 2669 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-"); 2670 2671 outs() << " "; 2672 2673 outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename), 2674 unwrapOrError(C.getGID(), Filename), 2675 unwrapOrError(C.getRawSize(), Filename)); 2676 2677 StringRef RawLastModified = C.getRawLastModified(); 2678 unsigned Seconds; 2679 if (RawLastModified.getAsInteger(10, Seconds)) 2680 outs() << "(date: \"" << RawLastModified 2681 << "\" contains non-decimal chars) "; 2682 else { 2683 // Since ctime(3) returns a 26 character string of the form: 2684 // "Sun Sep 16 01:03:52 1973\n\0" 2685 // just print 24 characters. 2686 time_t t = Seconds; 2687 outs() << format("%.24s ", ctime(&t)); 2688 } 2689 2690 StringRef Name = ""; 2691 Expected<StringRef> NameOrErr = C.getName(); 2692 if (!NameOrErr) { 2693 consumeError(NameOrErr.takeError()); 2694 Name = unwrapOrError(C.getRawName(), Filename); 2695 } else { 2696 Name = NameOrErr.get(); 2697 } 2698 outs() << Name << "\n"; 2699 } 2700 2701 // For ELF only now. 2702 static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) { 2703 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj)) { 2704 if (Elf->getEType() != ELF::ET_REL) 2705 return true; 2706 } 2707 return false; 2708 } 2709 2710 static void checkForInvalidStartStopAddress(ObjectFile *Obj, 2711 uint64_t Start, uint64_t Stop) { 2712 if (!shouldWarnForInvalidStartStopAddress(Obj)) 2713 return; 2714 2715 for (const SectionRef &Section : Obj->sections()) 2716 if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) { 2717 uint64_t BaseAddr = Section.getAddress(); 2718 uint64_t Size = Section.getSize(); 2719 if ((Start < BaseAddr + Size) && Stop > BaseAddr) 2720 return; 2721 } 2722 2723 if (!HasStartAddressFlag) 2724 reportWarning("no section has address less than 0x" + 2725 Twine::utohexstr(Stop) + " specified by --stop-address", 2726 Obj->getFileName()); 2727 else if (!HasStopAddressFlag) 2728 reportWarning("no section has address greater than or equal to 0x" + 2729 Twine::utohexstr(Start) + " specified by --start-address", 2730 Obj->getFileName()); 2731 else 2732 reportWarning("no section overlaps the range [0x" + 2733 Twine::utohexstr(Start) + ",0x" + Twine::utohexstr(Stop) + 2734 ") specified by --start-address/--stop-address", 2735 Obj->getFileName()); 2736 } 2737 2738 static void dumpObject(ObjectFile *O, const Archive *A = nullptr, 2739 const Archive::Child *C = nullptr) { 2740 // Avoid other output when using a raw option. 2741 if (!RawClangAST) { 2742 outs() << '\n'; 2743 if (A) 2744 outs() << A->getFileName() << "(" << O->getFileName() << ")"; 2745 else 2746 outs() << O->getFileName(); 2747 outs() << ":\tfile format " << O->getFileFormatName().lower() << "\n"; 2748 } 2749 2750 if (HasStartAddressFlag || HasStopAddressFlag) 2751 checkForInvalidStartStopAddress(O, StartAddress, StopAddress); 2752 2753 // Note: the order here matches GNU objdump for compatability. 2754 StringRef ArchiveName = A ? A->getFileName() : ""; 2755 if (ArchiveHeaders && !MachOOpt && C) 2756 printArchiveChild(ArchiveName, *C); 2757 if (FileHeaders) 2758 printFileHeaders(O); 2759 if (PrivateHeaders || FirstPrivateHeader) 2760 printPrivateFileHeaders(O, FirstPrivateHeader); 2761 if (SectionHeaders) 2762 printSectionHeaders(*O); 2763 if (SymbolTable) 2764 printSymbolTable(*O, ArchiveName); 2765 if (DynamicSymbolTable) 2766 printSymbolTable(*O, ArchiveName, /*ArchitectureName=*/"", 2767 /*DumpDynamic=*/true); 2768 if (DwarfDumpType != DIDT_Null) { 2769 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O); 2770 // Dump the complete DWARF structure. 2771 DIDumpOptions DumpOpts; 2772 DumpOpts.DumpType = DwarfDumpType; 2773 DICtx->dump(outs(), DumpOpts); 2774 } 2775 if (Relocations && !Disassemble) 2776 printRelocations(O); 2777 if (DynamicRelocations) 2778 printDynamicRelocations(O); 2779 if (SectionContents) 2780 printSectionContents(O); 2781 if (Disassemble) 2782 disassembleObject(O, Relocations); 2783 if (UnwindInfo) 2784 printUnwindInfo(O); 2785 2786 // Mach-O specific options: 2787 if (ExportsTrie) 2788 printExportsTrie(O); 2789 if (Rebase) 2790 printRebaseTable(O); 2791 if (Bind) 2792 printBindTable(O); 2793 if (LazyBind) 2794 printLazyBindTable(O); 2795 if (WeakBind) 2796 printWeakBindTable(O); 2797 2798 // Other special sections: 2799 if (RawClangAST) 2800 printRawClangAST(O); 2801 if (FaultMapSection) 2802 printFaultMaps(O); 2803 if (Offloading) 2804 dumpOffloadBinary(*O); 2805 } 2806 2807 static void dumpObject(const COFFImportFile *I, const Archive *A, 2808 const Archive::Child *C = nullptr) { 2809 StringRef ArchiveName = A ? A->getFileName() : ""; 2810 2811 // Avoid other output when using a raw option. 2812 if (!RawClangAST) 2813 outs() << '\n' 2814 << ArchiveName << "(" << I->getFileName() << ")" 2815 << ":\tfile format COFF-import-file" 2816 << "\n\n"; 2817 2818 if (ArchiveHeaders && !MachOOpt && C) 2819 printArchiveChild(ArchiveName, *C); 2820 if (SymbolTable) 2821 printCOFFSymbolTable(*I); 2822 } 2823 2824 /// Dump each object file in \a a; 2825 static void dumpArchive(const Archive *A) { 2826 Error Err = Error::success(); 2827 unsigned I = -1; 2828 for (auto &C : A->children(Err)) { 2829 ++I; 2830 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2831 if (!ChildOrErr) { 2832 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2833 reportError(std::move(E), getFileNameForError(C, I), A->getFileName()); 2834 continue; 2835 } 2836 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 2837 dumpObject(O, A, &C); 2838 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get())) 2839 dumpObject(I, A, &C); 2840 else 2841 reportError(errorCodeToError(object_error::invalid_file_type), 2842 A->getFileName()); 2843 } 2844 if (Err) 2845 reportError(std::move(Err), A->getFileName()); 2846 } 2847 2848 /// Open file and figure out how to dump it. 2849 static void dumpInput(StringRef file) { 2850 // If we are using the Mach-O specific object file parser, then let it parse 2851 // the file and process the command line options. So the -arch flags can 2852 // be used to select specific slices, etc. 2853 if (MachOOpt) { 2854 parseInputMachO(file); 2855 return; 2856 } 2857 2858 // Attempt to open the binary. 2859 OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file); 2860 Binary &Binary = *OBinary.getBinary(); 2861 2862 if (Archive *A = dyn_cast<Archive>(&Binary)) 2863 dumpArchive(A); 2864 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary)) 2865 dumpObject(O); 2866 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary)) 2867 parseInputMachO(UB); 2868 else if (OffloadBinary *OB = dyn_cast<OffloadBinary>(&Binary)) 2869 dumpOffloadSections(*OB); 2870 else 2871 reportError(errorCodeToError(object_error::invalid_file_type), file); 2872 } 2873 2874 template <typename T> 2875 static void parseIntArg(const llvm::opt::InputArgList &InputArgs, int ID, 2876 T &Value) { 2877 if (const opt::Arg *A = InputArgs.getLastArg(ID)) { 2878 StringRef V(A->getValue()); 2879 if (!llvm::to_integer(V, Value, 0)) { 2880 reportCmdLineError(A->getSpelling() + 2881 ": expected a non-negative integer, but got '" + V + 2882 "'"); 2883 } 2884 } 2885 } 2886 2887 static void invalidArgValue(const opt::Arg *A) { 2888 reportCmdLineError("'" + StringRef(A->getValue()) + 2889 "' is not a valid value for '" + A->getSpelling() + "'"); 2890 } 2891 2892 static std::vector<std::string> 2893 commaSeparatedValues(const llvm::opt::InputArgList &InputArgs, int ID) { 2894 std::vector<std::string> Values; 2895 for (StringRef Value : InputArgs.getAllArgValues(ID)) { 2896 llvm::SmallVector<StringRef, 2> SplitValues; 2897 llvm::SplitString(Value, SplitValues, ","); 2898 for (StringRef SplitValue : SplitValues) 2899 Values.push_back(SplitValue.str()); 2900 } 2901 return Values; 2902 } 2903 2904 static void parseOtoolOptions(const llvm::opt::InputArgList &InputArgs) { 2905 MachOOpt = true; 2906 FullLeadingAddr = true; 2907 PrintImmHex = true; 2908 2909 ArchName = InputArgs.getLastArgValue(OTOOL_arch).str(); 2910 LinkOptHints = InputArgs.hasArg(OTOOL_C); 2911 if (InputArgs.hasArg(OTOOL_d)) 2912 FilterSections.push_back("__DATA,__data"); 2913 DylibId = InputArgs.hasArg(OTOOL_D); 2914 UniversalHeaders = InputArgs.hasArg(OTOOL_f); 2915 DataInCode = InputArgs.hasArg(OTOOL_G); 2916 FirstPrivateHeader = InputArgs.hasArg(OTOOL_h); 2917 IndirectSymbols = InputArgs.hasArg(OTOOL_I); 2918 ShowRawInsn = InputArgs.hasArg(OTOOL_j); 2919 PrivateHeaders = InputArgs.hasArg(OTOOL_l); 2920 DylibsUsed = InputArgs.hasArg(OTOOL_L); 2921 MCPU = InputArgs.getLastArgValue(OTOOL_mcpu_EQ).str(); 2922 ObjcMetaData = InputArgs.hasArg(OTOOL_o); 2923 DisSymName = InputArgs.getLastArgValue(OTOOL_p).str(); 2924 InfoPlist = InputArgs.hasArg(OTOOL_P); 2925 Relocations = InputArgs.hasArg(OTOOL_r); 2926 if (const Arg *A = InputArgs.getLastArg(OTOOL_s)) { 2927 auto Filter = (A->getValue(0) + StringRef(",") + A->getValue(1)).str(); 2928 FilterSections.push_back(Filter); 2929 } 2930 if (InputArgs.hasArg(OTOOL_t)) 2931 FilterSections.push_back("__TEXT,__text"); 2932 Verbose = InputArgs.hasArg(OTOOL_v) || InputArgs.hasArg(OTOOL_V) || 2933 InputArgs.hasArg(OTOOL_o); 2934 SymbolicOperands = InputArgs.hasArg(OTOOL_V); 2935 if (InputArgs.hasArg(OTOOL_x)) 2936 FilterSections.push_back(",__text"); 2937 LeadingAddr = LeadingHeaders = !InputArgs.hasArg(OTOOL_X); 2938 2939 ChainedFixups = InputArgs.hasArg(OTOOL_chained_fixups); 2940 DyldInfo = InputArgs.hasArg(OTOOL_dyld_info); 2941 2942 InputFilenames = InputArgs.getAllArgValues(OTOOL_INPUT); 2943 if (InputFilenames.empty()) 2944 reportCmdLineError("no input file"); 2945 2946 for (const Arg *A : InputArgs) { 2947 const Option &O = A->getOption(); 2948 if (O.getGroup().isValid() && O.getGroup().getID() == OTOOL_grp_obsolete) { 2949 reportCmdLineWarning(O.getPrefixedName() + 2950 " is obsolete and not implemented"); 2951 } 2952 } 2953 } 2954 2955 static void parseObjdumpOptions(const llvm::opt::InputArgList &InputArgs) { 2956 parseIntArg(InputArgs, OBJDUMP_adjust_vma_EQ, AdjustVMA); 2957 AllHeaders = InputArgs.hasArg(OBJDUMP_all_headers); 2958 ArchName = InputArgs.getLastArgValue(OBJDUMP_arch_name_EQ).str(); 2959 ArchiveHeaders = InputArgs.hasArg(OBJDUMP_archive_headers); 2960 Demangle = InputArgs.hasArg(OBJDUMP_demangle); 2961 Disassemble = InputArgs.hasArg(OBJDUMP_disassemble); 2962 DisassembleAll = InputArgs.hasArg(OBJDUMP_disassemble_all); 2963 SymbolDescription = InputArgs.hasArg(OBJDUMP_symbol_description); 2964 DisassembleSymbols = 2965 commaSeparatedValues(InputArgs, OBJDUMP_disassemble_symbols_EQ); 2966 DisassembleZeroes = InputArgs.hasArg(OBJDUMP_disassemble_zeroes); 2967 if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_dwarf_EQ)) { 2968 DwarfDumpType = StringSwitch<DIDumpType>(A->getValue()) 2969 .Case("frames", DIDT_DebugFrame) 2970 .Default(DIDT_Null); 2971 if (DwarfDumpType == DIDT_Null) 2972 invalidArgValue(A); 2973 } 2974 DynamicRelocations = InputArgs.hasArg(OBJDUMP_dynamic_reloc); 2975 FaultMapSection = InputArgs.hasArg(OBJDUMP_fault_map_section); 2976 Offloading = InputArgs.hasArg(OBJDUMP_offloading); 2977 FileHeaders = InputArgs.hasArg(OBJDUMP_file_headers); 2978 SectionContents = InputArgs.hasArg(OBJDUMP_full_contents); 2979 PrintLines = InputArgs.hasArg(OBJDUMP_line_numbers); 2980 InputFilenames = InputArgs.getAllArgValues(OBJDUMP_INPUT); 2981 MachOOpt = InputArgs.hasArg(OBJDUMP_macho); 2982 MCPU = InputArgs.getLastArgValue(OBJDUMP_mcpu_EQ).str(); 2983 MAttrs = commaSeparatedValues(InputArgs, OBJDUMP_mattr_EQ); 2984 ShowRawInsn = !InputArgs.hasArg(OBJDUMP_no_show_raw_insn); 2985 LeadingAddr = !InputArgs.hasArg(OBJDUMP_no_leading_addr); 2986 RawClangAST = InputArgs.hasArg(OBJDUMP_raw_clang_ast); 2987 Relocations = InputArgs.hasArg(OBJDUMP_reloc); 2988 PrintImmHex = 2989 InputArgs.hasFlag(OBJDUMP_print_imm_hex, OBJDUMP_no_print_imm_hex, false); 2990 PrivateHeaders = InputArgs.hasArg(OBJDUMP_private_headers); 2991 FilterSections = InputArgs.getAllArgValues(OBJDUMP_section_EQ); 2992 SectionHeaders = InputArgs.hasArg(OBJDUMP_section_headers); 2993 ShowAllSymbols = InputArgs.hasArg(OBJDUMP_show_all_symbols); 2994 ShowLMA = InputArgs.hasArg(OBJDUMP_show_lma); 2995 PrintSource = InputArgs.hasArg(OBJDUMP_source); 2996 parseIntArg(InputArgs, OBJDUMP_start_address_EQ, StartAddress); 2997 HasStartAddressFlag = InputArgs.hasArg(OBJDUMP_start_address_EQ); 2998 parseIntArg(InputArgs, OBJDUMP_stop_address_EQ, StopAddress); 2999 HasStopAddressFlag = InputArgs.hasArg(OBJDUMP_stop_address_EQ); 3000 SymbolTable = InputArgs.hasArg(OBJDUMP_syms); 3001 SymbolizeOperands = InputArgs.hasArg(OBJDUMP_symbolize_operands); 3002 DynamicSymbolTable = InputArgs.hasArg(OBJDUMP_dynamic_syms); 3003 TripleName = InputArgs.getLastArgValue(OBJDUMP_triple_EQ).str(); 3004 UnwindInfo = InputArgs.hasArg(OBJDUMP_unwind_info); 3005 Wide = InputArgs.hasArg(OBJDUMP_wide); 3006 Prefix = InputArgs.getLastArgValue(OBJDUMP_prefix).str(); 3007 parseIntArg(InputArgs, OBJDUMP_prefix_strip, PrefixStrip); 3008 if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_debug_vars_EQ)) { 3009 DbgVariables = StringSwitch<DebugVarsFormat>(A->getValue()) 3010 .Case("ascii", DVASCII) 3011 .Case("unicode", DVUnicode) 3012 .Default(DVInvalid); 3013 if (DbgVariables == DVInvalid) 3014 invalidArgValue(A); 3015 } 3016 parseIntArg(InputArgs, OBJDUMP_debug_vars_indent_EQ, DbgIndent); 3017 3018 parseMachOOptions(InputArgs); 3019 3020 // Parse -M (--disassembler-options) and deprecated 3021 // --x86-asm-syntax={att,intel}. 3022 // 3023 // Note, for x86, the asm dialect (AssemblerDialect) is initialized when the 3024 // MCAsmInfo is constructed. MCInstPrinter::applyTargetSpecificCLOption is 3025 // called too late. For now we have to use the internal cl::opt option. 3026 const char *AsmSyntax = nullptr; 3027 for (const auto *A : InputArgs.filtered(OBJDUMP_disassembler_options_EQ, 3028 OBJDUMP_x86_asm_syntax_att, 3029 OBJDUMP_x86_asm_syntax_intel)) { 3030 switch (A->getOption().getID()) { 3031 case OBJDUMP_x86_asm_syntax_att: 3032 AsmSyntax = "--x86-asm-syntax=att"; 3033 continue; 3034 case OBJDUMP_x86_asm_syntax_intel: 3035 AsmSyntax = "--x86-asm-syntax=intel"; 3036 continue; 3037 } 3038 3039 SmallVector<StringRef, 2> Values; 3040 llvm::SplitString(A->getValue(), Values, ","); 3041 for (StringRef V : Values) { 3042 if (V == "att") 3043 AsmSyntax = "--x86-asm-syntax=att"; 3044 else if (V == "intel") 3045 AsmSyntax = "--x86-asm-syntax=intel"; 3046 else 3047 DisassemblerOptions.push_back(V.str()); 3048 } 3049 } 3050 if (AsmSyntax) { 3051 const char *Argv[] = {"llvm-objdump", AsmSyntax}; 3052 llvm::cl::ParseCommandLineOptions(2, Argv); 3053 } 3054 3055 // objdump defaults to a.out if no filenames specified. 3056 if (InputFilenames.empty()) 3057 InputFilenames.push_back("a.out"); 3058 } 3059 3060 int main(int argc, char **argv) { 3061 using namespace llvm; 3062 InitLLVM X(argc, argv); 3063 3064 ToolName = argv[0]; 3065 std::unique_ptr<CommonOptTable> T; 3066 OptSpecifier Unknown, HelpFlag, HelpHiddenFlag, VersionFlag; 3067 3068 StringRef Stem = sys::path::stem(ToolName); 3069 auto Is = [=](StringRef Tool) { 3070 // We need to recognize the following filenames: 3071 // 3072 // llvm-objdump -> objdump 3073 // llvm-otool-10.exe -> otool 3074 // powerpc64-unknown-freebsd13-objdump -> objdump 3075 auto I = Stem.rfind_insensitive(Tool); 3076 return I != StringRef::npos && 3077 (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()])); 3078 }; 3079 if (Is("otool")) { 3080 T = std::make_unique<OtoolOptTable>(); 3081 Unknown = OTOOL_UNKNOWN; 3082 HelpFlag = OTOOL_help; 3083 HelpHiddenFlag = OTOOL_help_hidden; 3084 VersionFlag = OTOOL_version; 3085 } else { 3086 T = std::make_unique<ObjdumpOptTable>(); 3087 Unknown = OBJDUMP_UNKNOWN; 3088 HelpFlag = OBJDUMP_help; 3089 HelpHiddenFlag = OBJDUMP_help_hidden; 3090 VersionFlag = OBJDUMP_version; 3091 } 3092 3093 BumpPtrAllocator A; 3094 StringSaver Saver(A); 3095 opt::InputArgList InputArgs = 3096 T->parseArgs(argc, argv, Unknown, Saver, 3097 [&](StringRef Msg) { reportCmdLineError(Msg); }); 3098 3099 if (InputArgs.size() == 0 || InputArgs.hasArg(HelpFlag)) { 3100 T->printHelp(ToolName); 3101 return 0; 3102 } 3103 if (InputArgs.hasArg(HelpHiddenFlag)) { 3104 T->printHelp(ToolName, /*ShowHidden=*/true); 3105 return 0; 3106 } 3107 3108 // Initialize targets and assembly printers/parsers. 3109 InitializeAllTargetInfos(); 3110 InitializeAllTargetMCs(); 3111 InitializeAllDisassemblers(); 3112 3113 if (InputArgs.hasArg(VersionFlag)) { 3114 cl::PrintVersionMessage(); 3115 if (!Is("otool")) { 3116 outs() << '\n'; 3117 TargetRegistry::printRegisteredTargetsForVersion(outs()); 3118 } 3119 return 0; 3120 } 3121 3122 // Initialize debuginfod. 3123 const bool ShouldUseDebuginfodByDefault = 3124 HTTPClient::isAvailable() && 3125 !ExitOnErr(getDefaultDebuginfodUrls()).empty(); 3126 std::vector<std::string> DebugFileDirectories = 3127 InputArgs.getAllArgValues(OBJDUMP_debug_file_directory); 3128 if (InputArgs.hasFlag(OBJDUMP_debuginfod, OBJDUMP_no_debuginfod, 3129 ShouldUseDebuginfodByDefault)) { 3130 HTTPClient::initialize(); 3131 BIDFetcher = 3132 std::make_unique<DebuginfodFetcher>(std::move(DebugFileDirectories)); 3133 } else { 3134 BIDFetcher = 3135 std::make_unique<BuildIDFetcher>(std::move(DebugFileDirectories)); 3136 } 3137 3138 if (Is("otool")) 3139 parseOtoolOptions(InputArgs); 3140 else 3141 parseObjdumpOptions(InputArgs); 3142 3143 if (StartAddress >= StopAddress) 3144 reportCmdLineError("start address should be less than stop address"); 3145 3146 // Removes trailing separators from prefix. 3147 while (!Prefix.empty() && sys::path::is_separator(Prefix.back())) 3148 Prefix.pop_back(); 3149 3150 if (AllHeaders) 3151 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations = 3152 SectionHeaders = SymbolTable = true; 3153 3154 if (DisassembleAll || PrintSource || PrintLines || 3155 !DisassembleSymbols.empty()) 3156 Disassemble = true; 3157 3158 if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null && 3159 !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST && 3160 !Relocations && !SectionHeaders && !SectionContents && !SymbolTable && 3161 !DynamicSymbolTable && !UnwindInfo && !FaultMapSection && !Offloading && 3162 !(MachOOpt && 3163 (Bind || DataInCode || ChainedFixups || DyldInfo || DylibId || 3164 DylibsUsed || ExportsTrie || FirstPrivateHeader || FunctionStarts || 3165 IndirectSymbols || InfoPlist || LazyBind || LinkOptHints || 3166 ObjcMetaData || Rebase || Rpaths || UniversalHeaders || WeakBind || 3167 !FilterSections.empty()))) { 3168 T->printHelp(ToolName); 3169 return 2; 3170 } 3171 3172 DisasmSymbolSet.insert(DisassembleSymbols.begin(), DisassembleSymbols.end()); 3173 3174 llvm::for_each(InputFilenames, dumpInput); 3175 3176 warnOnNoMatchForSections(); 3177 3178 return EXIT_SUCCESS; 3179 } 3180