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