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