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