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