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