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