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