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