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/Twine.h" 31 #include "llvm/BinaryFormat/Wasm.h" 32 #include "llvm/DebugInfo/BTF/BTFParser.h" 33 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 34 #include "llvm/DebugInfo/Symbolize/Symbolize.h" 35 #include "llvm/Debuginfod/BuildIDFetcher.h" 36 #include "llvm/Debuginfod/Debuginfod.h" 37 #include "llvm/Debuginfod/HTTPClient.h" 38 #include "llvm/Demangle/Demangle.h" 39 #include "llvm/MC/MCAsmInfo.h" 40 #include "llvm/MC/MCContext.h" 41 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h" 42 #include "llvm/MC/MCInst.h" 43 #include "llvm/MC/MCInstPrinter.h" 44 #include "llvm/MC/MCInstrAnalysis.h" 45 #include "llvm/MC/MCInstrInfo.h" 46 #include "llvm/MC/MCObjectFileInfo.h" 47 #include "llvm/MC/MCRegisterInfo.h" 48 #include "llvm/MC/MCTargetOptions.h" 49 #include "llvm/MC/TargetRegistry.h" 50 #include "llvm/Object/BuildID.h" 51 #include "llvm/Object/COFF.h" 52 #include "llvm/Object/COFFImportFile.h" 53 #include "llvm/Object/ELFObjectFile.h" 54 #include "llvm/Object/ELFTypes.h" 55 #include "llvm/Object/FaultMapParser.h" 56 #include "llvm/Object/MachO.h" 57 #include "llvm/Object/MachOUniversal.h" 58 #include "llvm/Object/OffloadBinary.h" 59 #include "llvm/Object/Wasm.h" 60 #include "llvm/Option/Arg.h" 61 #include "llvm/Option/ArgList.h" 62 #include "llvm/Option/Option.h" 63 #include "llvm/Support/Casting.h" 64 #include "llvm/Support/Debug.h" 65 #include "llvm/Support/Errc.h" 66 #include "llvm/Support/FileSystem.h" 67 #include "llvm/Support/Format.h" 68 #include "llvm/Support/FormatVariadic.h" 69 #include "llvm/Support/GraphWriter.h" 70 #include "llvm/Support/LLVMDriver.h" 71 #include "llvm/Support/MemoryBuffer.h" 72 #include "llvm/Support/SourceMgr.h" 73 #include "llvm/Support/StringSaver.h" 74 #include "llvm/Support/TargetSelect.h" 75 #include "llvm/Support/WithColor.h" 76 #include "llvm/Support/raw_ostream.h" 77 #include "llvm/TargetParser/Host.h" 78 #include "llvm/TargetParser/Triple.h" 79 #include <algorithm> 80 #include <cctype> 81 #include <cstring> 82 #include <optional> 83 #include <set> 84 #include <system_error> 85 #include <unordered_map> 86 #include <utility> 87 88 using namespace llvm; 89 using namespace llvm::object; 90 using namespace llvm::objdump; 91 using namespace llvm::opt; 92 93 namespace { 94 95 class CommonOptTable : public opt::GenericOptTable { 96 public: 97 CommonOptTable(const char *StrTable, ArrayRef<unsigned> PrefixesTable, 98 ArrayRef<Info> OptionInfos, const char *Usage, 99 const char *Description) 100 : opt::GenericOptTable(StrTable, PrefixesTable, OptionInfos), 101 Usage(Usage), Description(Description) { 102 setGroupedShortOptions(true); 103 } 104 105 void printHelp(StringRef Argv0, bool ShowHidden = false) const { 106 Argv0 = sys::path::filename(Argv0); 107 opt::GenericOptTable::printHelp(outs(), (Argv0 + Usage).str().c_str(), 108 Description, ShowHidden, ShowHidden); 109 // TODO Replace this with OptTable API once it adds extrahelp support. 110 outs() << "\nPass @FILE as argument to read options from FILE.\n"; 111 } 112 113 private: 114 const char *Usage; 115 const char *Description; 116 }; 117 118 // ObjdumpOptID is in ObjdumpOptID.h 119 namespace objdump_opt { 120 #define OPTTABLE_STR_TABLE_CODE 121 #include "ObjdumpOpts.inc" 122 #undef OPTTABLE_STR_TABLE_CODE 123 124 #define OPTTABLE_PREFIXES_TABLE_CODE 125 #include "ObjdumpOpts.inc" 126 #undef OPTTABLE_PREFIXES_TABLE_CODE 127 128 static constexpr opt::OptTable::Info ObjdumpInfoTable[] = { 129 #define OPTION(...) \ 130 LLVM_CONSTRUCT_OPT_INFO_WITH_ID_PREFIX(OBJDUMP_, __VA_ARGS__), 131 #include "ObjdumpOpts.inc" 132 #undef OPTION 133 }; 134 } // namespace objdump_opt 135 136 class ObjdumpOptTable : public CommonOptTable { 137 public: 138 ObjdumpOptTable() 139 : CommonOptTable( 140 objdump_opt::OptionStrTable, objdump_opt::OptionPrefixesTable, 141 objdump_opt::ObjdumpInfoTable, " [options] <input object files>", 142 "llvm object file dumper") {} 143 }; 144 145 enum OtoolOptID { 146 OTOOL_INVALID = 0, // This is not an option ID. 147 #define OPTION(...) LLVM_MAKE_OPT_ID_WITH_ID_PREFIX(OTOOL_, __VA_ARGS__), 148 #include "OtoolOpts.inc" 149 #undef OPTION 150 }; 151 152 namespace otool { 153 #define OPTTABLE_STR_TABLE_CODE 154 #include "OtoolOpts.inc" 155 #undef OPTTABLE_STR_TABLE_CODE 156 157 #define OPTTABLE_PREFIXES_TABLE_CODE 158 #include "OtoolOpts.inc" 159 #undef OPTTABLE_PREFIXES_TABLE_CODE 160 161 static constexpr opt::OptTable::Info OtoolInfoTable[] = { 162 #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO_WITH_ID_PREFIX(OTOOL_, __VA_ARGS__), 163 #include "OtoolOpts.inc" 164 #undef OPTION 165 }; 166 } // namespace otool 167 168 class OtoolOptTable : public CommonOptTable { 169 public: 170 OtoolOptTable() 171 : CommonOptTable(otool::OptionStrTable, otool::OptionPrefixesTable, 172 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 std::vector<std::string> objdump::DisassemblerOptions; 309 bool objdump::SymbolDescription; 310 bool objdump::TracebackTable; 311 static std::vector<std::string> DisassembleSymbols; 312 static bool DisassembleZeroes; 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 class RISCVPrettyPrinter : public PrettyPrinter { 951 public: 952 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 953 object::SectionedAddress Address, formatted_raw_ostream &OS, 954 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, 955 StringRef ObjectFilename, std::vector<RelocationRef> *Rels, 956 LiveVariablePrinter &LVP) override { 957 if (SP && (PrintSource || PrintLines)) 958 SP->printSourceLine(OS, Address, ObjectFilename, LVP); 959 LVP.printBetweenInsts(OS, false); 960 961 size_t Start = OS.tell(); 962 if (LeadingAddr) 963 OS << format("%8" PRIx64 ":", Address.Address); 964 if (ShowRawInsn) { 965 size_t Pos = 0, End = Bytes.size(); 966 if (End % 4 == 0) { 967 // 32-bit and 64-bit instructions. 968 for (; Pos + 4 <= End; Pos += 4) 969 OS << ' ' 970 << format_hex_no_prefix( 971 llvm::support::endian::read<uint32_t>( 972 Bytes.data() + Pos, llvm::endianness::little), 973 8); 974 } else if (End % 2 == 0) { 975 // 16-bit and 48-bits instructions. 976 for (; Pos + 2 <= End; Pos += 2) 977 OS << ' ' 978 << format_hex_no_prefix( 979 llvm::support::endian::read<uint16_t>( 980 Bytes.data() + Pos, llvm::endianness::little), 981 4); 982 } 983 if (Pos < End) { 984 OS << ' '; 985 dumpBytes(Bytes.slice(Pos), OS); 986 } 987 } 988 989 AlignToInstStartColumn(Start, STI, OS); 990 991 if (MI) { 992 IP.printInst(MI, Address.Address, "", STI, OS); 993 } else 994 OS << "\t<unknown>"; 995 } 996 }; 997 RISCVPrettyPrinter RISCVPrettyPrinterInst; 998 999 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) { 1000 switch(Triple.getArch()) { 1001 default: 1002 return PrettyPrinterInst; 1003 case Triple::hexagon: 1004 return HexagonPrettyPrinterInst; 1005 case Triple::amdgcn: 1006 return AMDGCNPrettyPrinterInst; 1007 case Triple::bpfel: 1008 case Triple::bpfeb: 1009 return BPFPrettyPrinterInst; 1010 case Triple::arm: 1011 case Triple::armeb: 1012 case Triple::thumb: 1013 case Triple::thumbeb: 1014 return ARMPrettyPrinterInst; 1015 case Triple::aarch64: 1016 case Triple::aarch64_be: 1017 case Triple::aarch64_32: 1018 return AArch64PrettyPrinterInst; 1019 case Triple::riscv32: 1020 case Triple::riscv64: 1021 return RISCVPrettyPrinterInst; 1022 } 1023 } 1024 1025 class DisassemblerTarget { 1026 public: 1027 const Target *TheTarget; 1028 std::unique_ptr<const MCSubtargetInfo> SubtargetInfo; 1029 std::shared_ptr<MCContext> Context; 1030 std::unique_ptr<MCDisassembler> DisAsm; 1031 std::shared_ptr<MCInstrAnalysis> InstrAnalysis; 1032 std::shared_ptr<MCInstPrinter> InstPrinter; 1033 PrettyPrinter *Printer; 1034 1035 DisassemblerTarget(const Target *TheTarget, ObjectFile &Obj, 1036 StringRef TripleName, StringRef MCPU, 1037 SubtargetFeatures &Features); 1038 DisassemblerTarget(DisassemblerTarget &Other, SubtargetFeatures &Features); 1039 1040 private: 1041 MCTargetOptions Options; 1042 std::shared_ptr<const MCRegisterInfo> RegisterInfo; 1043 std::shared_ptr<const MCAsmInfo> AsmInfo; 1044 std::shared_ptr<const MCInstrInfo> InstrInfo; 1045 std::shared_ptr<MCObjectFileInfo> ObjectFileInfo; 1046 }; 1047 1048 DisassemblerTarget::DisassemblerTarget(const Target *TheTarget, ObjectFile &Obj, 1049 StringRef TripleName, StringRef MCPU, 1050 SubtargetFeatures &Features) 1051 : TheTarget(TheTarget), 1052 Printer(&selectPrettyPrinter(Triple(TripleName))), 1053 RegisterInfo(TheTarget->createMCRegInfo(TripleName)) { 1054 if (!RegisterInfo) 1055 reportError(Obj.getFileName(), "no register info for target " + TripleName); 1056 1057 // Set up disassembler. 1058 AsmInfo.reset(TheTarget->createMCAsmInfo(*RegisterInfo, TripleName, Options)); 1059 if (!AsmInfo) 1060 reportError(Obj.getFileName(), "no assembly info for target " + TripleName); 1061 1062 SubtargetInfo.reset( 1063 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString())); 1064 if (!SubtargetInfo) 1065 reportError(Obj.getFileName(), 1066 "no subtarget info for target " + TripleName); 1067 InstrInfo.reset(TheTarget->createMCInstrInfo()); 1068 if (!InstrInfo) 1069 reportError(Obj.getFileName(), 1070 "no instruction info for target " + TripleName); 1071 Context = 1072 std::make_shared<MCContext>(Triple(TripleName), AsmInfo.get(), 1073 RegisterInfo.get(), SubtargetInfo.get()); 1074 1075 // FIXME: for now initialize MCObjectFileInfo with default values 1076 ObjectFileInfo.reset( 1077 TheTarget->createMCObjectFileInfo(*Context, /*PIC=*/false)); 1078 Context->setObjectFileInfo(ObjectFileInfo.get()); 1079 1080 DisAsm.reset(TheTarget->createMCDisassembler(*SubtargetInfo, *Context)); 1081 if (!DisAsm) 1082 reportError(Obj.getFileName(), "no disassembler for target " + TripleName); 1083 1084 if (auto *ELFObj = dyn_cast<ELFObjectFileBase>(&Obj)) 1085 DisAsm->setABIVersion(ELFObj->getEIdentABIVersion()); 1086 1087 InstrAnalysis.reset(TheTarget->createMCInstrAnalysis(InstrInfo.get())); 1088 1089 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 1090 InstPrinter.reset(TheTarget->createMCInstPrinter(Triple(TripleName), 1091 AsmPrinterVariant, *AsmInfo, 1092 *InstrInfo, *RegisterInfo)); 1093 if (!InstPrinter) 1094 reportError(Obj.getFileName(), 1095 "no instruction printer for target " + TripleName); 1096 InstPrinter->setPrintImmHex(PrintImmHex); 1097 InstPrinter->setPrintBranchImmAsAddress(true); 1098 InstPrinter->setSymbolizeOperands(SymbolizeOperands); 1099 InstPrinter->setMCInstrAnalysis(InstrAnalysis.get()); 1100 1101 switch (DisassemblyColor) { 1102 case ColorOutput::Enable: 1103 InstPrinter->setUseColor(true); 1104 break; 1105 case ColorOutput::Auto: 1106 InstPrinter->setUseColor(outs().has_colors()); 1107 break; 1108 case ColorOutput::Disable: 1109 case ColorOutput::Invalid: 1110 InstPrinter->setUseColor(false); 1111 break; 1112 }; 1113 } 1114 1115 DisassemblerTarget::DisassemblerTarget(DisassemblerTarget &Other, 1116 SubtargetFeatures &Features) 1117 : TheTarget(Other.TheTarget), 1118 SubtargetInfo(TheTarget->createMCSubtargetInfo(TripleName, MCPU, 1119 Features.getString())), 1120 Context(Other.Context), 1121 DisAsm(TheTarget->createMCDisassembler(*SubtargetInfo, *Context)), 1122 InstrAnalysis(Other.InstrAnalysis), InstPrinter(Other.InstPrinter), 1123 Printer(Other.Printer), RegisterInfo(Other.RegisterInfo), 1124 AsmInfo(Other.AsmInfo), InstrInfo(Other.InstrInfo), 1125 ObjectFileInfo(Other.ObjectFileInfo) {} 1126 } // namespace 1127 1128 static uint8_t getElfSymbolType(const ObjectFile &Obj, const SymbolRef &Sym) { 1129 assert(Obj.isELF()); 1130 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(&Obj)) 1131 return unwrapOrError(Elf32LEObj->getSymbol(Sym.getRawDataRefImpl()), 1132 Obj.getFileName()) 1133 ->getType(); 1134 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(&Obj)) 1135 return unwrapOrError(Elf64LEObj->getSymbol(Sym.getRawDataRefImpl()), 1136 Obj.getFileName()) 1137 ->getType(); 1138 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(&Obj)) 1139 return unwrapOrError(Elf32BEObj->getSymbol(Sym.getRawDataRefImpl()), 1140 Obj.getFileName()) 1141 ->getType(); 1142 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(&Obj)) 1143 return unwrapOrError(Elf64BEObj->getSymbol(Sym.getRawDataRefImpl()), 1144 Obj.getFileName()) 1145 ->getType(); 1146 llvm_unreachable("Unsupported binary format"); 1147 } 1148 1149 template <class ELFT> 1150 static void 1151 addDynamicElfSymbols(const ELFObjectFile<ELFT> &Obj, 1152 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { 1153 for (auto Symbol : Obj.getDynamicSymbolIterators()) { 1154 uint8_t SymbolType = Symbol.getELFType(); 1155 if (SymbolType == ELF::STT_SECTION) 1156 continue; 1157 1158 uint64_t Address = unwrapOrError(Symbol.getAddress(), Obj.getFileName()); 1159 // ELFSymbolRef::getAddress() returns size instead of value for common 1160 // symbols which is not desirable for disassembly output. Overriding. 1161 if (SymbolType == ELF::STT_COMMON) 1162 Address = unwrapOrError(Obj.getSymbol(Symbol.getRawDataRefImpl()), 1163 Obj.getFileName()) 1164 ->st_value; 1165 1166 StringRef Name = unwrapOrError(Symbol.getName(), Obj.getFileName()); 1167 if (Name.empty()) 1168 continue; 1169 1170 section_iterator SecI = 1171 unwrapOrError(Symbol.getSection(), Obj.getFileName()); 1172 if (SecI == Obj.section_end()) 1173 continue; 1174 1175 AllSymbols[*SecI].emplace_back(Address, Name, SymbolType); 1176 } 1177 } 1178 1179 static void 1180 addDynamicElfSymbols(const ELFObjectFileBase &Obj, 1181 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { 1182 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(&Obj)) 1183 addDynamicElfSymbols(*Elf32LEObj, AllSymbols); 1184 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(&Obj)) 1185 addDynamicElfSymbols(*Elf64LEObj, AllSymbols); 1186 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(&Obj)) 1187 addDynamicElfSymbols(*Elf32BEObj, AllSymbols); 1188 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(&Obj)) 1189 addDynamicElfSymbols(*Elf64BEObj, AllSymbols); 1190 else 1191 llvm_unreachable("Unsupported binary format"); 1192 } 1193 1194 static std::optional<SectionRef> getWasmCodeSection(const WasmObjectFile &Obj) { 1195 for (auto SecI : Obj.sections()) { 1196 const WasmSection &Section = Obj.getWasmSection(SecI); 1197 if (Section.Type == wasm::WASM_SEC_CODE) 1198 return SecI; 1199 } 1200 return std::nullopt; 1201 } 1202 1203 static void 1204 addMissingWasmCodeSymbols(const WasmObjectFile &Obj, 1205 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { 1206 std::optional<SectionRef> Section = getWasmCodeSection(Obj); 1207 if (!Section) 1208 return; 1209 SectionSymbolsTy &Symbols = AllSymbols[*Section]; 1210 1211 std::set<uint64_t> SymbolAddresses; 1212 for (const auto &Sym : Symbols) 1213 SymbolAddresses.insert(Sym.Addr); 1214 1215 for (const wasm::WasmFunction &Function : Obj.functions()) { 1216 // This adjustment mirrors the one in WasmObjectFile::getSymbolAddress. 1217 uint32_t Adjustment = Obj.isRelocatableObject() || Obj.isSharedObject() 1218 ? 0 1219 : Section->getAddress(); 1220 uint64_t Address = Function.CodeSectionOffset + Adjustment; 1221 // Only add fallback symbols for functions not already present in the symbol 1222 // table. 1223 if (SymbolAddresses.count(Address)) 1224 continue; 1225 // This function has no symbol, so it should have no SymbolName. 1226 assert(Function.SymbolName.empty()); 1227 // We use DebugName for the name, though it may be empty if there is no 1228 // "name" custom section, or that section is missing a name for this 1229 // function. 1230 StringRef Name = Function.DebugName; 1231 Symbols.emplace_back(Address, Name, ELF::STT_NOTYPE); 1232 } 1233 } 1234 1235 static void addPltEntries(const ObjectFile &Obj, 1236 std::map<SectionRef, SectionSymbolsTy> &AllSymbols, 1237 StringSaver &Saver) { 1238 auto *ElfObj = dyn_cast<ELFObjectFileBase>(&Obj); 1239 if (!ElfObj) 1240 return; 1241 DenseMap<StringRef, SectionRef> Sections; 1242 for (SectionRef Section : Obj.sections()) { 1243 Expected<StringRef> SecNameOrErr = Section.getName(); 1244 if (!SecNameOrErr) { 1245 consumeError(SecNameOrErr.takeError()); 1246 continue; 1247 } 1248 Sections[*SecNameOrErr] = Section; 1249 } 1250 for (auto Plt : ElfObj->getPltEntries()) { 1251 if (Plt.Symbol) { 1252 SymbolRef Symbol(*Plt.Symbol, ElfObj); 1253 uint8_t SymbolType = getElfSymbolType(Obj, Symbol); 1254 if (Expected<StringRef> NameOrErr = Symbol.getName()) { 1255 if (!NameOrErr->empty()) 1256 AllSymbols[Sections[Plt.Section]].emplace_back( 1257 Plt.Address, Saver.save((*NameOrErr + "@plt").str()), SymbolType); 1258 continue; 1259 } else { 1260 // The warning has been reported in disassembleObject(). 1261 consumeError(NameOrErr.takeError()); 1262 } 1263 } 1264 reportWarning("PLT entry at 0x" + Twine::utohexstr(Plt.Address) + 1265 " references an invalid symbol", 1266 Obj.getFileName()); 1267 } 1268 } 1269 1270 // Normally the disassembly output will skip blocks of zeroes. This function 1271 // returns the number of zero bytes that can be skipped when dumping the 1272 // disassembly of the instructions in Buf. 1273 static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) { 1274 // Find the number of leading zeroes. 1275 size_t N = 0; 1276 while (N < Buf.size() && !Buf[N]) 1277 ++N; 1278 1279 // We may want to skip blocks of zero bytes, but unless we see 1280 // at least 8 of them in a row. 1281 if (N < 8) 1282 return 0; 1283 1284 // We skip zeroes in multiples of 4 because do not want to truncate an 1285 // instruction if it starts with a zero byte. 1286 return N & ~0x3; 1287 } 1288 1289 // Returns a map from sections to their relocations. 1290 static std::map<SectionRef, std::vector<RelocationRef>> 1291 getRelocsMap(object::ObjectFile const &Obj) { 1292 std::map<SectionRef, std::vector<RelocationRef>> Ret; 1293 uint64_t I = (uint64_t)-1; 1294 for (SectionRef Sec : Obj.sections()) { 1295 ++I; 1296 Expected<section_iterator> RelocatedOrErr = Sec.getRelocatedSection(); 1297 if (!RelocatedOrErr) 1298 reportError(Obj.getFileName(), 1299 "section (" + Twine(I) + 1300 "): failed to get a relocated section: " + 1301 toString(RelocatedOrErr.takeError())); 1302 1303 section_iterator Relocated = *RelocatedOrErr; 1304 if (Relocated == Obj.section_end() || !checkSectionFilter(*Relocated).Keep) 1305 continue; 1306 std::vector<RelocationRef> &V = Ret[*Relocated]; 1307 append_range(V, Sec.relocations()); 1308 // Sort relocations by address. 1309 llvm::stable_sort(V, isRelocAddressLess); 1310 } 1311 return Ret; 1312 } 1313 1314 // Used for --adjust-vma to check if address should be adjusted by the 1315 // specified value for a given section. 1316 // For ELF we do not adjust non-allocatable sections like debug ones, 1317 // because they are not loadable. 1318 // TODO: implement for other file formats. 1319 static bool shouldAdjustVA(const SectionRef &Section) { 1320 const ObjectFile *Obj = Section.getObject(); 1321 if (Obj->isELF()) 1322 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC; 1323 return false; 1324 } 1325 1326 1327 typedef std::pair<uint64_t, char> MappingSymbolPair; 1328 static char getMappingSymbolKind(ArrayRef<MappingSymbolPair> MappingSymbols, 1329 uint64_t Address) { 1330 auto It = 1331 partition_point(MappingSymbols, [Address](const MappingSymbolPair &Val) { 1332 return Val.first <= Address; 1333 }); 1334 // Return zero for any address before the first mapping symbol; this means 1335 // we should use the default disassembly mode, depending on the target. 1336 if (It == MappingSymbols.begin()) 1337 return '\x00'; 1338 return (It - 1)->second; 1339 } 1340 1341 static uint64_t dumpARMELFData(uint64_t SectionAddr, uint64_t Index, 1342 uint64_t End, const ObjectFile &Obj, 1343 ArrayRef<uint8_t> Bytes, 1344 ArrayRef<MappingSymbolPair> MappingSymbols, 1345 const MCSubtargetInfo &STI, raw_ostream &OS) { 1346 llvm::endianness Endian = 1347 Obj.isLittleEndian() ? llvm::endianness::little : llvm::endianness::big; 1348 size_t Start = OS.tell(); 1349 OS << format("%8" PRIx64 ": ", SectionAddr + Index); 1350 if (Index + 4 <= End) { 1351 dumpBytes(Bytes.slice(Index, 4), OS); 1352 AlignToInstStartColumn(Start, STI, OS); 1353 OS << "\t.word\t" 1354 << format_hex(support::endian::read32(Bytes.data() + Index, Endian), 1355 10); 1356 return 4; 1357 } 1358 if (Index + 2 <= End) { 1359 dumpBytes(Bytes.slice(Index, 2), OS); 1360 AlignToInstStartColumn(Start, STI, OS); 1361 OS << "\t.short\t" 1362 << format_hex(support::endian::read16(Bytes.data() + Index, Endian), 6); 1363 return 2; 1364 } 1365 dumpBytes(Bytes.slice(Index, 1), OS); 1366 AlignToInstStartColumn(Start, STI, OS); 1367 OS << "\t.byte\t" << format_hex(Bytes[Index], 4); 1368 return 1; 1369 } 1370 1371 static void dumpELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End, 1372 ArrayRef<uint8_t> Bytes) { 1373 // print out data up to 8 bytes at a time in hex and ascii 1374 uint8_t AsciiData[9] = {'\0'}; 1375 uint8_t Byte; 1376 int NumBytes = 0; 1377 1378 for (; Index < End; ++Index) { 1379 if (NumBytes == 0) 1380 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 1381 Byte = Bytes.slice(Index)[0]; 1382 outs() << format(" %02x", Byte); 1383 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.'; 1384 1385 uint8_t IndentOffset = 0; 1386 NumBytes++; 1387 if (Index == End - 1 || NumBytes > 8) { 1388 // Indent the space for less than 8 bytes data. 1389 // 2 spaces for byte and one for space between bytes 1390 IndentOffset = 3 * (8 - NumBytes); 1391 for (int Excess = NumBytes; Excess < 8; Excess++) 1392 AsciiData[Excess] = '\0'; 1393 NumBytes = 8; 1394 } 1395 if (NumBytes == 8) { 1396 AsciiData[8] = '\0'; 1397 outs() << std::string(IndentOffset, ' ') << " "; 1398 outs() << reinterpret_cast<char *>(AsciiData); 1399 outs() << '\n'; 1400 NumBytes = 0; 1401 } 1402 } 1403 } 1404 1405 SymbolInfoTy objdump::createSymbolInfo(const ObjectFile &Obj, 1406 const SymbolRef &Symbol, 1407 bool IsMappingSymbol) { 1408 const StringRef FileName = Obj.getFileName(); 1409 const uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName); 1410 const StringRef Name = unwrapOrError(Symbol.getName(), FileName); 1411 1412 if (Obj.isXCOFF() && (SymbolDescription || TracebackTable)) { 1413 const auto &XCOFFObj = cast<XCOFFObjectFile>(Obj); 1414 DataRefImpl SymbolDRI = Symbol.getRawDataRefImpl(); 1415 1416 const uint32_t SymbolIndex = XCOFFObj.getSymbolIndex(SymbolDRI.p); 1417 std::optional<XCOFF::StorageMappingClass> Smc = 1418 getXCOFFSymbolCsectSMC(XCOFFObj, Symbol); 1419 return SymbolInfoTy(Smc, Addr, Name, SymbolIndex, 1420 isLabel(XCOFFObj, Symbol)); 1421 } else if (Obj.isXCOFF()) { 1422 const SymbolRef::Type SymType = unwrapOrError(Symbol.getType(), FileName); 1423 return SymbolInfoTy(Addr, Name, SymType, /*IsMappingSymbol=*/false, 1424 /*IsXCOFF=*/true); 1425 } else if (Obj.isWasm()) { 1426 uint8_t SymType = 1427 cast<WasmObjectFile>(&Obj)->getWasmSymbol(Symbol).Info.Kind; 1428 return SymbolInfoTy(Addr, Name, SymType, false); 1429 } else { 1430 uint8_t Type = 1431 Obj.isELF() ? getElfSymbolType(Obj, Symbol) : (uint8_t)ELF::STT_NOTYPE; 1432 return SymbolInfoTy(Addr, Name, Type, IsMappingSymbol); 1433 } 1434 } 1435 1436 static SymbolInfoTy createDummySymbolInfo(const ObjectFile &Obj, 1437 const uint64_t Addr, StringRef &Name, 1438 uint8_t Type) { 1439 if (Obj.isXCOFF() && (SymbolDescription || TracebackTable)) 1440 return SymbolInfoTy(std::nullopt, Addr, Name, std::nullopt, false); 1441 if (Obj.isWasm()) 1442 return SymbolInfoTy(Addr, Name, wasm::WASM_SYMBOL_TYPE_SECTION); 1443 return SymbolInfoTy(Addr, Name, Type); 1444 } 1445 1446 static void collectBBAddrMapLabels( 1447 const BBAddrMapInfo &FullAddrMap, uint64_t SectionAddr, uint64_t Start, 1448 uint64_t End, 1449 std::unordered_map<uint64_t, std::vector<BBAddrMapLabel>> &Labels) { 1450 if (FullAddrMap.empty()) 1451 return; 1452 Labels.clear(); 1453 uint64_t StartAddress = SectionAddr + Start; 1454 uint64_t EndAddress = SectionAddr + End; 1455 const BBAddrMapFunctionEntry *FunctionMap = 1456 FullAddrMap.getEntryForAddress(StartAddress); 1457 if (!FunctionMap) 1458 return; 1459 std::optional<size_t> BBRangeIndex = 1460 FunctionMap->getAddrMap().getBBRangeIndexForBaseAddress(StartAddress); 1461 if (!BBRangeIndex) 1462 return; 1463 size_t NumBBEntriesBeforeRange = 0; 1464 for (size_t I = 0; I < *BBRangeIndex; ++I) 1465 NumBBEntriesBeforeRange += 1466 FunctionMap->getAddrMap().BBRanges[I].BBEntries.size(); 1467 const auto &BBRange = FunctionMap->getAddrMap().BBRanges[*BBRangeIndex]; 1468 for (size_t I = 0; I < BBRange.BBEntries.size(); ++I) { 1469 const BBAddrMap::BBEntry &BBEntry = BBRange.BBEntries[I]; 1470 uint64_t BBAddress = BBEntry.Offset + BBRange.BaseAddress; 1471 if (BBAddress >= EndAddress) 1472 continue; 1473 1474 std::string LabelString = ("BB" + Twine(BBEntry.ID)).str(); 1475 Labels[BBAddress].push_back( 1476 {LabelString, FunctionMap->constructPGOLabelString( 1477 NumBBEntriesBeforeRange + I, PrettyPGOAnalysisMap)}); 1478 } 1479 } 1480 1481 static void 1482 collectLocalBranchTargets(ArrayRef<uint8_t> Bytes, MCInstrAnalysis *MIA, 1483 MCDisassembler *DisAsm, MCInstPrinter *IP, 1484 const MCSubtargetInfo *STI, uint64_t SectionAddr, 1485 uint64_t Start, uint64_t End, 1486 std::unordered_map<uint64_t, std::string> &Labels) { 1487 // Supported by certain targets. 1488 const bool isPPC = STI->getTargetTriple().isPPC(); 1489 const bool isX86 = STI->getTargetTriple().isX86(); 1490 const bool isBPF = STI->getTargetTriple().isBPF(); 1491 if (!isPPC && !isX86 && !isBPF) 1492 return; 1493 1494 if (MIA) 1495 MIA->resetState(); 1496 1497 Labels.clear(); 1498 unsigned LabelCount = 0; 1499 Start += SectionAddr; 1500 End += SectionAddr; 1501 const bool isXCOFF = STI->getTargetTriple().isOSBinFormatXCOFF(); 1502 for (uint64_t Index = Start; Index < End;) { 1503 // Disassemble a real instruction and record function-local branch labels. 1504 MCInst Inst; 1505 uint64_t Size; 1506 ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index - SectionAddr); 1507 bool Disassembled = 1508 DisAsm->getInstruction(Inst, Size, ThisBytes, Index, nulls()); 1509 if (Size == 0) 1510 Size = std::min<uint64_t>(ThisBytes.size(), 1511 DisAsm->suggestBytesToSkip(ThisBytes, Index)); 1512 1513 if (MIA) { 1514 if (Disassembled) { 1515 uint64_t Target; 1516 bool TargetKnown = MIA->evaluateBranch(Inst, Index, Size, Target); 1517 if (TargetKnown && (Target >= Start && Target < End) && 1518 !Labels.count(Target)) { 1519 // On PowerPC and AIX, a function call is encoded as a branch to 0. 1520 // On other PowerPC platforms (ELF), a function call is encoded as 1521 // a branch to self. Do not add a label for these cases. 1522 if (!(isPPC && 1523 ((Target == 0 && isXCOFF) || (Target == Index && !isXCOFF)))) 1524 Labels[Target] = ("L" + Twine(LabelCount++)).str(); 1525 } 1526 MIA->updateState(Inst, Index); 1527 } else 1528 MIA->resetState(); 1529 } 1530 Index += Size; 1531 } 1532 } 1533 1534 // Create an MCSymbolizer for the target and add it to the MCDisassembler. 1535 // This is currently only used on AMDGPU, and assumes the format of the 1536 // void * argument passed to AMDGPU's createMCSymbolizer. 1537 static void addSymbolizer( 1538 MCContext &Ctx, const Target *Target, StringRef TripleName, 1539 MCDisassembler *DisAsm, uint64_t SectionAddr, ArrayRef<uint8_t> Bytes, 1540 SectionSymbolsTy &Symbols, 1541 std::vector<std::unique_ptr<std::string>> &SynthesizedLabelNames) { 1542 1543 std::unique_ptr<MCRelocationInfo> RelInfo( 1544 Target->createMCRelocationInfo(TripleName, Ctx)); 1545 if (!RelInfo) 1546 return; 1547 std::unique_ptr<MCSymbolizer> Symbolizer(Target->createMCSymbolizer( 1548 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo))); 1549 MCSymbolizer *SymbolizerPtr = &*Symbolizer; 1550 DisAsm->setSymbolizer(std::move(Symbolizer)); 1551 1552 if (!SymbolizeOperands) 1553 return; 1554 1555 // Synthesize labels referenced by branch instructions by 1556 // disassembling, discarding the output, and collecting the referenced 1557 // addresses from the symbolizer. 1558 for (size_t Index = 0; Index != Bytes.size();) { 1559 MCInst Inst; 1560 uint64_t Size; 1561 ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index); 1562 const uint64_t ThisAddr = SectionAddr + Index; 1563 DisAsm->getInstruction(Inst, Size, ThisBytes, ThisAddr, nulls()); 1564 if (Size == 0) 1565 Size = std::min<uint64_t>(ThisBytes.size(), 1566 DisAsm->suggestBytesToSkip(ThisBytes, Index)); 1567 Index += Size; 1568 } 1569 ArrayRef<uint64_t> LabelAddrsRef = SymbolizerPtr->getReferencedAddresses(); 1570 // Copy and sort to remove duplicates. 1571 std::vector<uint64_t> LabelAddrs; 1572 LabelAddrs.insert(LabelAddrs.end(), LabelAddrsRef.begin(), 1573 LabelAddrsRef.end()); 1574 llvm::sort(LabelAddrs); 1575 LabelAddrs.resize(llvm::unique(LabelAddrs) - LabelAddrs.begin()); 1576 // Add the labels. 1577 for (unsigned LabelNum = 0; LabelNum != LabelAddrs.size(); ++LabelNum) { 1578 auto Name = std::make_unique<std::string>(); 1579 *Name = (Twine("L") + Twine(LabelNum)).str(); 1580 SynthesizedLabelNames.push_back(std::move(Name)); 1581 Symbols.push_back(SymbolInfoTy( 1582 LabelAddrs[LabelNum], *SynthesizedLabelNames.back(), ELF::STT_NOTYPE)); 1583 } 1584 llvm::stable_sort(Symbols); 1585 // Recreate the symbolizer with the new symbols list. 1586 RelInfo.reset(Target->createMCRelocationInfo(TripleName, Ctx)); 1587 Symbolizer.reset(Target->createMCSymbolizer( 1588 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo))); 1589 DisAsm->setSymbolizer(std::move(Symbolizer)); 1590 } 1591 1592 static StringRef getSegmentName(const MachOObjectFile *MachO, 1593 const SectionRef &Section) { 1594 if (MachO) { 1595 DataRefImpl DR = Section.getRawDataRefImpl(); 1596 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 1597 return SegmentName; 1598 } 1599 return ""; 1600 } 1601 1602 static void emitPostInstructionInfo(formatted_raw_ostream &FOS, 1603 const MCAsmInfo &MAI, 1604 const MCSubtargetInfo &STI, 1605 StringRef Comments, 1606 LiveVariablePrinter &LVP) { 1607 do { 1608 if (!Comments.empty()) { 1609 // Emit a line of comments. 1610 StringRef Comment; 1611 std::tie(Comment, Comments) = Comments.split('\n'); 1612 // MAI.getCommentColumn() assumes that instructions are printed at the 1613 // position of 8, while getInstStartColumn() returns the actual position. 1614 unsigned CommentColumn = 1615 MAI.getCommentColumn() - 8 + getInstStartColumn(STI); 1616 FOS.PadToColumn(CommentColumn); 1617 FOS << MAI.getCommentString() << ' ' << Comment; 1618 } 1619 LVP.printAfterInst(FOS); 1620 FOS << '\n'; 1621 } while (!Comments.empty()); 1622 FOS.flush(); 1623 } 1624 1625 static void createFakeELFSections(ObjectFile &Obj) { 1626 assert(Obj.isELF()); 1627 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(&Obj)) 1628 Elf32LEObj->createFakeSections(); 1629 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(&Obj)) 1630 Elf64LEObj->createFakeSections(); 1631 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(&Obj)) 1632 Elf32BEObj->createFakeSections(); 1633 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(&Obj)) 1634 Elf64BEObj->createFakeSections(); 1635 else 1636 llvm_unreachable("Unsupported binary format"); 1637 } 1638 1639 // Tries to fetch a more complete version of the given object file using its 1640 // Build ID. Returns std::nullopt if nothing was found. 1641 static std::optional<OwningBinary<Binary>> 1642 fetchBinaryByBuildID(const ObjectFile &Obj) { 1643 object::BuildIDRef BuildID = getBuildID(&Obj); 1644 if (BuildID.empty()) 1645 return std::nullopt; 1646 std::optional<std::string> Path = BIDFetcher->fetch(BuildID); 1647 if (!Path) 1648 return std::nullopt; 1649 Expected<OwningBinary<Binary>> DebugBinary = createBinary(*Path); 1650 if (!DebugBinary) { 1651 reportWarning(toString(DebugBinary.takeError()), *Path); 1652 return std::nullopt; 1653 } 1654 return std::move(*DebugBinary); 1655 } 1656 1657 static void 1658 disassembleObject(ObjectFile &Obj, const ObjectFile &DbgObj, 1659 DisassemblerTarget &PrimaryTarget, 1660 std::optional<DisassemblerTarget> &SecondaryTarget, 1661 SourcePrinter &SP, bool InlineRelocs) { 1662 DisassemblerTarget *DT = &PrimaryTarget; 1663 bool PrimaryIsThumb = false; 1664 SmallVector<std::pair<uint64_t, uint64_t>, 0> CHPECodeMap; 1665 1666 if (SecondaryTarget) { 1667 if (isArmElf(Obj)) { 1668 PrimaryIsThumb = 1669 PrimaryTarget.SubtargetInfo->checkFeatures("+thumb-mode"); 1670 } else if (const auto *COFFObj = dyn_cast<COFFObjectFile>(&Obj)) { 1671 const chpe_metadata *CHPEMetadata = COFFObj->getCHPEMetadata(); 1672 if (CHPEMetadata && CHPEMetadata->CodeMapCount) { 1673 uintptr_t CodeMapInt; 1674 cantFail(COFFObj->getRvaPtr(CHPEMetadata->CodeMap, CodeMapInt)); 1675 auto CodeMap = reinterpret_cast<const chpe_range_entry *>(CodeMapInt); 1676 1677 for (uint32_t i = 0; i < CHPEMetadata->CodeMapCount; ++i) { 1678 if (CodeMap[i].getType() == chpe_range_type::Amd64 && 1679 CodeMap[i].Length) { 1680 // Store x86_64 CHPE code ranges. 1681 uint64_t Start = CodeMap[i].getStart() + COFFObj->getImageBase(); 1682 CHPECodeMap.emplace_back(Start, Start + CodeMap[i].Length); 1683 } 1684 } 1685 llvm::sort(CHPECodeMap); 1686 } 1687 } 1688 } 1689 1690 std::map<SectionRef, std::vector<RelocationRef>> RelocMap; 1691 if (InlineRelocs || Obj.isXCOFF()) 1692 RelocMap = getRelocsMap(Obj); 1693 bool Is64Bits = Obj.getBytesInAddress() > 4; 1694 1695 // Create a mapping from virtual address to symbol name. This is used to 1696 // pretty print the symbols while disassembling. 1697 std::map<SectionRef, SectionSymbolsTy> AllSymbols; 1698 std::map<SectionRef, SmallVector<MappingSymbolPair, 0>> AllMappingSymbols; 1699 SectionSymbolsTy AbsoluteSymbols; 1700 const StringRef FileName = Obj.getFileName(); 1701 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(&Obj); 1702 for (const SymbolRef &Symbol : Obj.symbols()) { 1703 Expected<StringRef> NameOrErr = Symbol.getName(); 1704 if (!NameOrErr) { 1705 reportWarning(toString(NameOrErr.takeError()), FileName); 1706 continue; 1707 } 1708 if (NameOrErr->empty() && !(Obj.isXCOFF() && SymbolDescription)) 1709 continue; 1710 1711 if (Obj.isELF() && 1712 (cantFail(Symbol.getFlags()) & SymbolRef::SF_FormatSpecific)) { 1713 // Symbol is intended not to be displayed by default (STT_FILE, 1714 // STT_SECTION, or a mapping symbol). Ignore STT_SECTION symbols. We will 1715 // synthesize a section symbol if no symbol is defined at offset 0. 1716 // 1717 // For a mapping symbol, store it within both AllSymbols and 1718 // AllMappingSymbols. If --show-all-symbols is unspecified, its label will 1719 // not be printed in disassembly listing. 1720 if (getElfSymbolType(Obj, Symbol) != ELF::STT_SECTION && 1721 hasMappingSymbols(Obj)) { 1722 section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName); 1723 if (SecI != Obj.section_end()) { 1724 uint64_t SectionAddr = SecI->getAddress(); 1725 uint64_t Address = cantFail(Symbol.getAddress()); 1726 StringRef Name = *NameOrErr; 1727 if (Name.consume_front("$") && Name.size() && 1728 strchr("adtx", Name[0])) { 1729 AllMappingSymbols[*SecI].emplace_back(Address - SectionAddr, 1730 Name[0]); 1731 AllSymbols[*SecI].push_back( 1732 createSymbolInfo(Obj, Symbol, /*MappingSymbol=*/true)); 1733 } 1734 } 1735 } 1736 continue; 1737 } 1738 1739 if (MachO) { 1740 // __mh_(execute|dylib|dylinker|bundle|preload|object)_header are special 1741 // symbols that support MachO header introspection. They do not bind to 1742 // code locations and are irrelevant for disassembly. 1743 if (NameOrErr->starts_with("__mh_") && NameOrErr->ends_with("_header")) 1744 continue; 1745 // Don't ask a Mach-O STAB symbol for its section unless you know that 1746 // STAB symbol's section field refers to a valid section index. Otherwise 1747 // the symbol may error trying to load a section that does not exist. 1748 DataRefImpl SymDRI = Symbol.getRawDataRefImpl(); 1749 uint8_t NType = (MachO->is64Bit() ? 1750 MachO->getSymbol64TableEntry(SymDRI).n_type: 1751 MachO->getSymbolTableEntry(SymDRI).n_type); 1752 if (NType & MachO::N_STAB) 1753 continue; 1754 } 1755 1756 section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName); 1757 if (SecI != Obj.section_end()) 1758 AllSymbols[*SecI].push_back(createSymbolInfo(Obj, Symbol)); 1759 else 1760 AbsoluteSymbols.push_back(createSymbolInfo(Obj, Symbol)); 1761 } 1762 1763 if (AllSymbols.empty() && Obj.isELF()) 1764 addDynamicElfSymbols(cast<ELFObjectFileBase>(Obj), AllSymbols); 1765 1766 if (Obj.isWasm()) 1767 addMissingWasmCodeSymbols(cast<WasmObjectFile>(Obj), AllSymbols); 1768 1769 if (Obj.isELF() && Obj.sections().empty()) 1770 createFakeELFSections(Obj); 1771 1772 BumpPtrAllocator A; 1773 StringSaver Saver(A); 1774 addPltEntries(Obj, AllSymbols, Saver); 1775 1776 // Create a mapping from virtual address to section. An empty section can 1777 // cause more than one section at the same address. Sort such sections to be 1778 // before same-addressed non-empty sections so that symbol lookups prefer the 1779 // non-empty section. 1780 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses; 1781 for (SectionRef Sec : Obj.sections()) 1782 SectionAddresses.emplace_back(Sec.getAddress(), Sec); 1783 llvm::stable_sort(SectionAddresses, [](const auto &LHS, const auto &RHS) { 1784 if (LHS.first != RHS.first) 1785 return LHS.first < RHS.first; 1786 return LHS.second.getSize() < RHS.second.getSize(); 1787 }); 1788 1789 // Linked executables (.exe and .dll files) typically don't include a real 1790 // symbol table but they might contain an export table. 1791 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(&Obj)) { 1792 for (const auto &ExportEntry : COFFObj->export_directories()) { 1793 StringRef Name; 1794 if (Error E = ExportEntry.getSymbolName(Name)) 1795 reportError(std::move(E), Obj.getFileName()); 1796 if (Name.empty()) 1797 continue; 1798 1799 uint32_t RVA; 1800 if (Error E = ExportEntry.getExportRVA(RVA)) 1801 reportError(std::move(E), Obj.getFileName()); 1802 1803 uint64_t VA = COFFObj->getImageBase() + RVA; 1804 auto Sec = partition_point( 1805 SectionAddresses, [VA](const std::pair<uint64_t, SectionRef> &O) { 1806 return O.first <= VA; 1807 }); 1808 if (Sec != SectionAddresses.begin()) { 1809 --Sec; 1810 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE); 1811 } else 1812 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE); 1813 } 1814 } 1815 1816 // Sort all the symbols, this allows us to use a simple binary search to find 1817 // Multiple symbols can have the same address. Use a stable sort to stabilize 1818 // the output. 1819 StringSet<> FoundDisasmSymbolSet; 1820 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols) 1821 llvm::stable_sort(SecSyms.second); 1822 llvm::stable_sort(AbsoluteSymbols); 1823 1824 std::unique_ptr<DWARFContext> DICtx; 1825 LiveVariablePrinter LVP(*DT->Context->getRegisterInfo(), *DT->SubtargetInfo); 1826 1827 if (DbgVariables != DVDisabled) { 1828 DICtx = DWARFContext::create(DbgObj); 1829 for (const std::unique_ptr<DWARFUnit> &CU : DICtx->compile_units()) 1830 LVP.addCompileUnit(CU->getUnitDIE(false)); 1831 } 1832 1833 LLVM_DEBUG(LVP.dump()); 1834 1835 BBAddrMapInfo FullAddrMap; 1836 auto ReadBBAddrMap = [&](std::optional<unsigned> SectionIndex = 1837 std::nullopt) { 1838 FullAddrMap.clear(); 1839 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(&Obj)) { 1840 std::vector<PGOAnalysisMap> PGOAnalyses; 1841 auto BBAddrMapsOrErr = Elf->readBBAddrMap(SectionIndex, &PGOAnalyses); 1842 if (!BBAddrMapsOrErr) { 1843 reportWarning(toString(BBAddrMapsOrErr.takeError()), Obj.getFileName()); 1844 return; 1845 } 1846 for (auto &&[FunctionBBAddrMap, FunctionPGOAnalysis] : 1847 zip_equal(*std::move(BBAddrMapsOrErr), std::move(PGOAnalyses))) { 1848 FullAddrMap.AddFunctionEntry(std::move(FunctionBBAddrMap), 1849 std::move(FunctionPGOAnalysis)); 1850 } 1851 } 1852 }; 1853 1854 // For non-relocatable objects, Read all LLVM_BB_ADDR_MAP sections into a 1855 // single mapping, since they don't have any conflicts. 1856 if (SymbolizeOperands && !Obj.isRelocatableObject()) 1857 ReadBBAddrMap(); 1858 1859 std::optional<llvm::BTFParser> BTF; 1860 if (InlineRelocs && BTFParser::hasBTFSections(Obj)) { 1861 BTF.emplace(); 1862 BTFParser::ParseOptions Opts = {}; 1863 Opts.LoadTypes = true; 1864 Opts.LoadRelocs = true; 1865 if (Error E = BTF->parse(Obj, Opts)) 1866 WithColor::defaultErrorHandler(std::move(E)); 1867 } 1868 1869 for (const SectionRef &Section : ToolSectionFilter(Obj)) { 1870 if (FilterSections.empty() && !DisassembleAll && 1871 (!Section.isText() || Section.isVirtual())) 1872 continue; 1873 1874 uint64_t SectionAddr = Section.getAddress(); 1875 uint64_t SectSize = Section.getSize(); 1876 if (!SectSize) 1877 continue; 1878 1879 // For relocatable object files, read the LLVM_BB_ADDR_MAP section 1880 // corresponding to this section, if present. 1881 if (SymbolizeOperands && Obj.isRelocatableObject()) 1882 ReadBBAddrMap(Section.getIndex()); 1883 1884 // Get the list of all the symbols in this section. 1885 SectionSymbolsTy &Symbols = AllSymbols[Section]; 1886 auto &MappingSymbols = AllMappingSymbols[Section]; 1887 llvm::sort(MappingSymbols); 1888 1889 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef( 1890 unwrapOrError(Section.getContents(), Obj.getFileName())); 1891 1892 std::vector<std::unique_ptr<std::string>> SynthesizedLabelNames; 1893 if (Obj.isELF() && Obj.getArch() == Triple::amdgcn) { 1894 // AMDGPU disassembler uses symbolizer for printing labels 1895 addSymbolizer(*DT->Context, DT->TheTarget, TripleName, DT->DisAsm.get(), 1896 SectionAddr, Bytes, Symbols, SynthesizedLabelNames); 1897 } 1898 1899 StringRef SegmentName = getSegmentName(MachO, Section); 1900 StringRef SectionName = unwrapOrError(Section.getName(), Obj.getFileName()); 1901 // If the section has no symbol at the start, just insert a dummy one. 1902 // Without --show-all-symbols, also insert one if all symbols at the start 1903 // are mapping symbols. 1904 bool CreateDummy = Symbols.empty(); 1905 if (!CreateDummy) { 1906 CreateDummy = true; 1907 for (auto &Sym : Symbols) { 1908 if (Sym.Addr != SectionAddr) 1909 break; 1910 if (!Sym.IsMappingSymbol || ShowAllSymbols) 1911 CreateDummy = false; 1912 } 1913 } 1914 if (CreateDummy) { 1915 SymbolInfoTy Sym = createDummySymbolInfo( 1916 Obj, SectionAddr, SectionName, 1917 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT); 1918 if (Obj.isXCOFF()) 1919 Symbols.insert(Symbols.begin(), Sym); 1920 else 1921 Symbols.insert(llvm::lower_bound(Symbols, Sym), Sym); 1922 } 1923 1924 SmallString<40> Comments; 1925 raw_svector_ostream CommentStream(Comments); 1926 1927 uint64_t VMAAdjustment = 0; 1928 if (shouldAdjustVA(Section)) 1929 VMAAdjustment = AdjustVMA; 1930 1931 // In executable and shared objects, r_offset holds a virtual address. 1932 // Subtract SectionAddr from the r_offset field of a relocation to get 1933 // the section offset. 1934 uint64_t RelAdjustment = Obj.isRelocatableObject() ? 0 : SectionAddr; 1935 uint64_t Size; 1936 uint64_t Index; 1937 bool PrintedSection = false; 1938 std::vector<RelocationRef> Rels = RelocMap[Section]; 1939 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin(); 1940 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end(); 1941 1942 // Loop over each chunk of code between two points where at least 1943 // one symbol is defined. 1944 for (size_t SI = 0, SE = Symbols.size(); SI != SE;) { 1945 // Advance SI past all the symbols starting at the same address, 1946 // and make an ArrayRef of them. 1947 unsigned FirstSI = SI; 1948 uint64_t Start = Symbols[SI].Addr; 1949 ArrayRef<SymbolInfoTy> SymbolsHere; 1950 while (SI != SE && Symbols[SI].Addr == Start) 1951 ++SI; 1952 SymbolsHere = ArrayRef<SymbolInfoTy>(&Symbols[FirstSI], SI - FirstSI); 1953 1954 // Get the demangled names of all those symbols. We end up with a vector 1955 // of StringRef that holds the names we're going to use, and a vector of 1956 // std::string that stores the new strings returned by demangle(), if 1957 // any. If we don't call demangle() then that vector can stay empty. 1958 std::vector<StringRef> SymNamesHere; 1959 std::vector<std::string> DemangledSymNamesHere; 1960 if (Demangle) { 1961 // Fetch the demangled names and store them locally. 1962 for (const SymbolInfoTy &Symbol : SymbolsHere) 1963 DemangledSymNamesHere.push_back(demangle(Symbol.Name)); 1964 // Now we've finished modifying that vector, it's safe to make 1965 // a vector of StringRefs pointing into it. 1966 SymNamesHere.insert(SymNamesHere.begin(), DemangledSymNamesHere.begin(), 1967 DemangledSymNamesHere.end()); 1968 } else { 1969 for (const SymbolInfoTy &Symbol : SymbolsHere) 1970 SymNamesHere.push_back(Symbol.Name); 1971 } 1972 1973 // Distinguish ELF data from code symbols, which will be used later on to 1974 // decide whether to 'disassemble' this chunk as a data declaration via 1975 // dumpELFData(), or whether to treat it as code. 1976 // 1977 // If data _and_ code symbols are defined at the same address, the code 1978 // takes priority, on the grounds that disassembling code is our main 1979 // purpose here, and it would be a worse failure to _not_ interpret 1980 // something that _was_ meaningful as code than vice versa. 1981 // 1982 // Any ELF symbol type that is not clearly data will be regarded as code. 1983 // In particular, one of the uses of STT_NOTYPE is for branch targets 1984 // inside functions, for which STT_FUNC would be inaccurate. 1985 // 1986 // So here, we spot whether there's any non-data symbol present at all, 1987 // and only set the DisassembleAsELFData flag if there isn't. Also, we use 1988 // this distinction to inform the decision of which symbol to print at 1989 // the head of the section, so that if we're printing code, we print a 1990 // code-related symbol name to go with it. 1991 bool DisassembleAsELFData = false; 1992 size_t DisplaySymIndex = SymbolsHere.size() - 1; 1993 if (Obj.isELF() && !DisassembleAll && Section.isText()) { 1994 DisassembleAsELFData = true; // unless we find a code symbol below 1995 1996 for (size_t i = 0; i < SymbolsHere.size(); ++i) { 1997 uint8_t SymTy = SymbolsHere[i].Type; 1998 if (SymTy != ELF::STT_OBJECT && SymTy != ELF::STT_COMMON) { 1999 DisassembleAsELFData = false; 2000 DisplaySymIndex = i; 2001 } 2002 } 2003 } 2004 2005 // Decide which symbol(s) from this collection we're going to print. 2006 std::vector<bool> SymsToPrint(SymbolsHere.size(), false); 2007 // If the user has given the --disassemble-symbols option, then we must 2008 // display every symbol in that set, and no others. 2009 if (!DisasmSymbolSet.empty()) { 2010 bool FoundAny = false; 2011 for (size_t i = 0; i < SymbolsHere.size(); ++i) { 2012 if (DisasmSymbolSet.count(SymNamesHere[i])) { 2013 SymsToPrint[i] = true; 2014 FoundAny = true; 2015 } 2016 } 2017 2018 // And if none of the symbols here is one that the user asked for, skip 2019 // disassembling this entire chunk of code. 2020 if (!FoundAny) 2021 continue; 2022 } else if (!SymbolsHere[DisplaySymIndex].IsMappingSymbol) { 2023 // Otherwise, print whichever symbol at this location is last in the 2024 // Symbols array, because that array is pre-sorted in a way intended to 2025 // correlate with priority of which symbol to display. 2026 SymsToPrint[DisplaySymIndex] = true; 2027 } 2028 2029 // Now that we know we're disassembling this section, override the choice 2030 // of which symbols to display by printing _all_ of them at this address 2031 // if the user asked for all symbols. 2032 // 2033 // That way, '--show-all-symbols --disassemble-symbol=foo' will print 2034 // only the chunk of code headed by 'foo', but also show any other 2035 // symbols defined at that address, such as aliases for 'foo', or the ARM 2036 // mapping symbol preceding its code. 2037 if (ShowAllSymbols) { 2038 for (size_t i = 0; i < SymbolsHere.size(); ++i) 2039 SymsToPrint[i] = true; 2040 } 2041 2042 if (Start < SectionAddr || StopAddress <= Start) 2043 continue; 2044 2045 for (size_t i = 0; i < SymbolsHere.size(); ++i) 2046 FoundDisasmSymbolSet.insert(SymNamesHere[i]); 2047 2048 // The end is the section end, the beginning of the next symbol, or 2049 // --stop-address. 2050 uint64_t End = std::min<uint64_t>(SectionAddr + SectSize, StopAddress); 2051 if (SI < SE) 2052 End = std::min(End, Symbols[SI].Addr); 2053 if (Start >= End || End <= StartAddress) 2054 continue; 2055 Start -= SectionAddr; 2056 End -= SectionAddr; 2057 2058 if (!PrintedSection) { 2059 PrintedSection = true; 2060 outs() << "\nDisassembly of section "; 2061 if (!SegmentName.empty()) 2062 outs() << SegmentName << ","; 2063 outs() << SectionName << ":\n"; 2064 } 2065 2066 bool PrintedLabel = false; 2067 for (size_t i = 0; i < SymbolsHere.size(); ++i) { 2068 if (!SymsToPrint[i]) 2069 continue; 2070 2071 const SymbolInfoTy &Symbol = SymbolsHere[i]; 2072 const StringRef SymbolName = SymNamesHere[i]; 2073 2074 if (!PrintedLabel) { 2075 outs() << '\n'; 2076 PrintedLabel = true; 2077 } 2078 if (LeadingAddr) 2079 outs() << format(Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " ", 2080 SectionAddr + Start + VMAAdjustment); 2081 if (Obj.isXCOFF() && SymbolDescription) { 2082 outs() << getXCOFFSymbolDescription(Symbol, SymbolName) << ":\n"; 2083 } else 2084 outs() << '<' << SymbolName << ">:\n"; 2085 } 2086 2087 // Don't print raw contents of a virtual section. A virtual section 2088 // doesn't have any contents in the file. 2089 if (Section.isVirtual()) { 2090 outs() << "...\n"; 2091 continue; 2092 } 2093 2094 // See if any of the symbols defined at this location triggers target- 2095 // specific disassembly behavior, e.g. of special descriptors or function 2096 // prelude information. 2097 // 2098 // We stop this loop at the first symbol that triggers some kind of 2099 // interesting behavior (if any), on the assumption that if two symbols 2100 // defined at the same address trigger two conflicting symbol handlers, 2101 // the object file is probably confused anyway, and it would make even 2102 // less sense to present the output of _both_ handlers, because that 2103 // would describe the same data twice. 2104 for (size_t SHI = 0; SHI < SymbolsHere.size(); ++SHI) { 2105 SymbolInfoTy Symbol = SymbolsHere[SHI]; 2106 2107 Expected<bool> RespondedOrErr = DT->DisAsm->onSymbolStart( 2108 Symbol, Size, Bytes.slice(Start, End - Start), SectionAddr + Start); 2109 2110 if (RespondedOrErr && !*RespondedOrErr) { 2111 // This symbol didn't trigger any interesting handling. Try the other 2112 // symbols defined at this address. 2113 continue; 2114 } 2115 2116 // If onSymbolStart returned an Error, that means it identified some 2117 // kind of special data at this address, but wasn't able to disassemble 2118 // it meaningfully. So we fall back to printing the error out and 2119 // disassembling the failed region as bytes, assuming that the target 2120 // detected the failure before printing anything. 2121 if (!RespondedOrErr) { 2122 std::string ErrMsgStr = toString(RespondedOrErr.takeError()); 2123 StringRef ErrMsg = ErrMsgStr; 2124 do { 2125 StringRef Line; 2126 std::tie(Line, ErrMsg) = ErrMsg.split('\n'); 2127 outs() << DT->Context->getAsmInfo()->getCommentString() 2128 << " error decoding " << SymNamesHere[SHI] << ": " << Line 2129 << '\n'; 2130 } while (!ErrMsg.empty()); 2131 2132 if (Size) { 2133 outs() << DT->Context->getAsmInfo()->getCommentString() 2134 << " decoding failed region as bytes\n"; 2135 for (uint64_t I = 0; I < Size; ++I) 2136 outs() << "\t.byte\t " << format_hex(Bytes[I], 1, /*Upper=*/true) 2137 << '\n'; 2138 } 2139 } 2140 2141 // Regardless of whether onSymbolStart returned an Error or true, 'Size' 2142 // will have been set to the amount of data covered by whatever prologue 2143 // the target identified. So we advance our own position to beyond that. 2144 // Sometimes that will be the entire distance to the next symbol, and 2145 // sometimes it will be just a prologue and we should start 2146 // disassembling instructions from where it left off. 2147 Start += Size; 2148 break; 2149 } 2150 2151 Index = Start; 2152 if (SectionAddr < StartAddress) 2153 Index = std::max<uint64_t>(Index, StartAddress - SectionAddr); 2154 2155 if (DisassembleAsELFData) { 2156 dumpELFData(SectionAddr, Index, End, Bytes); 2157 Index = End; 2158 continue; 2159 } 2160 2161 // Skip relocations from symbols that are not dumped. 2162 for (; RelCur != RelEnd; ++RelCur) { 2163 uint64_t Offset = RelCur->getOffset() - RelAdjustment; 2164 if (Index <= Offset) 2165 break; 2166 } 2167 2168 bool DumpARMELFData = false; 2169 bool DumpTracebackTableForXCOFFFunction = 2170 Obj.isXCOFF() && Section.isText() && TracebackTable && 2171 Symbols[SI - 1].XCOFFSymInfo.StorageMappingClass && 2172 (*Symbols[SI - 1].XCOFFSymInfo.StorageMappingClass == XCOFF::XMC_PR); 2173 2174 formatted_raw_ostream FOS(outs()); 2175 2176 std::unordered_map<uint64_t, std::string> AllLabels; 2177 std::unordered_map<uint64_t, std::vector<BBAddrMapLabel>> BBAddrMapLabels; 2178 if (SymbolizeOperands) { 2179 collectLocalBranchTargets(Bytes, DT->InstrAnalysis.get(), 2180 DT->DisAsm.get(), DT->InstPrinter.get(), 2181 PrimaryTarget.SubtargetInfo.get(), 2182 SectionAddr, Index, End, AllLabels); 2183 collectBBAddrMapLabels(FullAddrMap, SectionAddr, Index, End, 2184 BBAddrMapLabels); 2185 } 2186 2187 if (DT->InstrAnalysis) 2188 DT->InstrAnalysis->resetState(); 2189 2190 while (Index < End) { 2191 uint64_t RelOffset; 2192 2193 // ARM and AArch64 ELF binaries can interleave data and text in the 2194 // same section. We rely on the markers introduced to understand what 2195 // we need to dump. If the data marker is within a function, it is 2196 // denoted as a word/short etc. 2197 if (!MappingSymbols.empty()) { 2198 char Kind = getMappingSymbolKind(MappingSymbols, Index); 2199 DumpARMELFData = Kind == 'd'; 2200 if (SecondaryTarget) { 2201 if (Kind == 'a') { 2202 DT = PrimaryIsThumb ? &*SecondaryTarget : &PrimaryTarget; 2203 } else if (Kind == 't') { 2204 DT = PrimaryIsThumb ? &PrimaryTarget : &*SecondaryTarget; 2205 } 2206 } 2207 } else if (!CHPECodeMap.empty()) { 2208 uint64_t Address = SectionAddr + Index; 2209 auto It = partition_point( 2210 CHPECodeMap, 2211 [Address](const std::pair<uint64_t, uint64_t> &Entry) { 2212 return Entry.first <= Address; 2213 }); 2214 if (It != CHPECodeMap.begin() && Address < (It - 1)->second) { 2215 DT = &*SecondaryTarget; 2216 } else { 2217 DT = &PrimaryTarget; 2218 // X64 disassembler range may have left Index unaligned, so 2219 // make sure that it's aligned when we switch back to ARM64 2220 // code. 2221 Index = llvm::alignTo(Index, 4); 2222 if (Index >= End) 2223 break; 2224 } 2225 } 2226 2227 auto findRel = [&]() { 2228 while (RelCur != RelEnd) { 2229 RelOffset = RelCur->getOffset() - RelAdjustment; 2230 // If this relocation is hidden, skip it. 2231 if (getHidden(*RelCur) || SectionAddr + RelOffset < StartAddress) { 2232 ++RelCur; 2233 continue; 2234 } 2235 2236 // Stop when RelCur's offset is past the disassembled 2237 // instruction/data. 2238 if (RelOffset >= Index + Size) 2239 return false; 2240 if (RelOffset >= Index) 2241 return true; 2242 ++RelCur; 2243 } 2244 return false; 2245 }; 2246 2247 // When -z or --disassemble-zeroes are given we always dissasemble 2248 // them. Otherwise we might want to skip zero bytes we see. 2249 if (!DisassembleZeroes) { 2250 uint64_t MaxOffset = End - Index; 2251 // For --reloc: print zero blocks patched by relocations, so that 2252 // relocations can be shown in the dump. 2253 if (InlineRelocs && RelCur != RelEnd) 2254 MaxOffset = std::min(RelCur->getOffset() - RelAdjustment - Index, 2255 MaxOffset); 2256 2257 if (size_t N = 2258 countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) { 2259 FOS << "\t\t..." << '\n'; 2260 Index += N; 2261 continue; 2262 } 2263 } 2264 2265 if (DumpARMELFData) { 2266 Size = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes, 2267 MappingSymbols, *DT->SubtargetInfo, FOS); 2268 } else { 2269 2270 if (DumpTracebackTableForXCOFFFunction && 2271 doesXCOFFTracebackTableBegin(Bytes.slice(Index, 4))) { 2272 dumpTracebackTable(Bytes.slice(Index), 2273 SectionAddr + Index + VMAAdjustment, FOS, 2274 SectionAddr + End + VMAAdjustment, 2275 *DT->SubtargetInfo, cast<XCOFFObjectFile>(&Obj)); 2276 Index = End; 2277 continue; 2278 } 2279 2280 // Print local label if there's any. 2281 auto Iter1 = BBAddrMapLabels.find(SectionAddr + Index); 2282 if (Iter1 != BBAddrMapLabels.end()) { 2283 for (const auto &BBLabel : Iter1->second) 2284 FOS << "<" << BBLabel.BlockLabel << ">" << BBLabel.PGOAnalysis 2285 << ":\n"; 2286 } else { 2287 auto Iter2 = AllLabels.find(SectionAddr + Index); 2288 if (Iter2 != AllLabels.end()) 2289 FOS << "<" << Iter2->second << ">:\n"; 2290 } 2291 2292 // Disassemble a real instruction or a data when disassemble all is 2293 // provided 2294 MCInst Inst; 2295 ArrayRef<uint8_t> ThisBytes = Bytes.slice(Index); 2296 uint64_t ThisAddr = SectionAddr + Index; 2297 bool Disassembled = DT->DisAsm->getInstruction( 2298 Inst, Size, ThisBytes, ThisAddr, CommentStream); 2299 if (Size == 0) 2300 Size = std::min<uint64_t>( 2301 ThisBytes.size(), 2302 DT->DisAsm->suggestBytesToSkip(ThisBytes, ThisAddr)); 2303 2304 LVP.update({Index, Section.getIndex()}, 2305 {Index + Size, Section.getIndex()}, Index + Size != End); 2306 2307 DT->InstPrinter->setCommentStream(CommentStream); 2308 2309 DT->Printer->printInst( 2310 *DT->InstPrinter, Disassembled ? &Inst : nullptr, 2311 Bytes.slice(Index, Size), 2312 {SectionAddr + Index + VMAAdjustment, Section.getIndex()}, FOS, 2313 "", *DT->SubtargetInfo, &SP, Obj.getFileName(), &Rels, LVP); 2314 2315 DT->InstPrinter->setCommentStream(llvm::nulls()); 2316 2317 // If disassembly succeeds, we try to resolve the target address 2318 // (jump target or memory operand address) and print it to the 2319 // right of the instruction. 2320 // 2321 // Otherwise, we don't print anything else so that we avoid 2322 // analyzing invalid or incomplete instruction information. 2323 if (Disassembled && DT->InstrAnalysis) { 2324 llvm::raw_ostream *TargetOS = &FOS; 2325 uint64_t Target; 2326 bool PrintTarget = DT->InstrAnalysis->evaluateBranch( 2327 Inst, SectionAddr + Index, Size, Target); 2328 2329 if (!PrintTarget) { 2330 if (std::optional<uint64_t> MaybeTarget = 2331 DT->InstrAnalysis->evaluateMemoryOperandAddress( 2332 Inst, DT->SubtargetInfo.get(), SectionAddr + Index, 2333 Size)) { 2334 Target = *MaybeTarget; 2335 PrintTarget = true; 2336 // Do not print real address when symbolizing. 2337 if (!SymbolizeOperands) { 2338 // Memory operand addresses are printed as comments. 2339 TargetOS = &CommentStream; 2340 *TargetOS << "0x" << Twine::utohexstr(Target); 2341 } 2342 } 2343 } 2344 2345 if (PrintTarget) { 2346 // In a relocatable object, the target's section must reside in 2347 // the same section as the call instruction or it is accessed 2348 // through a relocation. 2349 // 2350 // In a non-relocatable object, the target may be in any section. 2351 // In that case, locate the section(s) containing the target 2352 // address and find the symbol in one of those, if possible. 2353 // 2354 // N.B. Except for XCOFF, we don't walk the relocations in the 2355 // relocatable case yet. 2356 std::vector<const SectionSymbolsTy *> TargetSectionSymbols; 2357 if (!Obj.isRelocatableObject()) { 2358 auto It = llvm::partition_point( 2359 SectionAddresses, 2360 [=](const std::pair<uint64_t, SectionRef> &O) { 2361 return O.first <= Target; 2362 }); 2363 uint64_t TargetSecAddr = 0; 2364 while (It != SectionAddresses.begin()) { 2365 --It; 2366 if (TargetSecAddr == 0) 2367 TargetSecAddr = It->first; 2368 if (It->first != TargetSecAddr) 2369 break; 2370 TargetSectionSymbols.push_back(&AllSymbols[It->second]); 2371 } 2372 } else { 2373 TargetSectionSymbols.push_back(&Symbols); 2374 } 2375 TargetSectionSymbols.push_back(&AbsoluteSymbols); 2376 2377 // Find the last symbol in the first candidate section whose 2378 // offset is less than or equal to the target. If there are no 2379 // such symbols, try in the next section and so on, before finally 2380 // using the nearest preceding absolute symbol (if any), if there 2381 // are no other valid symbols. 2382 const SymbolInfoTy *TargetSym = nullptr; 2383 for (const SectionSymbolsTy *TargetSymbols : 2384 TargetSectionSymbols) { 2385 auto It = llvm::partition_point( 2386 *TargetSymbols, 2387 [=](const SymbolInfoTy &O) { return O.Addr <= Target; }); 2388 while (It != TargetSymbols->begin()) { 2389 --It; 2390 // Skip mapping symbols to avoid possible ambiguity as they 2391 // do not allow uniquely identifying the target address. 2392 if (!It->IsMappingSymbol) { 2393 TargetSym = &*It; 2394 break; 2395 } 2396 } 2397 if (TargetSym) 2398 break; 2399 } 2400 2401 // Branch targets are printed just after the instructions. 2402 // Print the labels corresponding to the target if there's any. 2403 bool BBAddrMapLabelAvailable = BBAddrMapLabels.count(Target); 2404 bool LabelAvailable = AllLabels.count(Target); 2405 2406 if (TargetSym != nullptr) { 2407 uint64_t TargetAddress = TargetSym->Addr; 2408 uint64_t Disp = Target - TargetAddress; 2409 std::string TargetName = Demangle ? demangle(TargetSym->Name) 2410 : TargetSym->Name.str(); 2411 bool RelFixedUp = false; 2412 SmallString<32> Val; 2413 2414 *TargetOS << " <"; 2415 // On XCOFF, we use relocations, even without -r, so we 2416 // can print the correct name for an extern function call. 2417 if (Obj.isXCOFF() && findRel()) { 2418 // Check for possible branch relocations and 2419 // branches to fixup code. 2420 bool BranchRelocationType = true; 2421 XCOFF::RelocationType RelocType; 2422 if (Obj.is64Bit()) { 2423 const XCOFFRelocation64 *Reloc = 2424 reinterpret_cast<XCOFFRelocation64 *>( 2425 RelCur->getRawDataRefImpl().p); 2426 RelFixedUp = Reloc->isFixupIndicated(); 2427 RelocType = Reloc->Type; 2428 } else { 2429 const XCOFFRelocation32 *Reloc = 2430 reinterpret_cast<XCOFFRelocation32 *>( 2431 RelCur->getRawDataRefImpl().p); 2432 RelFixedUp = Reloc->isFixupIndicated(); 2433 RelocType = Reloc->Type; 2434 } 2435 BranchRelocationType = 2436 RelocType == XCOFF::R_BA || RelocType == XCOFF::R_BR || 2437 RelocType == XCOFF::R_RBA || RelocType == XCOFF::R_RBR; 2438 2439 // If we have a valid relocation, try to print its 2440 // corresponding symbol name. Multiple relocations on the 2441 // same instruction are not handled. 2442 // Branches to fixup code will have the RelFixedUp flag set in 2443 // the RLD. For these instructions, we print the correct 2444 // branch target, but print the referenced symbol as a 2445 // comment. 2446 if (Error E = getRelocationValueString(*RelCur, false, Val)) { 2447 // If -r was used, this error will be printed later. 2448 // Otherwise, we ignore the error and print what 2449 // would have been printed without using relocations. 2450 consumeError(std::move(E)); 2451 *TargetOS << TargetName; 2452 RelFixedUp = false; // Suppress comment for RLD sym name 2453 } else if (BranchRelocationType && !RelFixedUp) 2454 *TargetOS << Val; 2455 else 2456 *TargetOS << TargetName; 2457 if (Disp) 2458 *TargetOS << "+0x" << Twine::utohexstr(Disp); 2459 } else if (!Disp) { 2460 *TargetOS << TargetName; 2461 } else if (BBAddrMapLabelAvailable) { 2462 *TargetOS << BBAddrMapLabels[Target].front().BlockLabel; 2463 } else if (LabelAvailable) { 2464 *TargetOS << AllLabels[Target]; 2465 } else { 2466 // Always Print the binary symbol plus an offset if there's no 2467 // local label corresponding to the target address. 2468 *TargetOS << TargetName << "+0x" << Twine::utohexstr(Disp); 2469 } 2470 *TargetOS << ">"; 2471 if (RelFixedUp && !InlineRelocs) { 2472 // We have fixup code for a relocation. We print the 2473 // referenced symbol as a comment. 2474 *TargetOS << "\t# " << Val; 2475 } 2476 2477 } else if (BBAddrMapLabelAvailable) { 2478 *TargetOS << " <" << BBAddrMapLabels[Target].front().BlockLabel 2479 << ">"; 2480 } else if (LabelAvailable) { 2481 *TargetOS << " <" << AllLabels[Target] << ">"; 2482 } 2483 // By convention, each record in the comment stream should be 2484 // terminated. 2485 if (TargetOS == &CommentStream) 2486 *TargetOS << "\n"; 2487 } 2488 2489 DT->InstrAnalysis->updateState(Inst, SectionAddr + Index); 2490 } else if (!Disassembled && DT->InstrAnalysis) { 2491 DT->InstrAnalysis->resetState(); 2492 } 2493 } 2494 2495 assert(DT->Context->getAsmInfo()); 2496 emitPostInstructionInfo(FOS, *DT->Context->getAsmInfo(), 2497 *DT->SubtargetInfo, CommentStream.str(), LVP); 2498 Comments.clear(); 2499 2500 if (BTF) 2501 printBTFRelocation(FOS, *BTF, {Index, Section.getIndex()}, LVP); 2502 2503 // Hexagon handles relocs in pretty printer 2504 if (InlineRelocs && Obj.getArch() != Triple::hexagon) { 2505 while (findRel()) { 2506 // When --adjust-vma is used, update the address printed. 2507 if (RelCur->getSymbol() != Obj.symbol_end()) { 2508 Expected<section_iterator> SymSI = 2509 RelCur->getSymbol()->getSection(); 2510 if (SymSI && *SymSI != Obj.section_end() && 2511 shouldAdjustVA(**SymSI)) 2512 RelOffset += AdjustVMA; 2513 } 2514 2515 printRelocation(FOS, Obj.getFileName(), *RelCur, 2516 SectionAddr + RelOffset, Is64Bits); 2517 LVP.printAfterOtherLine(FOS, true); 2518 ++RelCur; 2519 } 2520 } 2521 2522 Index += Size; 2523 } 2524 } 2525 } 2526 StringSet<> MissingDisasmSymbolSet = 2527 set_difference(DisasmSymbolSet, FoundDisasmSymbolSet); 2528 for (StringRef Sym : MissingDisasmSymbolSet.keys()) 2529 reportWarning("failed to disassemble missing symbol " + Sym, FileName); 2530 } 2531 2532 static void disassembleObject(ObjectFile *Obj, bool InlineRelocs) { 2533 // If information useful for showing the disassembly is missing, try to find a 2534 // more complete binary and disassemble that instead. 2535 OwningBinary<Binary> FetchedBinary; 2536 if (Obj->symbols().empty()) { 2537 if (std::optional<OwningBinary<Binary>> FetchedBinaryOpt = 2538 fetchBinaryByBuildID(*Obj)) { 2539 if (auto *O = dyn_cast<ObjectFile>(FetchedBinaryOpt->getBinary())) { 2540 if (!O->symbols().empty() || 2541 (!O->sections().empty() && Obj->sections().empty())) { 2542 FetchedBinary = std::move(*FetchedBinaryOpt); 2543 Obj = O; 2544 } 2545 } 2546 } 2547 } 2548 2549 const Target *TheTarget = getTarget(Obj); 2550 2551 // Package up features to be passed to target/subtarget 2552 Expected<SubtargetFeatures> FeaturesValue = Obj->getFeatures(); 2553 if (!FeaturesValue) 2554 reportError(FeaturesValue.takeError(), Obj->getFileName()); 2555 SubtargetFeatures Features = *FeaturesValue; 2556 if (!MAttrs.empty()) { 2557 for (unsigned I = 0; I != MAttrs.size(); ++I) 2558 Features.AddFeature(MAttrs[I]); 2559 } else if (MCPU.empty() && Obj->makeTriple().isAArch64()) { 2560 Features.AddFeature("+all"); 2561 } 2562 2563 if (MCPU.empty()) 2564 MCPU = Obj->tryGetCPUName().value_or("").str(); 2565 2566 if (isArmElf(*Obj)) { 2567 // When disassembling big-endian Arm ELF, the instruction endianness is 2568 // determined in a complex way. In relocatable objects, AAELF32 mandates 2569 // that instruction endianness matches the ELF file endianness; in 2570 // executable images, that's true unless the file header has the EF_ARM_BE8 2571 // flag, in which case instructions are little-endian regardless of data 2572 // endianness. 2573 // 2574 // We must set the big-endian-instructions SubtargetFeature to make the 2575 // disassembler read the instructions the right way round, and also tell 2576 // our own prettyprinter to retrieve the encodings the same way to print in 2577 // hex. 2578 const auto *Elf32BE = dyn_cast<ELF32BEObjectFile>(Obj); 2579 2580 if (Elf32BE && (Elf32BE->isRelocatableObject() || 2581 !(Elf32BE->getPlatformFlags() & ELF::EF_ARM_BE8))) { 2582 Features.AddFeature("+big-endian-instructions"); 2583 ARMPrettyPrinterInst.setInstructionEndianness(llvm::endianness::big); 2584 } else { 2585 ARMPrettyPrinterInst.setInstructionEndianness(llvm::endianness::little); 2586 } 2587 } 2588 2589 DisassemblerTarget PrimaryTarget(TheTarget, *Obj, TripleName, MCPU, Features); 2590 2591 // If we have an ARM object file, we need a second disassembler, because 2592 // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode. 2593 // We use mapping symbols to switch between the two assemblers, where 2594 // appropriate. 2595 std::optional<DisassemblerTarget> SecondaryTarget; 2596 2597 if (isArmElf(*Obj)) { 2598 if (!PrimaryTarget.SubtargetInfo->checkFeatures("+mclass")) { 2599 if (PrimaryTarget.SubtargetInfo->checkFeatures("+thumb-mode")) 2600 Features.AddFeature("-thumb-mode"); 2601 else 2602 Features.AddFeature("+thumb-mode"); 2603 SecondaryTarget.emplace(PrimaryTarget, Features); 2604 } 2605 } else if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) { 2606 const chpe_metadata *CHPEMetadata = COFFObj->getCHPEMetadata(); 2607 if (CHPEMetadata && CHPEMetadata->CodeMapCount) { 2608 // Set up x86_64 disassembler for ARM64EC binaries. 2609 Triple X64Triple(TripleName); 2610 X64Triple.setArch(Triple::ArchType::x86_64); 2611 2612 std::string Error; 2613 const Target *X64Target = 2614 TargetRegistry::lookupTarget("", X64Triple, Error); 2615 if (X64Target) { 2616 SubtargetFeatures X64Features; 2617 SecondaryTarget.emplace(X64Target, *Obj, X64Triple.getTriple(), "", 2618 X64Features); 2619 } else { 2620 reportWarning(Error, Obj->getFileName()); 2621 } 2622 } 2623 } 2624 2625 const ObjectFile *DbgObj = Obj; 2626 if (!FetchedBinary.getBinary() && !Obj->hasDebugInfo()) { 2627 if (std::optional<OwningBinary<Binary>> DebugBinaryOpt = 2628 fetchBinaryByBuildID(*Obj)) { 2629 if (auto *FetchedObj = 2630 dyn_cast<const ObjectFile>(DebugBinaryOpt->getBinary())) { 2631 if (FetchedObj->hasDebugInfo()) { 2632 FetchedBinary = std::move(*DebugBinaryOpt); 2633 DbgObj = FetchedObj; 2634 } 2635 } 2636 } 2637 } 2638 2639 std::unique_ptr<object::Binary> DSYMBinary; 2640 std::unique_ptr<MemoryBuffer> DSYMBuf; 2641 if (!DbgObj->hasDebugInfo()) { 2642 if (const MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*Obj)) { 2643 DbgObj = objdump::getMachODSymObject(MachOOF, Obj->getFileName(), 2644 DSYMBinary, DSYMBuf); 2645 if (!DbgObj) 2646 return; 2647 } 2648 } 2649 2650 SourcePrinter SP(DbgObj, TheTarget->getName()); 2651 2652 for (StringRef Opt : DisassemblerOptions) 2653 if (!PrimaryTarget.InstPrinter->applyTargetSpecificCLOption(Opt)) 2654 reportError(Obj->getFileName(), 2655 "Unrecognized disassembler option: " + Opt); 2656 2657 disassembleObject(*Obj, *DbgObj, PrimaryTarget, SecondaryTarget, SP, 2658 InlineRelocs); 2659 } 2660 2661 void Dumper::printRelocations() { 2662 StringRef Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 2663 2664 // Build a mapping from relocation target to a vector of relocation 2665 // sections. Usually, there is an only one relocation section for 2666 // each relocated section. 2667 MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec; 2668 uint64_t Ndx; 2669 for (const SectionRef &Section : ToolSectionFilter(O, &Ndx)) { 2670 if (O.isELF() && (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC)) 2671 continue; 2672 if (Section.relocation_begin() == Section.relocation_end()) 2673 continue; 2674 Expected<section_iterator> SecOrErr = Section.getRelocatedSection(); 2675 if (!SecOrErr) 2676 reportError(O.getFileName(), 2677 "section (" + Twine(Ndx) + 2678 "): unable to get a relocation target: " + 2679 toString(SecOrErr.takeError())); 2680 SecToRelSec[**SecOrErr].push_back(Section); 2681 } 2682 2683 for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) { 2684 StringRef SecName = unwrapOrError(P.first.getName(), O.getFileName()); 2685 outs() << "\nRELOCATION RECORDS FOR [" << SecName << "]:\n"; 2686 uint32_t OffsetPadding = (O.getBytesInAddress() > 4 ? 16 : 8); 2687 uint32_t TypePadding = 24; 2688 outs() << left_justify("OFFSET", OffsetPadding) << " " 2689 << left_justify("TYPE", TypePadding) << " " 2690 << "VALUE\n"; 2691 2692 for (SectionRef Section : P.second) { 2693 // CREL sections require decoding, each section may have its own specific 2694 // decode problems. 2695 if (O.isELF() && ELFSectionRef(Section).getType() == ELF::SHT_CREL) { 2696 StringRef Err = 2697 cast<const ELFObjectFileBase>(O).getCrelDecodeProblem(Section); 2698 if (!Err.empty()) { 2699 reportUniqueWarning(Err); 2700 continue; 2701 } 2702 } 2703 for (const RelocationRef &Reloc : Section.relocations()) { 2704 uint64_t Address = Reloc.getOffset(); 2705 SmallString<32> RelocName; 2706 SmallString<32> ValueStr; 2707 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc)) 2708 continue; 2709 Reloc.getTypeName(RelocName); 2710 if (Error E = 2711 getRelocationValueString(Reloc, SymbolDescription, ValueStr)) 2712 reportUniqueWarning(std::move(E)); 2713 2714 outs() << format(Fmt.data(), Address) << " " 2715 << left_justify(RelocName, TypePadding) << " " << ValueStr 2716 << "\n"; 2717 } 2718 } 2719 } 2720 } 2721 2722 // Returns true if we need to show LMA column when dumping section headers. We 2723 // show it only when the platform is ELF and either we have at least one section 2724 // whose VMA and LMA are different and/or when --show-lma flag is used. 2725 static bool shouldDisplayLMA(const ObjectFile &Obj) { 2726 if (!Obj.isELF()) 2727 return false; 2728 for (const SectionRef &S : ToolSectionFilter(Obj)) 2729 if (S.getAddress() != getELFSectionLMA(S)) 2730 return true; 2731 return ShowLMA; 2732 } 2733 2734 static size_t getMaxSectionNameWidth(const ObjectFile &Obj) { 2735 // Default column width for names is 13 even if no names are that long. 2736 size_t MaxWidth = 13; 2737 for (const SectionRef &Section : ToolSectionFilter(Obj)) { 2738 StringRef Name = unwrapOrError(Section.getName(), Obj.getFileName()); 2739 MaxWidth = std::max(MaxWidth, Name.size()); 2740 } 2741 return MaxWidth; 2742 } 2743 2744 void objdump::printSectionHeaders(ObjectFile &Obj) { 2745 if (Obj.isELF() && Obj.sections().empty()) 2746 createFakeELFSections(Obj); 2747 2748 size_t NameWidth = getMaxSectionNameWidth(Obj); 2749 size_t AddressWidth = 2 * Obj.getBytesInAddress(); 2750 bool HasLMAColumn = shouldDisplayLMA(Obj); 2751 outs() << "\nSections:\n"; 2752 if (HasLMAColumn) 2753 outs() << "Idx " << left_justify("Name", NameWidth) << " Size " 2754 << left_justify("VMA", AddressWidth) << " " 2755 << left_justify("LMA", AddressWidth) << " Type\n"; 2756 else 2757 outs() << "Idx " << left_justify("Name", NameWidth) << " Size " 2758 << left_justify("VMA", AddressWidth) << " Type\n"; 2759 2760 uint64_t Idx; 2761 for (const SectionRef &Section : ToolSectionFilter(Obj, &Idx)) { 2762 StringRef Name = unwrapOrError(Section.getName(), Obj.getFileName()); 2763 uint64_t VMA = Section.getAddress(); 2764 if (shouldAdjustVA(Section)) 2765 VMA += AdjustVMA; 2766 2767 uint64_t Size = Section.getSize(); 2768 2769 std::string Type = Section.isText() ? "TEXT" : ""; 2770 if (Section.isData()) 2771 Type += Type.empty() ? "DATA" : ", DATA"; 2772 if (Section.isBSS()) 2773 Type += Type.empty() ? "BSS" : ", BSS"; 2774 if (Section.isDebugSection()) 2775 Type += Type.empty() ? "DEBUG" : ", DEBUG"; 2776 2777 if (HasLMAColumn) 2778 outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth, 2779 Name.str().c_str(), Size) 2780 << format_hex_no_prefix(VMA, AddressWidth) << " " 2781 << format_hex_no_prefix(getELFSectionLMA(Section), AddressWidth) 2782 << " " << Type << "\n"; 2783 else 2784 outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth, 2785 Name.str().c_str(), Size) 2786 << format_hex_no_prefix(VMA, AddressWidth) << " " << Type << "\n"; 2787 } 2788 } 2789 2790 void objdump::printSectionContents(const ObjectFile *Obj) { 2791 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj); 2792 2793 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 2794 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName()); 2795 uint64_t BaseAddr = Section.getAddress(); 2796 uint64_t Size = Section.getSize(); 2797 if (!Size) 2798 continue; 2799 2800 outs() << "Contents of section "; 2801 StringRef SegmentName = getSegmentName(MachO, Section); 2802 if (!SegmentName.empty()) 2803 outs() << SegmentName << ","; 2804 outs() << Name << ":\n"; 2805 if (Section.isBSS()) { 2806 outs() << format("<skipping contents of bss section at [%04" PRIx64 2807 ", %04" PRIx64 ")>\n", 2808 BaseAddr, BaseAddr + Size); 2809 continue; 2810 } 2811 2812 StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName()); 2813 2814 // Dump out the content as hex and printable ascii characters. 2815 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) { 2816 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr); 2817 // Dump line of hex. 2818 for (std::size_t I = 0; I < 16; ++I) { 2819 if (I != 0 && I % 4 == 0) 2820 outs() << ' '; 2821 if (Addr + I < End) 2822 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true) 2823 << hexdigit(Contents[Addr + I] & 0xF, true); 2824 else 2825 outs() << " "; 2826 } 2827 // Print ascii. 2828 outs() << " "; 2829 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) { 2830 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF)) 2831 outs() << Contents[Addr + I]; 2832 else 2833 outs() << "."; 2834 } 2835 outs() << "\n"; 2836 } 2837 } 2838 } 2839 2840 void Dumper::printSymbolTable(StringRef ArchiveName, StringRef ArchitectureName, 2841 bool DumpDynamic) { 2842 if (O.isCOFF() && !DumpDynamic) { 2843 outs() << "\nSYMBOL TABLE:\n"; 2844 printCOFFSymbolTable(cast<const COFFObjectFile>(O)); 2845 return; 2846 } 2847 2848 const StringRef FileName = O.getFileName(); 2849 2850 if (!DumpDynamic) { 2851 outs() << "\nSYMBOL TABLE:\n"; 2852 for (auto I = O.symbol_begin(); I != O.symbol_end(); ++I) 2853 printSymbol(*I, {}, FileName, ArchiveName, ArchitectureName, DumpDynamic); 2854 return; 2855 } 2856 2857 outs() << "\nDYNAMIC SYMBOL TABLE:\n"; 2858 if (!O.isELF()) { 2859 reportWarning( 2860 "this operation is not currently supported for this file format", 2861 FileName); 2862 return; 2863 } 2864 2865 const ELFObjectFileBase *ELF = cast<const ELFObjectFileBase>(&O); 2866 auto Symbols = ELF->getDynamicSymbolIterators(); 2867 Expected<std::vector<VersionEntry>> SymbolVersionsOrErr = 2868 ELF->readDynsymVersions(); 2869 if (!SymbolVersionsOrErr) { 2870 reportWarning(toString(SymbolVersionsOrErr.takeError()), FileName); 2871 SymbolVersionsOrErr = std::vector<VersionEntry>(); 2872 (void)!SymbolVersionsOrErr; 2873 } 2874 for (auto &Sym : Symbols) 2875 printSymbol(Sym, *SymbolVersionsOrErr, FileName, ArchiveName, 2876 ArchitectureName, DumpDynamic); 2877 } 2878 2879 void Dumper::printSymbol(const SymbolRef &Symbol, 2880 ArrayRef<VersionEntry> SymbolVersions, 2881 StringRef FileName, StringRef ArchiveName, 2882 StringRef ArchitectureName, bool DumpDynamic) { 2883 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(&O); 2884 Expected<uint64_t> AddrOrErr = Symbol.getAddress(); 2885 if (!AddrOrErr) { 2886 reportUniqueWarning(AddrOrErr.takeError()); 2887 return; 2888 } 2889 2890 // Don't ask a Mach-O STAB symbol for its section unless you know that 2891 // STAB symbol's section field refers to a valid section index. Otherwise 2892 // the symbol may error trying to load a section that does not exist. 2893 bool IsSTAB = false; 2894 if (MachO) { 2895 DataRefImpl SymDRI = Symbol.getRawDataRefImpl(); 2896 uint8_t NType = 2897 (MachO->is64Bit() ? MachO->getSymbol64TableEntry(SymDRI).n_type 2898 : MachO->getSymbolTableEntry(SymDRI).n_type); 2899 if (NType & MachO::N_STAB) 2900 IsSTAB = true; 2901 } 2902 section_iterator Section = IsSTAB 2903 ? O.section_end() 2904 : unwrapOrError(Symbol.getSection(), FileName, 2905 ArchiveName, ArchitectureName); 2906 2907 uint64_t Address = *AddrOrErr; 2908 if (Section != O.section_end() && shouldAdjustVA(*Section)) 2909 Address += AdjustVMA; 2910 if ((Address < StartAddress) || (Address > StopAddress)) 2911 return; 2912 SymbolRef::Type Type = 2913 unwrapOrError(Symbol.getType(), FileName, ArchiveName, ArchitectureName); 2914 uint32_t Flags = 2915 unwrapOrError(Symbol.getFlags(), FileName, ArchiveName, ArchitectureName); 2916 2917 StringRef Name; 2918 if (Type == SymbolRef::ST_Debug && Section != O.section_end()) { 2919 if (Expected<StringRef> NameOrErr = Section->getName()) 2920 Name = *NameOrErr; 2921 else 2922 consumeError(NameOrErr.takeError()); 2923 2924 } else { 2925 Name = unwrapOrError(Symbol.getName(), FileName, ArchiveName, 2926 ArchitectureName); 2927 } 2928 2929 bool Global = Flags & SymbolRef::SF_Global; 2930 bool Weak = Flags & SymbolRef::SF_Weak; 2931 bool Absolute = Flags & SymbolRef::SF_Absolute; 2932 bool Common = Flags & SymbolRef::SF_Common; 2933 bool Hidden = Flags & SymbolRef::SF_Hidden; 2934 2935 char GlobLoc = ' '; 2936 if ((Section != O.section_end() || Absolute) && !Weak) 2937 GlobLoc = Global ? 'g' : 'l'; 2938 char IFunc = ' '; 2939 if (O.isELF()) { 2940 if (ELFSymbolRef(Symbol).getELFType() == ELF::STT_GNU_IFUNC) 2941 IFunc = 'i'; 2942 if (ELFSymbolRef(Symbol).getBinding() == ELF::STB_GNU_UNIQUE) 2943 GlobLoc = 'u'; 2944 } 2945 2946 char Debug = ' '; 2947 if (DumpDynamic) 2948 Debug = 'D'; 2949 else if (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 2950 Debug = 'd'; 2951 2952 char FileFunc = ' '; 2953 if (Type == SymbolRef::ST_File) 2954 FileFunc = 'f'; 2955 else if (Type == SymbolRef::ST_Function) 2956 FileFunc = 'F'; 2957 else if (Type == SymbolRef::ST_Data) 2958 FileFunc = 'O'; 2959 2960 const char *Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 2961 2962 outs() << format(Fmt, Address) << " " 2963 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 2964 << (Weak ? 'w' : ' ') // Weak? 2965 << ' ' // Constructor. Not supported yet. 2966 << ' ' // Warning. Not supported yet. 2967 << IFunc // Indirect reference to another symbol. 2968 << Debug // Debugging (d) or dynamic (D) symbol. 2969 << FileFunc // Name of function (F), file (f) or object (O). 2970 << ' '; 2971 if (Absolute) { 2972 outs() << "*ABS*"; 2973 } else if (Common) { 2974 outs() << "*COM*"; 2975 } else if (Section == O.section_end()) { 2976 if (O.isXCOFF()) { 2977 XCOFFSymbolRef XCOFFSym = cast<const XCOFFObjectFile>(O).toSymbolRef( 2978 Symbol.getRawDataRefImpl()); 2979 if (XCOFF::N_DEBUG == XCOFFSym.getSectionNumber()) 2980 outs() << "*DEBUG*"; 2981 else 2982 outs() << "*UND*"; 2983 } else 2984 outs() << "*UND*"; 2985 } else { 2986 StringRef SegmentName = getSegmentName(MachO, *Section); 2987 if (!SegmentName.empty()) 2988 outs() << SegmentName << ","; 2989 StringRef SectionName = unwrapOrError(Section->getName(), FileName); 2990 outs() << SectionName; 2991 if (O.isXCOFF()) { 2992 std::optional<SymbolRef> SymRef = 2993 getXCOFFSymbolContainingSymbolRef(cast<XCOFFObjectFile>(O), Symbol); 2994 if (SymRef) { 2995 2996 Expected<StringRef> NameOrErr = SymRef->getName(); 2997 2998 if (NameOrErr) { 2999 outs() << " (csect:"; 3000 std::string SymName = 3001 Demangle ? demangle(*NameOrErr) : NameOrErr->str(); 3002 3003 if (SymbolDescription) 3004 SymName = getXCOFFSymbolDescription(createSymbolInfo(O, *SymRef), 3005 SymName); 3006 3007 outs() << ' ' << SymName; 3008 outs() << ") "; 3009 } else 3010 reportWarning(toString(NameOrErr.takeError()), FileName); 3011 } 3012 } 3013 } 3014 3015 if (Common) 3016 outs() << '\t' << format(Fmt, static_cast<uint64_t>(Symbol.getAlignment())); 3017 else if (O.isXCOFF()) 3018 outs() << '\t' 3019 << format(Fmt, cast<XCOFFObjectFile>(O).getSymbolSize( 3020 Symbol.getRawDataRefImpl())); 3021 else if (O.isELF()) 3022 outs() << '\t' << format(Fmt, ELFSymbolRef(Symbol).getSize()); 3023 else if (O.isWasm()) 3024 outs() << '\t' 3025 << format(Fmt, static_cast<uint64_t>( 3026 cast<WasmObjectFile>(O).getSymbolSize(Symbol))); 3027 3028 if (O.isELF()) { 3029 if (!SymbolVersions.empty()) { 3030 const VersionEntry &Ver = 3031 SymbolVersions[Symbol.getRawDataRefImpl().d.b - 1]; 3032 std::string Str; 3033 if (!Ver.Name.empty()) 3034 Str = Ver.IsVerDef ? ' ' + Ver.Name : '(' + Ver.Name + ')'; 3035 outs() << ' ' << left_justify(Str, 12); 3036 } 3037 3038 uint8_t Other = ELFSymbolRef(Symbol).getOther(); 3039 switch (Other) { 3040 case ELF::STV_DEFAULT: 3041 break; 3042 case ELF::STV_INTERNAL: 3043 outs() << " .internal"; 3044 break; 3045 case ELF::STV_HIDDEN: 3046 outs() << " .hidden"; 3047 break; 3048 case ELF::STV_PROTECTED: 3049 outs() << " .protected"; 3050 break; 3051 default: 3052 outs() << format(" 0x%02x", Other); 3053 break; 3054 } 3055 } else if (Hidden) { 3056 outs() << " .hidden"; 3057 } 3058 3059 std::string SymName = Demangle ? demangle(Name) : Name.str(); 3060 if (O.isXCOFF() && SymbolDescription) 3061 SymName = getXCOFFSymbolDescription(createSymbolInfo(O, Symbol), SymName); 3062 3063 outs() << ' ' << SymName << '\n'; 3064 } 3065 3066 static void printUnwindInfo(const ObjectFile *O) { 3067 outs() << "Unwind info:\n\n"; 3068 3069 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O)) 3070 printCOFFUnwindInfo(Coff); 3071 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O)) 3072 printMachOUnwindInfo(MachO); 3073 else 3074 // TODO: Extract DWARF dump tool to objdump. 3075 WithColor::error(errs(), ToolName) 3076 << "This operation is only currently supported " 3077 "for COFF and MachO object files.\n"; 3078 } 3079 3080 /// Dump the raw contents of the __clangast section so the output can be piped 3081 /// into llvm-bcanalyzer. 3082 static void printRawClangAST(const ObjectFile *Obj) { 3083 if (outs().is_displayed()) { 3084 WithColor::error(errs(), ToolName) 3085 << "The -raw-clang-ast option will dump the raw binary contents of " 3086 "the clang ast section.\n" 3087 "Please redirect the output to a file or another program such as " 3088 "llvm-bcanalyzer.\n"; 3089 return; 3090 } 3091 3092 StringRef ClangASTSectionName("__clangast"); 3093 if (Obj->isCOFF()) { 3094 ClangASTSectionName = "clangast"; 3095 } 3096 3097 std::optional<object::SectionRef> ClangASTSection; 3098 for (auto Sec : ToolSectionFilter(*Obj)) { 3099 StringRef Name; 3100 if (Expected<StringRef> NameOrErr = Sec.getName()) 3101 Name = *NameOrErr; 3102 else 3103 consumeError(NameOrErr.takeError()); 3104 3105 if (Name == ClangASTSectionName) { 3106 ClangASTSection = Sec; 3107 break; 3108 } 3109 } 3110 if (!ClangASTSection) 3111 return; 3112 3113 StringRef ClangASTContents = 3114 unwrapOrError(ClangASTSection->getContents(), Obj->getFileName()); 3115 outs().write(ClangASTContents.data(), ClangASTContents.size()); 3116 } 3117 3118 static void printFaultMaps(const ObjectFile *Obj) { 3119 StringRef FaultMapSectionName; 3120 3121 if (Obj->isELF()) { 3122 FaultMapSectionName = ".llvm_faultmaps"; 3123 } else if (Obj->isMachO()) { 3124 FaultMapSectionName = "__llvm_faultmaps"; 3125 } else { 3126 WithColor::error(errs(), ToolName) 3127 << "This operation is only currently supported " 3128 "for ELF and Mach-O executable files.\n"; 3129 return; 3130 } 3131 3132 std::optional<object::SectionRef> FaultMapSection; 3133 3134 for (auto Sec : ToolSectionFilter(*Obj)) { 3135 StringRef Name; 3136 if (Expected<StringRef> NameOrErr = Sec.getName()) 3137 Name = *NameOrErr; 3138 else 3139 consumeError(NameOrErr.takeError()); 3140 3141 if (Name == FaultMapSectionName) { 3142 FaultMapSection = Sec; 3143 break; 3144 } 3145 } 3146 3147 outs() << "FaultMap table:\n"; 3148 3149 if (!FaultMapSection) { 3150 outs() << "<not found>\n"; 3151 return; 3152 } 3153 3154 StringRef FaultMapContents = 3155 unwrapOrError(FaultMapSection->getContents(), Obj->getFileName()); 3156 FaultMapParser FMP(FaultMapContents.bytes_begin(), 3157 FaultMapContents.bytes_end()); 3158 3159 outs() << FMP; 3160 } 3161 3162 void Dumper::printPrivateHeaders() { 3163 reportError(O.getFileName(), "Invalid/Unsupported object file format"); 3164 } 3165 3166 static void printFileHeaders(const ObjectFile *O) { 3167 if (!O->isELF() && !O->isCOFF() && !O->isXCOFF()) 3168 reportError(O->getFileName(), "Invalid/Unsupported object file format"); 3169 3170 Triple::ArchType AT = O->getArch(); 3171 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n"; 3172 uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName()); 3173 3174 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 3175 outs() << "start address: " 3176 << "0x" << format(Fmt.data(), Address) << "\n"; 3177 } 3178 3179 static void printArchiveChild(StringRef Filename, const Archive::Child &C) { 3180 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode(); 3181 if (!ModeOrErr) { 3182 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n"; 3183 consumeError(ModeOrErr.takeError()); 3184 return; 3185 } 3186 sys::fs::perms Mode = ModeOrErr.get(); 3187 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-"); 3188 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-"); 3189 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-"); 3190 outs() << ((Mode & sys::fs::group_read) ? "r" : "-"); 3191 outs() << ((Mode & sys::fs::group_write) ? "w" : "-"); 3192 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-"); 3193 outs() << ((Mode & sys::fs::others_read) ? "r" : "-"); 3194 outs() << ((Mode & sys::fs::others_write) ? "w" : "-"); 3195 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-"); 3196 3197 outs() << " "; 3198 3199 outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename), 3200 unwrapOrError(C.getGID(), Filename), 3201 unwrapOrError(C.getRawSize(), Filename)); 3202 3203 StringRef RawLastModified = C.getRawLastModified(); 3204 unsigned Seconds; 3205 if (RawLastModified.getAsInteger(10, Seconds)) 3206 outs() << "(date: \"" << RawLastModified 3207 << "\" contains non-decimal chars) "; 3208 else { 3209 // Since ctime(3) returns a 26 character string of the form: 3210 // "Sun Sep 16 01:03:52 1973\n\0" 3211 // just print 24 characters. 3212 time_t t = Seconds; 3213 outs() << format("%.24s ", ctime(&t)); 3214 } 3215 3216 StringRef Name = ""; 3217 Expected<StringRef> NameOrErr = C.getName(); 3218 if (!NameOrErr) { 3219 consumeError(NameOrErr.takeError()); 3220 Name = unwrapOrError(C.getRawName(), Filename); 3221 } else { 3222 Name = NameOrErr.get(); 3223 } 3224 outs() << Name << "\n"; 3225 } 3226 3227 // For ELF only now. 3228 static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) { 3229 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj)) { 3230 if (Elf->getEType() != ELF::ET_REL) 3231 return true; 3232 } 3233 return false; 3234 } 3235 3236 static void checkForInvalidStartStopAddress(ObjectFile *Obj, 3237 uint64_t Start, uint64_t Stop) { 3238 if (!shouldWarnForInvalidStartStopAddress(Obj)) 3239 return; 3240 3241 for (const SectionRef &Section : Obj->sections()) 3242 if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) { 3243 uint64_t BaseAddr = Section.getAddress(); 3244 uint64_t Size = Section.getSize(); 3245 if ((Start < BaseAddr + Size) && Stop > BaseAddr) 3246 return; 3247 } 3248 3249 if (!HasStartAddressFlag) 3250 reportWarning("no section has address less than 0x" + 3251 Twine::utohexstr(Stop) + " specified by --stop-address", 3252 Obj->getFileName()); 3253 else if (!HasStopAddressFlag) 3254 reportWarning("no section has address greater than or equal to 0x" + 3255 Twine::utohexstr(Start) + " specified by --start-address", 3256 Obj->getFileName()); 3257 else 3258 reportWarning("no section overlaps the range [0x" + 3259 Twine::utohexstr(Start) + ",0x" + Twine::utohexstr(Stop) + 3260 ") specified by --start-address/--stop-address", 3261 Obj->getFileName()); 3262 } 3263 3264 static void dumpObject(ObjectFile *O, const Archive *A = nullptr, 3265 const Archive::Child *C = nullptr) { 3266 Expected<std::unique_ptr<Dumper>> DumperOrErr = createDumper(*O); 3267 if (!DumperOrErr) { 3268 reportError(DumperOrErr.takeError(), O->getFileName(), 3269 A ? A->getFileName() : ""); 3270 return; 3271 } 3272 Dumper &D = **DumperOrErr; 3273 3274 // Avoid other output when using a raw option. 3275 if (!RawClangAST) { 3276 outs() << '\n'; 3277 if (A) 3278 outs() << A->getFileName() << "(" << O->getFileName() << ")"; 3279 else 3280 outs() << O->getFileName(); 3281 outs() << ":\tfile format " << O->getFileFormatName().lower() << "\n"; 3282 } 3283 3284 if (HasStartAddressFlag || HasStopAddressFlag) 3285 checkForInvalidStartStopAddress(O, StartAddress, StopAddress); 3286 3287 // TODO: Change print* free functions to Dumper member functions to utilitize 3288 // stateful functions like reportUniqueWarning. 3289 3290 // Note: the order here matches GNU objdump for compatability. 3291 StringRef ArchiveName = A ? A->getFileName() : ""; 3292 if (ArchiveHeaders && !MachOOpt && C) 3293 printArchiveChild(ArchiveName, *C); 3294 if (FileHeaders) 3295 printFileHeaders(O); 3296 if (PrivateHeaders || FirstPrivateHeader) 3297 D.printPrivateHeaders(); 3298 if (SectionHeaders) 3299 printSectionHeaders(*O); 3300 if (SymbolTable) 3301 D.printSymbolTable(ArchiveName); 3302 if (DynamicSymbolTable) 3303 D.printSymbolTable(ArchiveName, /*ArchitectureName=*/"", 3304 /*DumpDynamic=*/true); 3305 if (DwarfDumpType != DIDT_Null) { 3306 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O); 3307 // Dump the complete DWARF structure. 3308 DIDumpOptions DumpOpts; 3309 DumpOpts.DumpType = DwarfDumpType; 3310 DICtx->dump(outs(), DumpOpts); 3311 } 3312 if (Relocations && !Disassemble) 3313 D.printRelocations(); 3314 if (DynamicRelocations) 3315 D.printDynamicRelocations(); 3316 if (SectionContents) 3317 printSectionContents(O); 3318 if (Disassemble) 3319 disassembleObject(O, Relocations); 3320 if (UnwindInfo) 3321 printUnwindInfo(O); 3322 3323 // Mach-O specific options: 3324 if (ExportsTrie) 3325 printExportsTrie(O); 3326 if (Rebase) 3327 printRebaseTable(O); 3328 if (Bind) 3329 printBindTable(O); 3330 if (LazyBind) 3331 printLazyBindTable(O); 3332 if (WeakBind) 3333 printWeakBindTable(O); 3334 3335 // Other special sections: 3336 if (RawClangAST) 3337 printRawClangAST(O); 3338 if (FaultMapSection) 3339 printFaultMaps(O); 3340 if (Offloading) 3341 dumpOffloadBinary(*O); 3342 } 3343 3344 static void dumpObject(const COFFImportFile *I, const Archive *A, 3345 const Archive::Child *C = nullptr) { 3346 StringRef ArchiveName = A ? A->getFileName() : ""; 3347 3348 // Avoid other output when using a raw option. 3349 if (!RawClangAST) 3350 outs() << '\n' 3351 << ArchiveName << "(" << I->getFileName() << ")" 3352 << ":\tfile format COFF-import-file" 3353 << "\n\n"; 3354 3355 if (ArchiveHeaders && !MachOOpt && C) 3356 printArchiveChild(ArchiveName, *C); 3357 if (SymbolTable) 3358 printCOFFSymbolTable(*I); 3359 } 3360 3361 /// Dump each object file in \a a; 3362 static void dumpArchive(const Archive *A) { 3363 Error Err = Error::success(); 3364 unsigned I = -1; 3365 for (auto &C : A->children(Err)) { 3366 ++I; 3367 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 3368 if (!ChildOrErr) { 3369 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 3370 reportError(std::move(E), getFileNameForError(C, I), A->getFileName()); 3371 continue; 3372 } 3373 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 3374 dumpObject(O, A, &C); 3375 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get())) 3376 dumpObject(I, A, &C); 3377 else 3378 reportError(errorCodeToError(object_error::invalid_file_type), 3379 A->getFileName()); 3380 } 3381 if (Err) 3382 reportError(std::move(Err), A->getFileName()); 3383 } 3384 3385 /// Open file and figure out how to dump it. 3386 static void dumpInput(StringRef file) { 3387 // If we are using the Mach-O specific object file parser, then let it parse 3388 // the file and process the command line options. So the -arch flags can 3389 // be used to select specific slices, etc. 3390 if (MachOOpt) { 3391 parseInputMachO(file); 3392 return; 3393 } 3394 3395 // Attempt to open the binary. 3396 OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file); 3397 Binary &Binary = *OBinary.getBinary(); 3398 3399 if (Archive *A = dyn_cast<Archive>(&Binary)) 3400 dumpArchive(A); 3401 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary)) 3402 dumpObject(O); 3403 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary)) 3404 parseInputMachO(UB); 3405 else if (OffloadBinary *OB = dyn_cast<OffloadBinary>(&Binary)) 3406 dumpOffloadSections(*OB); 3407 else 3408 reportError(errorCodeToError(object_error::invalid_file_type), file); 3409 } 3410 3411 template <typename T> 3412 static void parseIntArg(const llvm::opt::InputArgList &InputArgs, int ID, 3413 T &Value) { 3414 if (const opt::Arg *A = InputArgs.getLastArg(ID)) { 3415 StringRef V(A->getValue()); 3416 if (!llvm::to_integer(V, Value, 0)) { 3417 reportCmdLineError(A->getSpelling() + 3418 ": expected a non-negative integer, but got '" + V + 3419 "'"); 3420 } 3421 } 3422 } 3423 3424 static object::BuildID parseBuildIDArg(const opt::Arg *A) { 3425 StringRef V(A->getValue()); 3426 object::BuildID BID = parseBuildID(V); 3427 if (BID.empty()) 3428 reportCmdLineError(A->getSpelling() + ": expected a build ID, but got '" + 3429 V + "'"); 3430 return BID; 3431 } 3432 3433 void objdump::invalidArgValue(const opt::Arg *A) { 3434 reportCmdLineError("'" + StringRef(A->getValue()) + 3435 "' is not a valid value for '" + A->getSpelling() + "'"); 3436 } 3437 3438 static std::vector<std::string> 3439 commaSeparatedValues(const llvm::opt::InputArgList &InputArgs, int ID) { 3440 std::vector<std::string> Values; 3441 for (StringRef Value : InputArgs.getAllArgValues(ID)) { 3442 llvm::SmallVector<StringRef, 2> SplitValues; 3443 llvm::SplitString(Value, SplitValues, ","); 3444 for (StringRef SplitValue : SplitValues) 3445 Values.push_back(SplitValue.str()); 3446 } 3447 return Values; 3448 } 3449 3450 static void parseOtoolOptions(const llvm::opt::InputArgList &InputArgs) { 3451 MachOOpt = true; 3452 FullLeadingAddr = true; 3453 PrintImmHex = true; 3454 3455 ArchName = InputArgs.getLastArgValue(OTOOL_arch).str(); 3456 LinkOptHints = InputArgs.hasArg(OTOOL_C); 3457 if (InputArgs.hasArg(OTOOL_d)) 3458 FilterSections.push_back("__DATA,__data"); 3459 DylibId = InputArgs.hasArg(OTOOL_D); 3460 UniversalHeaders = InputArgs.hasArg(OTOOL_f); 3461 DataInCode = InputArgs.hasArg(OTOOL_G); 3462 FirstPrivateHeader = InputArgs.hasArg(OTOOL_h); 3463 IndirectSymbols = InputArgs.hasArg(OTOOL_I); 3464 ShowRawInsn = InputArgs.hasArg(OTOOL_j); 3465 PrivateHeaders = InputArgs.hasArg(OTOOL_l); 3466 DylibsUsed = InputArgs.hasArg(OTOOL_L); 3467 MCPU = InputArgs.getLastArgValue(OTOOL_mcpu_EQ).str(); 3468 ObjcMetaData = InputArgs.hasArg(OTOOL_o); 3469 DisSymName = InputArgs.getLastArgValue(OTOOL_p).str(); 3470 InfoPlist = InputArgs.hasArg(OTOOL_P); 3471 Relocations = InputArgs.hasArg(OTOOL_r); 3472 if (const Arg *A = InputArgs.getLastArg(OTOOL_s)) { 3473 auto Filter = (A->getValue(0) + StringRef(",") + A->getValue(1)).str(); 3474 FilterSections.push_back(Filter); 3475 } 3476 if (InputArgs.hasArg(OTOOL_t)) 3477 FilterSections.push_back("__TEXT,__text"); 3478 Verbose = InputArgs.hasArg(OTOOL_v) || InputArgs.hasArg(OTOOL_V) || 3479 InputArgs.hasArg(OTOOL_o); 3480 SymbolicOperands = InputArgs.hasArg(OTOOL_V); 3481 if (InputArgs.hasArg(OTOOL_x)) 3482 FilterSections.push_back(",__text"); 3483 LeadingAddr = LeadingHeaders = !InputArgs.hasArg(OTOOL_X); 3484 3485 ChainedFixups = InputArgs.hasArg(OTOOL_chained_fixups); 3486 DyldInfo = InputArgs.hasArg(OTOOL_dyld_info); 3487 3488 InputFilenames = InputArgs.getAllArgValues(OTOOL_INPUT); 3489 if (InputFilenames.empty()) 3490 reportCmdLineError("no input file"); 3491 3492 for (const Arg *A : InputArgs) { 3493 const Option &O = A->getOption(); 3494 if (O.getGroup().isValid() && O.getGroup().getID() == OTOOL_grp_obsolete) { 3495 reportCmdLineWarning(O.getPrefixedName() + 3496 " is obsolete and not implemented"); 3497 } 3498 } 3499 } 3500 3501 static void parseObjdumpOptions(const llvm::opt::InputArgList &InputArgs) { 3502 parseIntArg(InputArgs, OBJDUMP_adjust_vma_EQ, AdjustVMA); 3503 AllHeaders = InputArgs.hasArg(OBJDUMP_all_headers); 3504 ArchName = InputArgs.getLastArgValue(OBJDUMP_arch_name_EQ).str(); 3505 ArchiveHeaders = InputArgs.hasArg(OBJDUMP_archive_headers); 3506 Demangle = InputArgs.hasArg(OBJDUMP_demangle); 3507 Disassemble = InputArgs.hasArg(OBJDUMP_disassemble); 3508 DisassembleAll = InputArgs.hasArg(OBJDUMP_disassemble_all); 3509 SymbolDescription = InputArgs.hasArg(OBJDUMP_symbol_description); 3510 TracebackTable = InputArgs.hasArg(OBJDUMP_traceback_table); 3511 DisassembleSymbols = 3512 commaSeparatedValues(InputArgs, OBJDUMP_disassemble_symbols_EQ); 3513 DisassembleZeroes = InputArgs.hasArg(OBJDUMP_disassemble_zeroes); 3514 if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_dwarf_EQ)) { 3515 DwarfDumpType = StringSwitch<DIDumpType>(A->getValue()) 3516 .Case("frames", DIDT_DebugFrame) 3517 .Default(DIDT_Null); 3518 if (DwarfDumpType == DIDT_Null) 3519 invalidArgValue(A); 3520 } 3521 DynamicRelocations = InputArgs.hasArg(OBJDUMP_dynamic_reloc); 3522 FaultMapSection = InputArgs.hasArg(OBJDUMP_fault_map_section); 3523 Offloading = InputArgs.hasArg(OBJDUMP_offloading); 3524 FileHeaders = InputArgs.hasArg(OBJDUMP_file_headers); 3525 SectionContents = InputArgs.hasArg(OBJDUMP_full_contents); 3526 PrintLines = InputArgs.hasArg(OBJDUMP_line_numbers); 3527 InputFilenames = InputArgs.getAllArgValues(OBJDUMP_INPUT); 3528 MachOOpt = InputArgs.hasArg(OBJDUMP_macho); 3529 MCPU = InputArgs.getLastArgValue(OBJDUMP_mcpu_EQ).str(); 3530 MAttrs = commaSeparatedValues(InputArgs, OBJDUMP_mattr_EQ); 3531 ShowRawInsn = !InputArgs.hasArg(OBJDUMP_no_show_raw_insn); 3532 LeadingAddr = !InputArgs.hasArg(OBJDUMP_no_leading_addr); 3533 RawClangAST = InputArgs.hasArg(OBJDUMP_raw_clang_ast); 3534 Relocations = InputArgs.hasArg(OBJDUMP_reloc); 3535 PrintImmHex = 3536 InputArgs.hasFlag(OBJDUMP_print_imm_hex, OBJDUMP_no_print_imm_hex, true); 3537 PrivateHeaders = InputArgs.hasArg(OBJDUMP_private_headers); 3538 FilterSections = InputArgs.getAllArgValues(OBJDUMP_section_EQ); 3539 SectionHeaders = InputArgs.hasArg(OBJDUMP_section_headers); 3540 ShowAllSymbols = InputArgs.hasArg(OBJDUMP_show_all_symbols); 3541 ShowLMA = InputArgs.hasArg(OBJDUMP_show_lma); 3542 PrintSource = InputArgs.hasArg(OBJDUMP_source); 3543 parseIntArg(InputArgs, OBJDUMP_start_address_EQ, StartAddress); 3544 HasStartAddressFlag = InputArgs.hasArg(OBJDUMP_start_address_EQ); 3545 parseIntArg(InputArgs, OBJDUMP_stop_address_EQ, StopAddress); 3546 HasStopAddressFlag = InputArgs.hasArg(OBJDUMP_stop_address_EQ); 3547 SymbolTable = InputArgs.hasArg(OBJDUMP_syms); 3548 SymbolizeOperands = InputArgs.hasArg(OBJDUMP_symbolize_operands); 3549 PrettyPGOAnalysisMap = InputArgs.hasArg(OBJDUMP_pretty_pgo_analysis_map); 3550 if (PrettyPGOAnalysisMap && !SymbolizeOperands) 3551 reportCmdLineWarning("--symbolize-operands must be enabled for " 3552 "--pretty-pgo-analysis-map to have an effect"); 3553 DynamicSymbolTable = InputArgs.hasArg(OBJDUMP_dynamic_syms); 3554 TripleName = InputArgs.getLastArgValue(OBJDUMP_triple_EQ).str(); 3555 UnwindInfo = InputArgs.hasArg(OBJDUMP_unwind_info); 3556 Wide = InputArgs.hasArg(OBJDUMP_wide); 3557 Prefix = InputArgs.getLastArgValue(OBJDUMP_prefix).str(); 3558 parseIntArg(InputArgs, OBJDUMP_prefix_strip, PrefixStrip); 3559 if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_debug_vars_EQ)) { 3560 DbgVariables = StringSwitch<DebugVarsFormat>(A->getValue()) 3561 .Case("ascii", DVASCII) 3562 .Case("unicode", DVUnicode) 3563 .Default(DVInvalid); 3564 if (DbgVariables == DVInvalid) 3565 invalidArgValue(A); 3566 } 3567 if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_disassembler_color_EQ)) { 3568 DisassemblyColor = StringSwitch<ColorOutput>(A->getValue()) 3569 .Case("on", ColorOutput::Enable) 3570 .Case("off", ColorOutput::Disable) 3571 .Case("terminal", ColorOutput::Auto) 3572 .Default(ColorOutput::Invalid); 3573 if (DisassemblyColor == ColorOutput::Invalid) 3574 invalidArgValue(A); 3575 } 3576 3577 parseIntArg(InputArgs, OBJDUMP_debug_vars_indent_EQ, DbgIndent); 3578 3579 parseMachOOptions(InputArgs); 3580 3581 // Parse -M (--disassembler-options) and deprecated 3582 // --x86-asm-syntax={att,intel}. 3583 // 3584 // Note, for x86, the asm dialect (AssemblerDialect) is initialized when the 3585 // MCAsmInfo is constructed. MCInstPrinter::applyTargetSpecificCLOption is 3586 // called too late. For now we have to use the internal cl::opt option. 3587 const char *AsmSyntax = nullptr; 3588 for (const auto *A : InputArgs.filtered(OBJDUMP_disassembler_options_EQ, 3589 OBJDUMP_x86_asm_syntax_att, 3590 OBJDUMP_x86_asm_syntax_intel)) { 3591 switch (A->getOption().getID()) { 3592 case OBJDUMP_x86_asm_syntax_att: 3593 AsmSyntax = "--x86-asm-syntax=att"; 3594 continue; 3595 case OBJDUMP_x86_asm_syntax_intel: 3596 AsmSyntax = "--x86-asm-syntax=intel"; 3597 continue; 3598 } 3599 3600 SmallVector<StringRef, 2> Values; 3601 llvm::SplitString(A->getValue(), Values, ","); 3602 for (StringRef V : Values) { 3603 if (V == "att") 3604 AsmSyntax = "--x86-asm-syntax=att"; 3605 else if (V == "intel") 3606 AsmSyntax = "--x86-asm-syntax=intel"; 3607 else 3608 DisassemblerOptions.push_back(V.str()); 3609 } 3610 } 3611 SmallVector<const char *> Args = {"llvm-objdump"}; 3612 for (const opt::Arg *A : InputArgs.filtered(OBJDUMP_mllvm)) 3613 Args.push_back(A->getValue()); 3614 if (AsmSyntax) 3615 Args.push_back(AsmSyntax); 3616 if (Args.size() > 1) 3617 llvm::cl::ParseCommandLineOptions(Args.size(), Args.data()); 3618 3619 // Look up any provided build IDs, then append them to the input filenames. 3620 for (const opt::Arg *A : InputArgs.filtered(OBJDUMP_build_id)) { 3621 object::BuildID BuildID = parseBuildIDArg(A); 3622 std::optional<std::string> Path = BIDFetcher->fetch(BuildID); 3623 if (!Path) { 3624 reportCmdLineError(A->getSpelling() + ": could not find build ID '" + 3625 A->getValue() + "'"); 3626 } 3627 InputFilenames.push_back(std::move(*Path)); 3628 } 3629 3630 // objdump defaults to a.out if no filenames specified. 3631 if (InputFilenames.empty()) 3632 InputFilenames.push_back("a.out"); 3633 } 3634 3635 int llvm_objdump_main(int argc, char **argv, const llvm::ToolContext &) { 3636 using namespace llvm; 3637 3638 ToolName = argv[0]; 3639 std::unique_ptr<CommonOptTable> T; 3640 OptSpecifier Unknown, HelpFlag, HelpHiddenFlag, VersionFlag; 3641 3642 StringRef Stem = sys::path::stem(ToolName); 3643 auto Is = [=](StringRef Tool) { 3644 // We need to recognize the following filenames: 3645 // 3646 // llvm-objdump -> objdump 3647 // llvm-otool-10.exe -> otool 3648 // powerpc64-unknown-freebsd13-objdump -> objdump 3649 auto I = Stem.rfind_insensitive(Tool); 3650 return I != StringRef::npos && 3651 (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()])); 3652 }; 3653 if (Is("otool")) { 3654 T = std::make_unique<OtoolOptTable>(); 3655 Unknown = OTOOL_UNKNOWN; 3656 HelpFlag = OTOOL_help; 3657 HelpHiddenFlag = OTOOL_help_hidden; 3658 VersionFlag = OTOOL_version; 3659 } else { 3660 T = std::make_unique<ObjdumpOptTable>(); 3661 Unknown = OBJDUMP_UNKNOWN; 3662 HelpFlag = OBJDUMP_help; 3663 HelpHiddenFlag = OBJDUMP_help_hidden; 3664 VersionFlag = OBJDUMP_version; 3665 } 3666 3667 BumpPtrAllocator A; 3668 StringSaver Saver(A); 3669 opt::InputArgList InputArgs = 3670 T->parseArgs(argc, argv, Unknown, Saver, 3671 [&](StringRef Msg) { reportCmdLineError(Msg); }); 3672 3673 if (InputArgs.size() == 0 || InputArgs.hasArg(HelpFlag)) { 3674 T->printHelp(ToolName); 3675 return 0; 3676 } 3677 if (InputArgs.hasArg(HelpHiddenFlag)) { 3678 T->printHelp(ToolName, /*ShowHidden=*/true); 3679 return 0; 3680 } 3681 3682 // Initialize targets and assembly printers/parsers. 3683 InitializeAllTargetInfos(); 3684 InitializeAllTargetMCs(); 3685 InitializeAllDisassemblers(); 3686 3687 if (InputArgs.hasArg(VersionFlag)) { 3688 cl::PrintVersionMessage(); 3689 if (!Is("otool")) { 3690 outs() << '\n'; 3691 TargetRegistry::printRegisteredTargetsForVersion(outs()); 3692 } 3693 return 0; 3694 } 3695 3696 // Initialize debuginfod. 3697 const bool ShouldUseDebuginfodByDefault = 3698 InputArgs.hasArg(OBJDUMP_build_id) || canUseDebuginfod(); 3699 std::vector<std::string> DebugFileDirectories = 3700 InputArgs.getAllArgValues(OBJDUMP_debug_file_directory); 3701 if (InputArgs.hasFlag(OBJDUMP_debuginfod, OBJDUMP_no_debuginfod, 3702 ShouldUseDebuginfodByDefault)) { 3703 HTTPClient::initialize(); 3704 BIDFetcher = 3705 std::make_unique<DebuginfodFetcher>(std::move(DebugFileDirectories)); 3706 } else { 3707 BIDFetcher = 3708 std::make_unique<BuildIDFetcher>(std::move(DebugFileDirectories)); 3709 } 3710 3711 if (Is("otool")) 3712 parseOtoolOptions(InputArgs); 3713 else 3714 parseObjdumpOptions(InputArgs); 3715 3716 if (StartAddress >= StopAddress) 3717 reportCmdLineError("start address should be less than stop address"); 3718 3719 // Removes trailing separators from prefix. 3720 while (!Prefix.empty() && sys::path::is_separator(Prefix.back())) 3721 Prefix.pop_back(); 3722 3723 if (AllHeaders) 3724 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations = 3725 SectionHeaders = SymbolTable = true; 3726 3727 if (DisassembleAll || PrintSource || PrintLines || TracebackTable || 3728 !DisassembleSymbols.empty()) 3729 Disassemble = true; 3730 3731 if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null && 3732 !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST && 3733 !Relocations && !SectionHeaders && !SectionContents && !SymbolTable && 3734 !DynamicSymbolTable && !UnwindInfo && !FaultMapSection && !Offloading && 3735 !(MachOOpt && 3736 (Bind || DataInCode || ChainedFixups || DyldInfo || DylibId || 3737 DylibsUsed || ExportsTrie || FirstPrivateHeader || 3738 FunctionStartsType != FunctionStartsMode::None || IndirectSymbols || 3739 InfoPlist || LazyBind || LinkOptHints || ObjcMetaData || Rebase || 3740 Rpaths || UniversalHeaders || WeakBind || !FilterSections.empty()))) { 3741 T->printHelp(ToolName); 3742 return 2; 3743 } 3744 3745 DisasmSymbolSet.insert(DisassembleSymbols.begin(), DisassembleSymbols.end()); 3746 3747 llvm::for_each(InputFilenames, dumpInput); 3748 3749 warnOnNoMatchForSections(); 3750 3751 return EXIT_SUCCESS; 3752 } 3753