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