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