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