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