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