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