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