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