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