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 "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/ADT/StringSet.h" 23 #include "llvm/ADT/Triple.h" 24 #include "llvm/CodeGen/FaultMaps.h" 25 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 26 #include "llvm/DebugInfo/Symbolize/Symbolize.h" 27 #include "llvm/Demangle/Demangle.h" 28 #include "llvm/MC/MCAsmInfo.h" 29 #include "llvm/MC/MCContext.h" 30 #include "llvm/MC/MCDisassembler/MCDisassembler.h" 31 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h" 32 #include "llvm/MC/MCInst.h" 33 #include "llvm/MC/MCInstPrinter.h" 34 #include "llvm/MC/MCInstrAnalysis.h" 35 #include "llvm/MC/MCInstrInfo.h" 36 #include "llvm/MC/MCObjectFileInfo.h" 37 #include "llvm/MC/MCRegisterInfo.h" 38 #include "llvm/MC/MCSubtargetInfo.h" 39 #include "llvm/Object/Archive.h" 40 #include "llvm/Object/COFF.h" 41 #include "llvm/Object/COFFImportFile.h" 42 #include "llvm/Object/ELFObjectFile.h" 43 #include "llvm/Object/MachO.h" 44 #include "llvm/Object/MachOUniversal.h" 45 #include "llvm/Object/ObjectFile.h" 46 #include "llvm/Object/Wasm.h" 47 #include "llvm/Support/Casting.h" 48 #include "llvm/Support/CommandLine.h" 49 #include "llvm/Support/Debug.h" 50 #include "llvm/Support/Errc.h" 51 #include "llvm/Support/FileSystem.h" 52 #include "llvm/Support/Format.h" 53 #include "llvm/Support/GraphWriter.h" 54 #include "llvm/Support/Host.h" 55 #include "llvm/Support/InitLLVM.h" 56 #include "llvm/Support/MemoryBuffer.h" 57 #include "llvm/Support/SourceMgr.h" 58 #include "llvm/Support/StringSaver.h" 59 #include "llvm/Support/TargetRegistry.h" 60 #include "llvm/Support/TargetSelect.h" 61 #include "llvm/Support/WithColor.h" 62 #include "llvm/Support/raw_ostream.h" 63 #include <algorithm> 64 #include <cctype> 65 #include <cstring> 66 #include <system_error> 67 #include <unordered_map> 68 #include <utility> 69 70 using namespace llvm; 71 using namespace object; 72 73 cl::opt<unsigned long long> AdjustVMA( 74 "adjust-vma", 75 cl::desc("Increase the displayed address by the specified offset"), 76 cl::value_desc("offset"), cl::init(0)); 77 78 cl::opt<bool> 79 llvm::AllHeaders("all-headers", 80 cl::desc("Display all available header information")); 81 static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"), 82 cl::NotHidden, cl::Grouping, 83 cl::aliasopt(AllHeaders)); 84 85 static cl::list<std::string> 86 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore); 87 88 cl::opt<bool> 89 llvm::Disassemble("disassemble", 90 cl::desc("Display assembler mnemonics for the machine instructions")); 91 static cl::alias Disassembled("d", cl::desc("Alias for --disassemble"), 92 cl::NotHidden, cl::Grouping, 93 cl::aliasopt(Disassemble)); 94 95 cl::opt<bool> 96 llvm::DisassembleAll("disassemble-all", 97 cl::desc("Display assembler mnemonics for the machine instructions")); 98 static cl::alias DisassembleAlld("D", cl::desc("Alias for --disassemble-all"), 99 cl::NotHidden, cl::Grouping, 100 cl::aliasopt(DisassembleAll)); 101 102 cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"), 103 cl::init(false)); 104 105 static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"), 106 cl::NotHidden, cl::Grouping, 107 cl::aliasopt(llvm::Demangle)); 108 109 static cl::list<std::string> 110 DisassembleFunctions("disassemble-functions", 111 cl::CommaSeparated, 112 cl::desc("List of functions to disassemble")); 113 static StringSet<> DisasmFuncsSet; 114 115 cl::opt<bool> 116 llvm::Relocations("reloc", 117 cl::desc("Display the relocation entries in the file")); 118 static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"), 119 cl::NotHidden, cl::Grouping, 120 cl::aliasopt(llvm::Relocations)); 121 122 cl::opt<bool> 123 llvm::DynamicRelocations("dynamic-reloc", 124 cl::desc("Display the dynamic relocation entries in the file")); 125 static cl::alias DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"), 126 cl::NotHidden, cl::Grouping, 127 cl::aliasopt(DynamicRelocations)); 128 129 cl::opt<bool> 130 llvm::SectionContents("full-contents", 131 cl::desc("Display the content of each section")); 132 static cl::alias SectionContentsShort("s", 133 cl::desc("Alias for --full-contents"), 134 cl::NotHidden, cl::Grouping, 135 cl::aliasopt(SectionContents)); 136 137 cl::opt<bool> llvm::SymbolTable("syms", cl::desc("Display the symbol table")); 138 static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"), 139 cl::NotHidden, cl::Grouping, 140 cl::aliasopt(llvm::SymbolTable)); 141 142 cl::opt<bool> 143 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols")); 144 145 cl::opt<bool> 146 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info")); 147 148 cl::opt<bool> 149 llvm::Bind("bind", cl::desc("Display mach-o binding info")); 150 151 cl::opt<bool> 152 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info")); 153 154 cl::opt<bool> 155 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info")); 156 157 cl::opt<bool> 158 llvm::RawClangAST("raw-clang-ast", 159 cl::desc("Dump the raw binary contents of the clang AST section")); 160 161 static cl::opt<bool> 162 MachOOpt("macho", cl::desc("Use MachO specific object file parser")); 163 static cl::alias MachOm("m", cl::desc("Alias for --macho"), cl::NotHidden, 164 cl::Grouping, cl::aliasopt(MachOOpt)); 165 166 cl::opt<std::string> 167 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, " 168 "see -version for available targets")); 169 170 cl::opt<std::string> 171 llvm::MCPU("mcpu", 172 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 173 cl::value_desc("cpu-name"), 174 cl::init("")); 175 176 cl::opt<std::string> 177 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, " 178 "see -version for available targets")); 179 180 cl::opt<bool> 181 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the " 182 "headers for each section.")); 183 static cl::alias SectionHeadersShort("headers", 184 cl::desc("Alias for --section-headers"), 185 cl::NotHidden, 186 cl::aliasopt(SectionHeaders)); 187 static cl::alias SectionHeadersShorter("h", 188 cl::desc("Alias for --section-headers"), 189 cl::NotHidden, cl::Grouping, 190 cl::aliasopt(SectionHeaders)); 191 192 static cl::opt<bool> 193 ShowLMA("show-lma", 194 cl::desc("Display LMA column when dumping ELF section headers")); 195 196 cl::list<std::string> 197 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. " 198 "With -macho dump segment,section")); 199 cl::alias static FilterSectionsj("j", cl::desc("Alias for --section"), 200 cl::NotHidden, 201 cl::aliasopt(llvm::FilterSections)); 202 203 cl::list<std::string> 204 llvm::MAttrs("mattr", 205 cl::CommaSeparated, 206 cl::desc("Target specific attributes"), 207 cl::value_desc("a1,+a2,-a3,...")); 208 209 cl::opt<bool> 210 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling " 211 "instructions, do not print " 212 "the instruction bytes.")); 213 cl::opt<bool> 214 llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address")); 215 216 cl::opt<bool> 217 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information")); 218 219 static cl::alias UnwindInfoShort("u", cl::desc("Alias for --unwind-info"), 220 cl::NotHidden, cl::Grouping, 221 cl::aliasopt(UnwindInfo)); 222 223 cl::opt<bool> 224 llvm::PrivateHeaders("private-headers", 225 cl::desc("Display format specific file headers")); 226 227 cl::opt<bool> 228 llvm::FirstPrivateHeader("private-header", 229 cl::desc("Display only the first format specific file " 230 "header")); 231 232 static cl::alias PrivateHeadersShort("p", 233 cl::desc("Alias for --private-headers"), 234 cl::NotHidden, cl::Grouping, 235 cl::aliasopt(PrivateHeaders)); 236 237 cl::opt<bool> llvm::FileHeaders( 238 "file-headers", 239 cl::desc("Display the contents of the overall file header")); 240 241 static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"), 242 cl::NotHidden, cl::Grouping, 243 cl::aliasopt(FileHeaders)); 244 245 cl::opt<bool> 246 llvm::ArchiveHeaders("archive-headers", 247 cl::desc("Display archive header information")); 248 249 cl::alias ArchiveHeadersShort("a", cl::desc("Alias for --archive-headers"), 250 cl::NotHidden, cl::Grouping, 251 cl::aliasopt(ArchiveHeaders)); 252 253 cl::opt<bool> 254 llvm::PrintImmHex("print-imm-hex", 255 cl::desc("Use hex format for immediate values")); 256 257 cl::opt<bool> PrintFaultMaps("fault-map-section", 258 cl::desc("Display contents of faultmap section")); 259 260 cl::opt<DIDumpType> llvm::DwarfDumpType( 261 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"), 262 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame"))); 263 264 cl::opt<bool> PrintSource( 265 "source", 266 cl::desc( 267 "Display source inlined with disassembly. Implies disassemble object")); 268 269 cl::alias PrintSourceShort("S", cl::desc("Alias for -source"), cl::NotHidden, 270 cl::Grouping, cl::aliasopt(PrintSource)); 271 272 cl::opt<bool> PrintLines("line-numbers", 273 cl::desc("Display source line numbers with " 274 "disassembly. Implies disassemble object")); 275 276 cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"), 277 cl::NotHidden, cl::Grouping, 278 cl::aliasopt(PrintLines)); 279 280 cl::opt<unsigned long long> 281 StartAddress("start-address", cl::desc("Disassemble beginning at address"), 282 cl::value_desc("address"), cl::init(0)); 283 cl::opt<unsigned long long> 284 StopAddress("stop-address", 285 cl::desc("Stop disassembly at address"), 286 cl::value_desc("address"), cl::init(UINT64_MAX)); 287 288 cl::opt<bool> DisassembleZeroes( 289 "disassemble-zeroes", 290 cl::desc("Do not skip blocks of zeroes when disassembling")); 291 cl::alias DisassembleZeroesShort("z", 292 cl::desc("Alias for --disassemble-zeroes"), 293 cl::NotHidden, cl::Grouping, 294 cl::aliasopt(DisassembleZeroes)); 295 296 static cl::list<std::string> 297 DisassemblerOptions("disassembler-options", 298 cl::desc("Pass target specific disassembler options"), 299 cl::value_desc("options"), cl::CommaSeparated); 300 static cl::alias 301 DisassemblerOptionsShort("M", cl::desc("Alias for --disassembler-options"), 302 cl::NotHidden, cl::Prefix, cl::CommaSeparated, 303 cl::aliasopt(DisassemblerOptions)); 304 305 static StringRef ToolName; 306 307 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy; 308 309 SectionFilter llvm::ToolSectionFilter(llvm::object::ObjectFile const &O) { 310 return SectionFilter( 311 [](llvm::object::SectionRef const &S) { 312 if (FilterSections.empty()) 313 return true; 314 llvm::StringRef String; 315 std::error_code error = S.getName(String); 316 if (error) 317 return false; 318 return is_contained(FilterSections, String); 319 }, 320 O); 321 } 322 323 void llvm::error(std::error_code EC) { 324 if (!EC) 325 return; 326 WithColor::error(errs(), ToolName) 327 << "reading file: " << EC.message() << ".\n"; 328 errs().flush(); 329 exit(1); 330 } 331 332 LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) { 333 WithColor::error(errs(), ToolName) << Message << ".\n"; 334 errs().flush(); 335 exit(1); 336 } 337 338 void llvm::warn(StringRef Message) { 339 WithColor::warning(errs(), ToolName) << Message << ".\n"; 340 errs().flush(); 341 } 342 343 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File, 344 Twine Message) { 345 WithColor::error(errs(), ToolName) 346 << "'" << File << "': " << Message << ".\n"; 347 exit(1); 348 } 349 350 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File, 351 std::error_code EC) { 352 assert(EC); 353 WithColor::error(errs(), ToolName) 354 << "'" << File << "': " << EC.message() << ".\n"; 355 exit(1); 356 } 357 358 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File, 359 llvm::Error E) { 360 assert(E); 361 std::string Buf; 362 raw_string_ostream OS(Buf); 363 logAllUnhandledErrors(std::move(E), OS); 364 OS.flush(); 365 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf; 366 exit(1); 367 } 368 369 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName, 370 StringRef FileName, 371 llvm::Error E, 372 StringRef ArchitectureName) { 373 assert(E); 374 WithColor::error(errs(), ToolName); 375 if (ArchiveName != "") 376 errs() << ArchiveName << "(" << FileName << ")"; 377 else 378 errs() << "'" << FileName << "'"; 379 if (!ArchitectureName.empty()) 380 errs() << " (for architecture " << ArchitectureName << ")"; 381 std::string Buf; 382 raw_string_ostream OS(Buf); 383 logAllUnhandledErrors(std::move(E), OS); 384 OS.flush(); 385 errs() << ": " << Buf; 386 exit(1); 387 } 388 389 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName, 390 const object::Archive::Child &C, 391 llvm::Error E, 392 StringRef ArchitectureName) { 393 Expected<StringRef> NameOrErr = C.getName(); 394 // TODO: if we have a error getting the name then it would be nice to print 395 // the index of which archive member this is and or its offset in the 396 // archive instead of "???" as the name. 397 if (!NameOrErr) { 398 consumeError(NameOrErr.takeError()); 399 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName); 400 } else 401 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E), 402 ArchitectureName); 403 } 404 405 static const Target *getTarget(const ObjectFile *Obj = nullptr) { 406 // Figure out the target triple. 407 llvm::Triple TheTriple("unknown-unknown-unknown"); 408 if (TripleName.empty()) { 409 if (Obj) 410 TheTriple = Obj->makeTriple(); 411 } else { 412 TheTriple.setTriple(Triple::normalize(TripleName)); 413 414 // Use the triple, but also try to combine with ARM build attributes. 415 if (Obj) { 416 auto Arch = Obj->getArch(); 417 if (Arch == Triple::arm || Arch == Triple::armeb) 418 Obj->setARMSubArch(TheTriple); 419 } 420 } 421 422 // Get the target specific parser. 423 std::string Error; 424 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, 425 Error); 426 if (!TheTarget) { 427 if (Obj) 428 report_error(Obj->getFileName(), "can't find target: " + Error); 429 else 430 error("can't find target: " + Error); 431 } 432 433 // Update the triple name and return the found target. 434 TripleName = TheTriple.getTriple(); 435 return TheTarget; 436 } 437 438 bool llvm::isRelocAddressLess(RelocationRef A, RelocationRef B) { 439 return A.getOffset() < B.getOffset(); 440 } 441 442 static std::error_code getRelocationValueString(const RelocationRef &Rel, 443 SmallVectorImpl<char> &Result) { 444 const ObjectFile *Obj = Rel.getObject(); 445 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj)) 446 return getELFRelocationValueString(ELF, Rel, Result); 447 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj)) 448 return getCOFFRelocationValueString(COFF, Rel, Result); 449 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj)) 450 return getWasmRelocationValueString(Wasm, Rel, Result); 451 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj)) 452 return getMachORelocationValueString(MachO, Rel, Result); 453 llvm_unreachable("unknown object file format"); 454 } 455 456 /// Indicates whether this relocation should hidden when listing 457 /// relocations, usually because it is the trailing part of a multipart 458 /// relocation that will be printed as part of the leading relocation. 459 static bool getHidden(RelocationRef RelRef) { 460 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject()); 461 if (!MachO) 462 return false; 463 464 unsigned Arch = MachO->getArch(); 465 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 466 uint64_t Type = MachO->getRelocationType(Rel); 467 468 // On arches that use the generic relocations, GENERIC_RELOC_PAIR 469 // is always hidden. 470 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) 471 return Type == MachO::GENERIC_RELOC_PAIR; 472 473 if (Arch == Triple::x86_64) { 474 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows 475 // an X86_64_RELOC_SUBTRACTOR. 476 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) { 477 DataRefImpl RelPrev = Rel; 478 RelPrev.d.a--; 479 uint64_t PrevType = MachO->getRelocationType(RelPrev); 480 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR) 481 return true; 482 } 483 } 484 485 return false; 486 } 487 488 namespace { 489 class SourcePrinter { 490 protected: 491 DILineInfo OldLineInfo; 492 const ObjectFile *Obj = nullptr; 493 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer; 494 // File name to file contents of source 495 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache; 496 // Mark the line endings of the cached source 497 std::unordered_map<std::string, std::vector<StringRef>> LineCache; 498 499 private: 500 bool cacheSource(const DILineInfo& LineInfoFile); 501 502 public: 503 SourcePrinter() = default; 504 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) { 505 symbolize::LLVMSymbolizer::Options SymbolizerOpts( 506 DILineInfoSpecifier::FunctionNameKind::None, true, false, false, 507 DefaultArch); 508 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts)); 509 } 510 virtual ~SourcePrinter() = default; 511 virtual void printSourceLine(raw_ostream &OS, 512 object::SectionedAddress Address, 513 StringRef Delimiter = "; "); 514 }; 515 516 bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) { 517 std::unique_ptr<MemoryBuffer> Buffer; 518 if (LineInfo.Source) { 519 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source); 520 } else { 521 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName); 522 if (!BufferOrError) 523 return false; 524 Buffer = std::move(*BufferOrError); 525 } 526 // Chomp the file to get lines 527 size_t BufferSize = Buffer->getBufferSize(); 528 const char *BufferStart = Buffer->getBufferStart(); 529 for (const char *Start = BufferStart, *End = BufferStart; 530 End < BufferStart + BufferSize; End++) 531 if (*End == '\n' || End == BufferStart + BufferSize - 1 || 532 (*End == '\r' && *(End + 1) == '\n')) { 533 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start)); 534 if (*End == '\r') 535 End++; 536 Start = End + 1; 537 } 538 SourceCache[LineInfo.FileName] = std::move(Buffer); 539 return true; 540 } 541 542 void SourcePrinter::printSourceLine(raw_ostream &OS, 543 object::SectionedAddress Address, 544 StringRef Delimiter) { 545 if (!Symbolizer) 546 return; 547 DILineInfo LineInfo = DILineInfo(); 548 auto ExpectecLineInfo = 549 Symbolizer->symbolizeCode(Obj->getFileName(), Address); 550 if (!ExpectecLineInfo) 551 consumeError(ExpectecLineInfo.takeError()); 552 else 553 LineInfo = *ExpectecLineInfo; 554 555 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line || 556 LineInfo.Line == 0) 557 return; 558 559 if (PrintLines) 560 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n"; 561 if (PrintSource) { 562 if (SourceCache.find(LineInfo.FileName) == SourceCache.end()) 563 if (!cacheSource(LineInfo)) 564 return; 565 auto FileBuffer = SourceCache.find(LineInfo.FileName); 566 if (FileBuffer != SourceCache.end()) { 567 auto LineBuffer = LineCache.find(LineInfo.FileName); 568 if (LineBuffer != LineCache.end()) { 569 if (LineInfo.Line > LineBuffer->second.size()) 570 return; 571 // Vector begins at 0, line numbers are non-zero 572 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim() 573 << "\n"; 574 } 575 } 576 } 577 OldLineInfo = LineInfo; 578 } 579 580 static bool isArmElf(const ObjectFile *Obj) { 581 return (Obj->isELF() && 582 (Obj->getArch() == Triple::aarch64 || 583 Obj->getArch() == Triple::aarch64_be || 584 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb || 585 Obj->getArch() == Triple::thumb || 586 Obj->getArch() == Triple::thumbeb)); 587 } 588 589 static void printRelocation(const RelocationRef &Rel, uint64_t Address, 590 uint8_t AddrSize) { 591 StringRef Fmt = 592 AddrSize > 4 ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": "; 593 SmallString<16> Name; 594 SmallString<32> Val; 595 Rel.getTypeName(Name); 596 error(getRelocationValueString(Rel, Val)); 597 outs() << format(Fmt.data(), Address) << Name << "\t" << Val << "\n"; 598 } 599 600 class PrettyPrinter { 601 public: 602 virtual ~PrettyPrinter() = default; 603 virtual void printInst(MCInstPrinter &IP, const MCInst *MI, 604 ArrayRef<uint8_t> Bytes, 605 object::SectionedAddress Address, raw_ostream &OS, 606 StringRef Annot, MCSubtargetInfo const &STI, 607 SourcePrinter *SP, 608 std::vector<RelocationRef> *Rels = nullptr) { 609 if (SP && (PrintSource || PrintLines)) 610 SP->printSourceLine(OS, Address); 611 if (!NoLeadingAddr) 612 OS << format("%8" PRIx64 ":", Address.Address); 613 if (!NoShowRawInsn) { 614 OS << "\t"; 615 dumpBytes(Bytes, OS); 616 } 617 if (MI) 618 IP.printInst(MI, OS, "", STI); 619 else 620 OS << " <unknown>"; 621 } 622 }; 623 PrettyPrinter PrettyPrinterInst; 624 class HexagonPrettyPrinter : public PrettyPrinter { 625 public: 626 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address, 627 raw_ostream &OS) { 628 uint32_t opcode = 629 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0]; 630 if (!NoLeadingAddr) 631 OS << format("%8" PRIx64 ":", Address); 632 if (!NoShowRawInsn) { 633 OS << "\t"; 634 dumpBytes(Bytes.slice(0, 4), OS); 635 OS << format("%08" PRIx32, opcode); 636 } 637 } 638 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 639 object::SectionedAddress Address, raw_ostream &OS, 640 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, 641 std::vector<RelocationRef> *Rels) override { 642 if (SP && (PrintSource || PrintLines)) 643 SP->printSourceLine(OS, Address, ""); 644 if (!MI) { 645 printLead(Bytes, Address.Address, OS); 646 OS << " <unknown>"; 647 return; 648 } 649 std::string Buffer; 650 { 651 raw_string_ostream TempStream(Buffer); 652 IP.printInst(MI, TempStream, "", STI); 653 } 654 StringRef Contents(Buffer); 655 // Split off bundle attributes 656 auto PacketBundle = Contents.rsplit('\n'); 657 // Split off first instruction from the rest 658 auto HeadTail = PacketBundle.first.split('\n'); 659 auto Preamble = " { "; 660 auto Separator = ""; 661 662 // Hexagon's packets require relocations to be inline rather than 663 // clustered at the end of the packet. 664 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin(); 665 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end(); 666 auto PrintReloc = [&]() -> void { 667 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address.Address)) { 668 if (RelCur->getOffset() == Address.Address) { 669 printRelocation(*RelCur, Address.Address, 4); 670 return; 671 } 672 ++RelCur; 673 } 674 }; 675 676 while (!HeadTail.first.empty()) { 677 OS << Separator; 678 Separator = "\n"; 679 if (SP && (PrintSource || PrintLines)) 680 SP->printSourceLine(OS, Address, ""); 681 printLead(Bytes, Address.Address, OS); 682 OS << Preamble; 683 Preamble = " "; 684 StringRef Inst; 685 auto Duplex = HeadTail.first.split('\v'); 686 if (!Duplex.second.empty()) { 687 OS << Duplex.first; 688 OS << "; "; 689 Inst = Duplex.second; 690 } 691 else 692 Inst = HeadTail.first; 693 OS << Inst; 694 HeadTail = HeadTail.second.split('\n'); 695 if (HeadTail.first.empty()) 696 OS << " } " << PacketBundle.second; 697 PrintReloc(); 698 Bytes = Bytes.slice(4); 699 Address.Address += 4; 700 } 701 } 702 }; 703 HexagonPrettyPrinter HexagonPrettyPrinterInst; 704 705 class AMDGCNPrettyPrinter : public PrettyPrinter { 706 public: 707 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 708 object::SectionedAddress Address, raw_ostream &OS, 709 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, 710 std::vector<RelocationRef> *Rels) override { 711 if (SP && (PrintSource || PrintLines)) 712 SP->printSourceLine(OS, Address); 713 714 typedef support::ulittle32_t U32; 715 716 if (MI) { 717 SmallString<40> InstStr; 718 raw_svector_ostream IS(InstStr); 719 720 IP.printInst(MI, IS, "", STI); 721 722 OS << left_justify(IS.str(), 60); 723 } else { 724 // an unrecognized encoding - this is probably data so represent it 725 // using the .long directive, or .byte directive if fewer than 4 bytes 726 // remaining 727 if (Bytes.size() >= 4) { 728 OS << format("\t.long 0x%08" PRIx32 " ", 729 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data()))); 730 OS.indent(42); 731 } else { 732 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]); 733 for (unsigned int i = 1; i < Bytes.size(); i++) 734 OS << format(", 0x%02" PRIx8, Bytes[i]); 735 OS.indent(55 - (6 * Bytes.size())); 736 } 737 } 738 739 OS << format("// %012" PRIX64 ": ", Address.Address); 740 if (Bytes.size() >=4) { 741 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()), 742 Bytes.size() / sizeof(U32))) 743 // D should be explicitly casted to uint32_t here as it is passed 744 // by format to snprintf as vararg. 745 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D)); 746 } else { 747 for (unsigned int i = 0; i < Bytes.size(); i++) 748 OS << format("%02" PRIX8 " ", Bytes[i]); 749 } 750 751 if (!Annot.empty()) 752 OS << "// " << Annot; 753 } 754 }; 755 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst; 756 757 class BPFPrettyPrinter : public PrettyPrinter { 758 public: 759 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, 760 object::SectionedAddress Address, raw_ostream &OS, 761 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, 762 std::vector<RelocationRef> *Rels) override { 763 if (SP && (PrintSource || PrintLines)) 764 SP->printSourceLine(OS, Address); 765 if (!NoLeadingAddr) 766 OS << format("%8" PRId64 ":", Address.Address / 8); 767 if (!NoShowRawInsn) { 768 OS << "\t"; 769 dumpBytes(Bytes, OS); 770 } 771 if (MI) 772 IP.printInst(MI, OS, "", STI); 773 else 774 OS << " <unknown>"; 775 } 776 }; 777 BPFPrettyPrinter BPFPrettyPrinterInst; 778 779 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) { 780 switch(Triple.getArch()) { 781 default: 782 return PrettyPrinterInst; 783 case Triple::hexagon: 784 return HexagonPrettyPrinterInst; 785 case Triple::amdgcn: 786 return AMDGCNPrettyPrinterInst; 787 case Triple::bpfel: 788 case Triple::bpfeb: 789 return BPFPrettyPrinterInst; 790 } 791 } 792 } 793 794 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) { 795 assert(Obj->isELF()); 796 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj)) 797 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 798 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj)) 799 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 800 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj)) 801 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 802 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj)) 803 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType(); 804 llvm_unreachable("Unsupported binary format"); 805 } 806 807 template <class ELFT> static void 808 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj, 809 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { 810 for (auto Symbol : Obj->getDynamicSymbolIterators()) { 811 uint8_t SymbolType = Symbol.getELFType(); 812 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0) 813 continue; 814 815 Expected<uint64_t> AddressOrErr = Symbol.getAddress(); 816 if (!AddressOrErr) 817 report_error(Obj->getFileName(), AddressOrErr.takeError()); 818 819 Expected<StringRef> Name = Symbol.getName(); 820 if (!Name) 821 report_error(Obj->getFileName(), Name.takeError()); 822 if (Name->empty()) 823 continue; 824 825 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 826 if (!SectionOrErr) 827 report_error(Obj->getFileName(), SectionOrErr.takeError()); 828 section_iterator SecI = *SectionOrErr; 829 if (SecI == Obj->section_end()) 830 continue; 831 832 AllSymbols[*SecI].emplace_back(*AddressOrErr, *Name, SymbolType); 833 } 834 } 835 836 static void 837 addDynamicElfSymbols(const ObjectFile *Obj, 838 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { 839 assert(Obj->isELF()); 840 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj)) 841 addDynamicElfSymbols(Elf32LEObj, AllSymbols); 842 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj)) 843 addDynamicElfSymbols(Elf64LEObj, AllSymbols); 844 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj)) 845 addDynamicElfSymbols(Elf32BEObj, AllSymbols); 846 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj)) 847 addDynamicElfSymbols(Elf64BEObj, AllSymbols); 848 else 849 llvm_unreachable("Unsupported binary format"); 850 } 851 852 static void addPltEntries(const ObjectFile *Obj, 853 std::map<SectionRef, SectionSymbolsTy> &AllSymbols, 854 StringSaver &Saver) { 855 Optional<SectionRef> Plt = None; 856 for (const SectionRef &Section : Obj->sections()) { 857 StringRef Name; 858 if (Section.getName(Name)) 859 continue; 860 if (Name == ".plt") 861 Plt = Section; 862 } 863 if (!Plt) 864 return; 865 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) { 866 for (auto PltEntry : ElfObj->getPltAddresses()) { 867 SymbolRef Symbol(PltEntry.first, ElfObj); 868 uint8_t SymbolType = getElfSymbolType(Obj, Symbol); 869 870 Expected<StringRef> NameOrErr = Symbol.getName(); 871 if (!NameOrErr) 872 report_error(Obj->getFileName(), NameOrErr.takeError()); 873 if (NameOrErr->empty()) 874 continue; 875 StringRef Name = Saver.save((*NameOrErr + "@plt").str()); 876 877 AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType); 878 } 879 } 880 } 881 882 // Normally the disassembly output will skip blocks of zeroes. This function 883 // returns the number of zero bytes that can be skipped when dumping the 884 // disassembly of the instructions in Buf. 885 static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) { 886 // Find the number of leading zeroes. 887 size_t N = 0; 888 while (N < Buf.size() && !Buf[N]) 889 ++N; 890 891 // We may want to skip blocks of zero bytes, but unless we see 892 // at least 8 of them in a row. 893 if (N < 8) 894 return 0; 895 896 // We skip zeroes in multiples of 4 because do not want to truncate an 897 // instruction if it starts with a zero byte. 898 return N & ~0x3; 899 } 900 901 // Returns a map from sections to their relocations. 902 static std::map<SectionRef, std::vector<RelocationRef>> 903 getRelocsMap(llvm::object::ObjectFile const &Obj) { 904 std::map<SectionRef, std::vector<RelocationRef>> Ret; 905 for (const SectionRef &Section : ToolSectionFilter(Obj)) { 906 section_iterator RelSec = Section.getRelocatedSection(); 907 if (RelSec == Obj.section_end()) 908 continue; 909 std::vector<RelocationRef> &V = Ret[*RelSec]; 910 for (const RelocationRef &R : Section.relocations()) 911 V.push_back(R); 912 // Sort relocations by address. 913 llvm::sort(V, isRelocAddressLess); 914 } 915 return Ret; 916 } 917 918 // Used for --adjust-vma to check if address should be adjusted by the 919 // specified value for a given section. 920 // For ELF we do not adjust non-allocatable sections like debug ones, 921 // because they are not loadable. 922 // TODO: implement for other file formats. 923 static bool shouldAdjustVA(const SectionRef &Section) { 924 const ObjectFile *Obj = Section.getObject(); 925 if (isa<object::ELFObjectFileBase>(Obj)) 926 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC; 927 return false; 928 } 929 930 static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj, 931 MCContext &Ctx, MCDisassembler *DisAsm, 932 const MCInstrAnalysis *MIA, MCInstPrinter *IP, 933 const MCSubtargetInfo *STI, PrettyPrinter &PIP, 934 SourcePrinter &SP, bool InlineRelocs) { 935 std::map<SectionRef, std::vector<RelocationRef>> RelocMap; 936 if (InlineRelocs) 937 RelocMap = getRelocsMap(*Obj); 938 939 // Create a mapping from virtual address to symbol name. This is used to 940 // pretty print the symbols while disassembling. 941 std::map<SectionRef, SectionSymbolsTy> AllSymbols; 942 SectionSymbolsTy AbsoluteSymbols; 943 for (const SymbolRef &Symbol : Obj->symbols()) { 944 Expected<uint64_t> AddressOrErr = Symbol.getAddress(); 945 if (!AddressOrErr) 946 report_error(Obj->getFileName(), AddressOrErr.takeError()); 947 uint64_t Address = *AddressOrErr; 948 949 Expected<StringRef> Name = Symbol.getName(); 950 if (!Name) 951 report_error(Obj->getFileName(), Name.takeError()); 952 if (Name->empty()) 953 continue; 954 955 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 956 if (!SectionOrErr) 957 report_error(Obj->getFileName(), SectionOrErr.takeError()); 958 959 uint8_t SymbolType = ELF::STT_NOTYPE; 960 if (Obj->isELF()) { 961 SymbolType = getElfSymbolType(Obj, Symbol); 962 if (SymbolType == ELF::STT_SECTION) 963 continue; 964 } 965 966 section_iterator SecI = *SectionOrErr; 967 if (SecI != Obj->section_end()) 968 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType); 969 else 970 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType); 971 972 973 } 974 if (AllSymbols.empty() && Obj->isELF()) 975 addDynamicElfSymbols(Obj, AllSymbols); 976 977 BumpPtrAllocator A; 978 StringSaver Saver(A); 979 addPltEntries(Obj, AllSymbols, Saver); 980 981 // Create a mapping from virtual address to section. 982 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses; 983 for (SectionRef Sec : Obj->sections()) 984 SectionAddresses.emplace_back(Sec.getAddress(), Sec); 985 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end()); 986 987 // Linked executables (.exe and .dll files) typically don't include a real 988 // symbol table but they might contain an export table. 989 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) { 990 for (const auto &ExportEntry : COFFObj->export_directories()) { 991 StringRef Name; 992 error(ExportEntry.getSymbolName(Name)); 993 if (Name.empty()) 994 continue; 995 uint32_t RVA; 996 error(ExportEntry.getExportRVA(RVA)); 997 998 uint64_t VA = COFFObj->getImageBase() + RVA; 999 auto Sec = std::upper_bound( 1000 SectionAddresses.begin(), SectionAddresses.end(), VA, 1001 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) { 1002 return LHS < RHS.first; 1003 }); 1004 if (Sec != SectionAddresses.begin()) 1005 --Sec; 1006 else 1007 Sec = SectionAddresses.end(); 1008 1009 if (Sec != SectionAddresses.end()) 1010 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE); 1011 else 1012 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE); 1013 } 1014 } 1015 1016 // Sort all the symbols, this allows us to use a simple binary search to find 1017 // a symbol near an address. 1018 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols) 1019 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end()); 1020 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end()); 1021 1022 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1023 if (!DisassembleAll && (!Section.isText() || Section.isVirtual())) 1024 continue; 1025 1026 uint64_t SectionAddr = Section.getAddress(); 1027 uint64_t SectSize = Section.getSize(); 1028 if (!SectSize) 1029 continue; 1030 1031 // Get the list of all the symbols in this section. 1032 SectionSymbolsTy &Symbols = AllSymbols[Section]; 1033 std::vector<uint64_t> DataMappingSymsAddr; 1034 std::vector<uint64_t> TextMappingSymsAddr; 1035 if (isArmElf(Obj)) { 1036 for (const auto &Symb : Symbols) { 1037 uint64_t Address = std::get<0>(Symb); 1038 StringRef Name = std::get<1>(Symb); 1039 if (Name.startswith("$d")) 1040 DataMappingSymsAddr.push_back(Address - SectionAddr); 1041 if (Name.startswith("$x")) 1042 TextMappingSymsAddr.push_back(Address - SectionAddr); 1043 if (Name.startswith("$a")) 1044 TextMappingSymsAddr.push_back(Address - SectionAddr); 1045 if (Name.startswith("$t")) 1046 TextMappingSymsAddr.push_back(Address - SectionAddr); 1047 } 1048 } 1049 1050 llvm::sort(DataMappingSymsAddr); 1051 llvm::sort(TextMappingSymsAddr); 1052 1053 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1054 // AMDGPU disassembler uses symbolizer for printing labels 1055 std::unique_ptr<MCRelocationInfo> RelInfo( 1056 TheTarget->createMCRelocationInfo(TripleName, Ctx)); 1057 if (RelInfo) { 1058 std::unique_ptr<MCSymbolizer> Symbolizer( 1059 TheTarget->createMCSymbolizer( 1060 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo))); 1061 DisAsm->setSymbolizer(std::move(Symbolizer)); 1062 } 1063 } 1064 1065 StringRef SegmentName = ""; 1066 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) { 1067 DataRefImpl DR = Section.getRawDataRefImpl(); 1068 SegmentName = MachO->getSectionFinalSegmentName(DR); 1069 } 1070 StringRef SectionName; 1071 error(Section.getName(SectionName)); 1072 1073 // If the section has no symbol at the start, just insert a dummy one. 1074 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) { 1075 Symbols.insert( 1076 Symbols.begin(), 1077 std::make_tuple(SectionAddr, SectionName, 1078 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT)); 1079 } 1080 1081 SmallString<40> Comments; 1082 raw_svector_ostream CommentStream(Comments); 1083 1084 StringRef BytesStr; 1085 error(Section.getContents(BytesStr)); 1086 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()), 1087 BytesStr.size()); 1088 1089 uint64_t VMAAdjustment = 0; 1090 if (shouldAdjustVA(Section)) 1091 VMAAdjustment = AdjustVMA; 1092 1093 uint64_t Size; 1094 uint64_t Index; 1095 bool PrintedSection = false; 1096 std::vector<RelocationRef> Rels = RelocMap[Section]; 1097 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin(); 1098 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end(); 1099 // Disassemble symbol by symbol. 1100 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) { 1101 uint64_t Start = std::get<0>(Symbols[SI]) - SectionAddr; 1102 // The end is either the section end or the beginning of the next 1103 // symbol. 1104 uint64_t End = (SI == SE - 1) 1105 ? SectSize 1106 : std::get<0>(Symbols[SI + 1]) - SectionAddr; 1107 // Don't try to disassemble beyond the end of section contents. 1108 if (End > SectSize) 1109 End = SectSize; 1110 // If this symbol has the same address as the next symbol, then skip it. 1111 if (Start >= End) 1112 continue; 1113 1114 // Check if we need to skip symbol 1115 // Skip if the symbol's data is not between StartAddress and StopAddress 1116 if (End + SectionAddr < StartAddress || 1117 Start + SectionAddr > StopAddress) { 1118 continue; 1119 } 1120 1121 /// Skip if user requested specific symbols and this is not in the list 1122 if (!DisasmFuncsSet.empty() && 1123 !DisasmFuncsSet.count(std::get<1>(Symbols[SI]))) 1124 continue; 1125 1126 if (!PrintedSection) { 1127 PrintedSection = true; 1128 outs() << "Disassembly of section "; 1129 if (!SegmentName.empty()) 1130 outs() << SegmentName << ","; 1131 outs() << SectionName << ':'; 1132 } 1133 1134 // Stop disassembly at the stop address specified 1135 if (End + SectionAddr > StopAddress) 1136 End = StopAddress - SectionAddr; 1137 1138 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1139 if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) { 1140 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes) 1141 Start += 256; 1142 } 1143 if (SI == SE - 1 || 1144 std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) { 1145 // cut trailing zeroes at the end of kernel 1146 // cut up to 256 bytes 1147 const uint64_t EndAlign = 256; 1148 const auto Limit = End - (std::min)(EndAlign, End - Start); 1149 while (End > Limit && 1150 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0) 1151 End -= 4; 1152 } 1153 } 1154 1155 outs() << '\n'; 1156 if (!NoLeadingAddr) 1157 outs() << format("%016" PRIx64 " ", 1158 SectionAddr + Start + VMAAdjustment); 1159 1160 StringRef SymbolName = std::get<1>(Symbols[SI]); 1161 if (Demangle) 1162 outs() << demangle(SymbolName) << ":\n"; 1163 else 1164 outs() << SymbolName << ":\n"; 1165 1166 // Don't print raw contents of a virtual section. A virtual section 1167 // doesn't have any contents in the file. 1168 if (Section.isVirtual()) { 1169 outs() << "...\n"; 1170 continue; 1171 } 1172 1173 #ifndef NDEBUG 1174 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); 1175 #else 1176 raw_ostream &DebugOut = nulls(); 1177 #endif 1178 1179 // Some targets (like WebAssembly) have a special prelude at the start 1180 // of each symbol. 1181 DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start), 1182 SectionAddr + Start, DebugOut, CommentStream); 1183 Start += Size; 1184 1185 for (Index = Start; Index < End; Index += Size) { 1186 MCInst Inst; 1187 1188 if (Index + SectionAddr < StartAddress || 1189 Index + SectionAddr > StopAddress) { 1190 // skip byte by byte till StartAddress is reached 1191 Size = 1; 1192 continue; 1193 } 1194 // AArch64 ELF binaries can interleave data and text in the 1195 // same section. We rely on the markers introduced to 1196 // understand what we need to dump. If the data marker is within a 1197 // function, it is denoted as a word/short etc 1198 if (isArmElf(Obj) && std::get<2>(Symbols[SI]) != ELF::STT_OBJECT && 1199 !DisassembleAll) { 1200 uint64_t Stride = 0; 1201 1202 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(), 1203 DataMappingSymsAddr.end(), Index); 1204 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) { 1205 // Switch to data. 1206 while (Index < End) { 1207 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 1208 outs() << "\t"; 1209 if (Index + 4 <= End) { 1210 Stride = 4; 1211 dumpBytes(Bytes.slice(Index, 4), outs()); 1212 outs() << "\t.word\t"; 1213 uint32_t Data = 0; 1214 if (Obj->isLittleEndian()) { 1215 const auto Word = 1216 reinterpret_cast<const support::ulittle32_t *>( 1217 Bytes.data() + Index); 1218 Data = *Word; 1219 } else { 1220 const auto Word = reinterpret_cast<const support::ubig32_t *>( 1221 Bytes.data() + Index); 1222 Data = *Word; 1223 } 1224 outs() << "0x" << format("%08" PRIx32, Data); 1225 } else if (Index + 2 <= End) { 1226 Stride = 2; 1227 dumpBytes(Bytes.slice(Index, 2), outs()); 1228 outs() << "\t\t.short\t"; 1229 uint16_t Data = 0; 1230 if (Obj->isLittleEndian()) { 1231 const auto Short = 1232 reinterpret_cast<const support::ulittle16_t *>( 1233 Bytes.data() + Index); 1234 Data = *Short; 1235 } else { 1236 const auto Short = 1237 reinterpret_cast<const support::ubig16_t *>(Bytes.data() + 1238 Index); 1239 Data = *Short; 1240 } 1241 outs() << "0x" << format("%04" PRIx16, Data); 1242 } else { 1243 Stride = 1; 1244 dumpBytes(Bytes.slice(Index, 1), outs()); 1245 outs() << "\t\t.byte\t"; 1246 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]); 1247 } 1248 Index += Stride; 1249 outs() << "\n"; 1250 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(), 1251 TextMappingSymsAddr.end(), Index); 1252 if (TAI != TextMappingSymsAddr.end() && *TAI == Index) 1253 break; 1254 } 1255 } 1256 } 1257 1258 // If there is a data symbol inside an ELF text section and we are only 1259 // disassembling text (applicable all architectures), 1260 // we are in a situation where we must print the data and not 1261 // disassemble it. 1262 if (Obj->isELF() && std::get<2>(Symbols[SI]) == ELF::STT_OBJECT && 1263 !DisassembleAll && Section.isText()) { 1264 // print out data up to 8 bytes at a time in hex and ascii 1265 uint8_t AsciiData[9] = {'\0'}; 1266 uint8_t Byte; 1267 int NumBytes = 0; 1268 1269 for (Index = Start; Index < End; Index += 1) { 1270 if (((SectionAddr + Index) < StartAddress) || 1271 ((SectionAddr + Index) > StopAddress)) 1272 continue; 1273 if (NumBytes == 0) { 1274 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 1275 outs() << "\t"; 1276 } 1277 Byte = Bytes.slice(Index)[0]; 1278 outs() << format(" %02x", Byte); 1279 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.'; 1280 1281 uint8_t IndentOffset = 0; 1282 NumBytes++; 1283 if (Index == End - 1 || NumBytes > 8) { 1284 // Indent the space for less than 8 bytes data. 1285 // 2 spaces for byte and one for space between bytes 1286 IndentOffset = 3 * (8 - NumBytes); 1287 for (int Excess = NumBytes; Excess < 8; Excess++) 1288 AsciiData[Excess] = '\0'; 1289 NumBytes = 8; 1290 } 1291 if (NumBytes == 8) { 1292 AsciiData[8] = '\0'; 1293 outs() << std::string(IndentOffset, ' ') << " "; 1294 outs() << reinterpret_cast<char *>(AsciiData); 1295 outs() << '\n'; 1296 NumBytes = 0; 1297 } 1298 } 1299 } 1300 if (Index >= End) 1301 break; 1302 1303 // When -z or --disassemble-zeroes are given we always dissasemble them. 1304 // Otherwise we might want to skip zero bytes we see. 1305 if (!DisassembleZeroes) { 1306 uint64_t MaxOffset = End - Index; 1307 // For -reloc: print zero blocks patched by relocations, so that 1308 // relocations can be shown in the dump. 1309 if (RelCur != RelEnd) 1310 MaxOffset = RelCur->getOffset() - Index; 1311 1312 if (size_t N = 1313 countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) { 1314 outs() << "\t\t..." << '\n'; 1315 Index += N; 1316 if (Index >= End) 1317 break; 1318 } 1319 } 1320 1321 // Disassemble a real instruction or a data when disassemble all is 1322 // provided 1323 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), 1324 SectionAddr + Index, DebugOut, 1325 CommentStream); 1326 if (Size == 0) 1327 Size = 1; 1328 1329 PIP.printInst(*IP, Disassembled ? &Inst : nullptr, 1330 Bytes.slice(Index, Size), 1331 {SectionAddr + Index + VMAAdjustment, Section.getIndex()}, 1332 outs(), "", *STI, &SP, &Rels); 1333 outs() << CommentStream.str(); 1334 Comments.clear(); 1335 1336 // Try to resolve the target of a call, tail call, etc. to a specific 1337 // symbol. 1338 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) || 1339 MIA->isConditionalBranch(Inst))) { 1340 uint64_t Target; 1341 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) { 1342 // In a relocatable object, the target's section must reside in 1343 // the same section as the call instruction or it is accessed 1344 // through a relocation. 1345 // 1346 // In a non-relocatable object, the target may be in any section. 1347 // 1348 // N.B. We don't walk the relocations in the relocatable case yet. 1349 auto *TargetSectionSymbols = &Symbols; 1350 if (!Obj->isRelocatableObject()) { 1351 auto SectionAddress = std::upper_bound( 1352 SectionAddresses.begin(), SectionAddresses.end(), Target, 1353 [](uint64_t LHS, 1354 const std::pair<uint64_t, SectionRef> &RHS) { 1355 return LHS < RHS.first; 1356 }); 1357 if (SectionAddress != SectionAddresses.begin()) { 1358 --SectionAddress; 1359 TargetSectionSymbols = &AllSymbols[SectionAddress->second]; 1360 } else { 1361 TargetSectionSymbols = &AbsoluteSymbols; 1362 } 1363 } 1364 1365 // Find the first symbol in the section whose offset is less than 1366 // or equal to the target. If there isn't a section that contains 1367 // the target, find the nearest preceding absolute symbol. 1368 auto TargetSym = std::upper_bound( 1369 TargetSectionSymbols->begin(), TargetSectionSymbols->end(), 1370 Target, [](uint64_t LHS, 1371 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) { 1372 return LHS < std::get<0>(RHS); 1373 }); 1374 if (TargetSym == TargetSectionSymbols->begin()) { 1375 TargetSectionSymbols = &AbsoluteSymbols; 1376 TargetSym = std::upper_bound( 1377 AbsoluteSymbols.begin(), AbsoluteSymbols.end(), 1378 Target, [](uint64_t LHS, 1379 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) { 1380 return LHS < std::get<0>(RHS); 1381 }); 1382 } 1383 if (TargetSym != TargetSectionSymbols->begin()) { 1384 --TargetSym; 1385 uint64_t TargetAddress = std::get<0>(*TargetSym); 1386 StringRef TargetName = std::get<1>(*TargetSym); 1387 outs() << " <" << TargetName; 1388 uint64_t Disp = Target - TargetAddress; 1389 if (Disp) 1390 outs() << "+0x" << Twine::utohexstr(Disp); 1391 outs() << '>'; 1392 } 1393 } 1394 } 1395 outs() << "\n"; 1396 1397 // Hexagon does this in pretty printer 1398 if (Obj->getArch() != Triple::hexagon) { 1399 // Print relocation for instruction. 1400 while (RelCur != RelEnd) { 1401 uint64_t Offset = RelCur->getOffset(); 1402 // If this relocation is hidden, skip it. 1403 if (getHidden(*RelCur) || ((SectionAddr + Offset) < StartAddress)) { 1404 ++RelCur; 1405 continue; 1406 } 1407 1408 // Stop when RelCur's offset is past the current instruction. 1409 if (Offset >= Index + Size) 1410 break; 1411 1412 // When --adjust-vma is used, update the address printed. 1413 if (RelCur->getSymbol() != Obj->symbol_end()) { 1414 Expected<section_iterator> SymSI = 1415 RelCur->getSymbol()->getSection(); 1416 if (SymSI && *SymSI != Obj->section_end() && 1417 (shouldAdjustVA(**SymSI))) 1418 Offset += AdjustVMA; 1419 } 1420 1421 printRelocation(*RelCur, SectionAddr + Offset, 1422 Obj->getBytesInAddress()); 1423 ++RelCur; 1424 } 1425 } 1426 } 1427 } 1428 } 1429 } 1430 1431 static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) { 1432 if (StartAddress > StopAddress) 1433 error("Start address should be less than stop address"); 1434 1435 const Target *TheTarget = getTarget(Obj); 1436 1437 // Package up features to be passed to target/subtarget 1438 SubtargetFeatures Features = Obj->getFeatures(); 1439 if (!MAttrs.empty()) 1440 for (unsigned I = 0; I != MAttrs.size(); ++I) 1441 Features.AddFeature(MAttrs[I]); 1442 1443 std::unique_ptr<const MCRegisterInfo> MRI( 1444 TheTarget->createMCRegInfo(TripleName)); 1445 if (!MRI) 1446 report_error(Obj->getFileName(), 1447 "no register info for target " + TripleName); 1448 1449 // Set up disassembler. 1450 std::unique_ptr<const MCAsmInfo> AsmInfo( 1451 TheTarget->createMCAsmInfo(*MRI, TripleName)); 1452 if (!AsmInfo) 1453 report_error(Obj->getFileName(), 1454 "no assembly info for target " + TripleName); 1455 std::unique_ptr<const MCSubtargetInfo> STI( 1456 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString())); 1457 if (!STI) 1458 report_error(Obj->getFileName(), 1459 "no subtarget info for target " + TripleName); 1460 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); 1461 if (!MII) 1462 report_error(Obj->getFileName(), 1463 "no instruction info for target " + TripleName); 1464 MCObjectFileInfo MOFI; 1465 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI); 1466 // FIXME: for now initialize MCObjectFileInfo with default values 1467 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx); 1468 1469 std::unique_ptr<MCDisassembler> DisAsm( 1470 TheTarget->createMCDisassembler(*STI, Ctx)); 1471 if (!DisAsm) 1472 report_error(Obj->getFileName(), 1473 "no disassembler for target " + TripleName); 1474 1475 std::unique_ptr<const MCInstrAnalysis> MIA( 1476 TheTarget->createMCInstrAnalysis(MII.get())); 1477 1478 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 1479 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 1480 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI)); 1481 if (!IP) 1482 report_error(Obj->getFileName(), 1483 "no instruction printer for target " + TripleName); 1484 IP->setPrintImmHex(PrintImmHex); 1485 1486 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName)); 1487 SourcePrinter SP(Obj, TheTarget->getName()); 1488 1489 for (StringRef Opt : DisassemblerOptions) 1490 if (!IP->applyTargetSpecificCLOption(Opt)) 1491 error("Unrecognized disassembler option: " + Opt); 1492 1493 disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), MIA.get(), IP.get(), 1494 STI.get(), PIP, SP, InlineRelocs); 1495 } 1496 1497 void llvm::printRelocations(const ObjectFile *Obj) { 1498 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : 1499 "%08" PRIx64; 1500 // Regular objdump doesn't print relocations in non-relocatable object 1501 // files. 1502 if (!Obj->isRelocatableObject()) 1503 return; 1504 1505 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1506 if (Section.relocation_begin() == Section.relocation_end()) 1507 continue; 1508 StringRef SecName; 1509 error(Section.getName(SecName)); 1510 outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n"; 1511 for (const RelocationRef &Reloc : Section.relocations()) { 1512 uint64_t Address = Reloc.getOffset(); 1513 SmallString<32> RelocName; 1514 SmallString<32> ValueStr; 1515 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc)) 1516 continue; 1517 Reloc.getTypeName(RelocName); 1518 error(getRelocationValueString(Reloc, ValueStr)); 1519 outs() << format(Fmt.data(), Address) << " " << RelocName << " " 1520 << ValueStr << "\n"; 1521 } 1522 outs() << "\n"; 1523 } 1524 } 1525 1526 void llvm::printDynamicRelocations(const ObjectFile *Obj) { 1527 // For the moment, this option is for ELF only 1528 if (!Obj->isELF()) 1529 return; 1530 1531 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj); 1532 if (!Elf || Elf->getEType() != ELF::ET_DYN) { 1533 error("not a dynamic object"); 1534 return; 1535 } 1536 1537 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections(); 1538 if (DynRelSec.empty()) 1539 return; 1540 1541 outs() << "DYNAMIC RELOCATION RECORDS\n"; 1542 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 1543 for (const SectionRef &Section : DynRelSec) { 1544 if (Section.relocation_begin() == Section.relocation_end()) 1545 continue; 1546 for (const RelocationRef &Reloc : Section.relocations()) { 1547 uint64_t Address = Reloc.getOffset(); 1548 SmallString<32> RelocName; 1549 SmallString<32> ValueStr; 1550 Reloc.getTypeName(RelocName); 1551 error(getRelocationValueString(Reloc, ValueStr)); 1552 outs() << format(Fmt.data(), Address) << " " << RelocName << " " 1553 << ValueStr << "\n"; 1554 } 1555 } 1556 } 1557 1558 // Returns true if we need to show LMA column when dumping section headers. We 1559 // show it only when the platform is ELF and either we have at least one section 1560 // whose VMA and LMA are different and/or when --show-lma flag is used. 1561 static bool shouldDisplayLMA(const ObjectFile *Obj) { 1562 if (!Obj->isELF()) 1563 return false; 1564 for (const SectionRef &S : ToolSectionFilter(*Obj)) 1565 if (S.getAddress() != getELFSectionLMA(S)) 1566 return true; 1567 return ShowLMA; 1568 } 1569 1570 void llvm::printSectionHeaders(const ObjectFile *Obj) { 1571 bool HasLMAColumn = shouldDisplayLMA(Obj); 1572 if (HasLMAColumn) 1573 outs() << "Sections:\n" 1574 "Idx Name Size VMA LMA " 1575 "Type\n"; 1576 else 1577 outs() << "Sections:\n" 1578 "Idx Name Size VMA Type\n"; 1579 1580 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1581 StringRef Name; 1582 error(Section.getName(Name)); 1583 uint64_t VMA = Section.getAddress(); 1584 if (shouldAdjustVA(Section)) 1585 VMA += AdjustVMA; 1586 1587 uint64_t Size = Section.getSize(); 1588 bool Text = Section.isText(); 1589 bool Data = Section.isData(); 1590 bool BSS = Section.isBSS(); 1591 std::string Type = (std::string(Text ? "TEXT " : "") + 1592 (Data ? "DATA " : "") + (BSS ? "BSS" : "")); 1593 1594 if (HasLMAColumn) 1595 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %016" PRIx64 1596 " %s\n", 1597 (unsigned)Section.getIndex(), Name.str().c_str(), Size, 1598 VMA, getELFSectionLMA(Section), Type.c_str()); 1599 else 1600 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", 1601 (unsigned)Section.getIndex(), Name.str().c_str(), Size, 1602 VMA, Type.c_str()); 1603 } 1604 outs() << "\n"; 1605 } 1606 1607 void llvm::printSectionContents(const ObjectFile *Obj) { 1608 std::error_code EC; 1609 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1610 StringRef Name; 1611 StringRef Contents; 1612 error(Section.getName(Name)); 1613 uint64_t BaseAddr = Section.getAddress(); 1614 uint64_t Size = Section.getSize(); 1615 if (!Size) 1616 continue; 1617 1618 outs() << "Contents of section " << Name << ":\n"; 1619 if (Section.isBSS()) { 1620 outs() << format("<skipping contents of bss section at [%04" PRIx64 1621 ", %04" PRIx64 ")>\n", 1622 BaseAddr, BaseAddr + Size); 1623 continue; 1624 } 1625 1626 error(Section.getContents(Contents)); 1627 1628 // Dump out the content as hex and printable ascii characters. 1629 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) { 1630 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr); 1631 // Dump line of hex. 1632 for (std::size_t I = 0; I < 16; ++I) { 1633 if (I != 0 && I % 4 == 0) 1634 outs() << ' '; 1635 if (Addr + I < End) 1636 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true) 1637 << hexdigit(Contents[Addr + I] & 0xF, true); 1638 else 1639 outs() << " "; 1640 } 1641 // Print ascii. 1642 outs() << " "; 1643 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) { 1644 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF)) 1645 outs() << Contents[Addr + I]; 1646 else 1647 outs() << "."; 1648 } 1649 outs() << "\n"; 1650 } 1651 } 1652 } 1653 1654 void llvm::printSymbolTable(const ObjectFile *O, StringRef ArchiveName, 1655 StringRef ArchitectureName) { 1656 outs() << "SYMBOL TABLE:\n"; 1657 1658 if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) { 1659 printCOFFSymbolTable(Coff); 1660 return; 1661 } 1662 1663 for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) { 1664 // Skip printing the special zero symbol when dumping an ELF file. 1665 // This makes the output consistent with the GNU objdump. 1666 if (I == O->symbol_begin() && isa<ELFObjectFileBase>(O)) 1667 continue; 1668 1669 const SymbolRef &Symbol = *I; 1670 Expected<uint64_t> AddressOrError = Symbol.getAddress(); 1671 if (!AddressOrError) 1672 report_error(ArchiveName, O->getFileName(), AddressOrError.takeError(), 1673 ArchitectureName); 1674 uint64_t Address = *AddressOrError; 1675 if ((Address < StartAddress) || (Address > StopAddress)) 1676 continue; 1677 Expected<SymbolRef::Type> TypeOrError = Symbol.getType(); 1678 if (!TypeOrError) 1679 report_error(ArchiveName, O->getFileName(), TypeOrError.takeError(), 1680 ArchitectureName); 1681 SymbolRef::Type Type = *TypeOrError; 1682 uint32_t Flags = Symbol.getFlags(); 1683 Expected<section_iterator> SectionOrErr = Symbol.getSection(); 1684 if (!SectionOrErr) 1685 report_error(ArchiveName, O->getFileName(), SectionOrErr.takeError(), 1686 ArchitectureName); 1687 section_iterator Section = *SectionOrErr; 1688 StringRef Name; 1689 if (Type == SymbolRef::ST_Debug && Section != O->section_end()) { 1690 Section->getName(Name); 1691 } else { 1692 Expected<StringRef> NameOrErr = Symbol.getName(); 1693 if (!NameOrErr) 1694 report_error(ArchiveName, O->getFileName(), NameOrErr.takeError(), 1695 ArchitectureName); 1696 Name = *NameOrErr; 1697 } 1698 1699 bool Global = Flags & SymbolRef::SF_Global; 1700 bool Weak = Flags & SymbolRef::SF_Weak; 1701 bool Absolute = Flags & SymbolRef::SF_Absolute; 1702 bool Common = Flags & SymbolRef::SF_Common; 1703 bool Hidden = Flags & SymbolRef::SF_Hidden; 1704 1705 char GlobLoc = ' '; 1706 if (Type != SymbolRef::ST_Unknown) 1707 GlobLoc = Global ? 'g' : 'l'; 1708 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 1709 ? 'd' : ' '; 1710 char FileFunc = ' '; 1711 if (Type == SymbolRef::ST_File) 1712 FileFunc = 'f'; 1713 else if (Type == SymbolRef::ST_Function) 1714 FileFunc = 'F'; 1715 else if (Type == SymbolRef::ST_Data) 1716 FileFunc = 'O'; 1717 1718 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : 1719 "%08" PRIx64; 1720 1721 outs() << format(Fmt, Address) << " " 1722 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 1723 << (Weak ? 'w' : ' ') // Weak? 1724 << ' ' // Constructor. Not supported yet. 1725 << ' ' // Warning. Not supported yet. 1726 << ' ' // Indirect reference to another symbol. 1727 << Debug // Debugging (d) or dynamic (D) symbol. 1728 << FileFunc // Name of function (F), file (f) or object (O). 1729 << ' '; 1730 if (Absolute) { 1731 outs() << "*ABS*"; 1732 } else if (Common) { 1733 outs() << "*COM*"; 1734 } else if (Section == O->section_end()) { 1735 outs() << "*UND*"; 1736 } else { 1737 if (const MachOObjectFile *MachO = 1738 dyn_cast<const MachOObjectFile>(O)) { 1739 DataRefImpl DR = Section->getRawDataRefImpl(); 1740 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 1741 outs() << SegmentName << ","; 1742 } 1743 StringRef SectionName; 1744 error(Section->getName(SectionName)); 1745 outs() << SectionName; 1746 } 1747 1748 outs() << '\t'; 1749 if (Common || isa<ELFObjectFileBase>(O)) { 1750 uint64_t Val = 1751 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize(); 1752 outs() << format("\t %08" PRIx64 " ", Val); 1753 } 1754 1755 if (Hidden) 1756 outs() << ".hidden "; 1757 1758 if (Demangle) 1759 outs() << demangle(Name) << '\n'; 1760 else 1761 outs() << Name << '\n'; 1762 } 1763 } 1764 1765 static void printUnwindInfo(const ObjectFile *O) { 1766 outs() << "Unwind info:\n\n"; 1767 1768 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O)) 1769 printCOFFUnwindInfo(Coff); 1770 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O)) 1771 printMachOUnwindInfo(MachO); 1772 else 1773 // TODO: Extract DWARF dump tool to objdump. 1774 WithColor::error(errs(), ToolName) 1775 << "This operation is only currently supported " 1776 "for COFF and MachO object files.\n"; 1777 } 1778 1779 void llvm::printExportsTrie(const ObjectFile *o) { 1780 outs() << "Exports trie:\n"; 1781 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1782 printMachOExportsTrie(MachO); 1783 else 1784 WithColor::error(errs(), ToolName) 1785 << "This operation is only currently supported " 1786 "for Mach-O executable files.\n"; 1787 } 1788 1789 void llvm::printRebaseTable(ObjectFile *o) { 1790 outs() << "Rebase table:\n"; 1791 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1792 printMachORebaseTable(MachO); 1793 else 1794 WithColor::error(errs(), ToolName) 1795 << "This operation is only currently supported " 1796 "for Mach-O executable files.\n"; 1797 } 1798 1799 void llvm::printBindTable(ObjectFile *o) { 1800 outs() << "Bind table:\n"; 1801 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1802 printMachOBindTable(MachO); 1803 else 1804 WithColor::error(errs(), ToolName) 1805 << "This operation is only currently supported " 1806 "for Mach-O executable files.\n"; 1807 } 1808 1809 void llvm::printLazyBindTable(ObjectFile *o) { 1810 outs() << "Lazy bind table:\n"; 1811 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1812 printMachOLazyBindTable(MachO); 1813 else 1814 WithColor::error(errs(), ToolName) 1815 << "This operation is only currently supported " 1816 "for Mach-O executable files.\n"; 1817 } 1818 1819 void llvm::printWeakBindTable(ObjectFile *o) { 1820 outs() << "Weak bind table:\n"; 1821 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 1822 printMachOWeakBindTable(MachO); 1823 else 1824 WithColor::error(errs(), ToolName) 1825 << "This operation is only currently supported " 1826 "for Mach-O executable files.\n"; 1827 } 1828 1829 /// Dump the raw contents of the __clangast section so the output can be piped 1830 /// into llvm-bcanalyzer. 1831 void llvm::printRawClangAST(const ObjectFile *Obj) { 1832 if (outs().is_displayed()) { 1833 WithColor::error(errs(), ToolName) 1834 << "The -raw-clang-ast option will dump the raw binary contents of " 1835 "the clang ast section.\n" 1836 "Please redirect the output to a file or another program such as " 1837 "llvm-bcanalyzer.\n"; 1838 return; 1839 } 1840 1841 StringRef ClangASTSectionName("__clangast"); 1842 if (isa<COFFObjectFile>(Obj)) { 1843 ClangASTSectionName = "clangast"; 1844 } 1845 1846 Optional<object::SectionRef> ClangASTSection; 1847 for (auto Sec : ToolSectionFilter(*Obj)) { 1848 StringRef Name; 1849 Sec.getName(Name); 1850 if (Name == ClangASTSectionName) { 1851 ClangASTSection = Sec; 1852 break; 1853 } 1854 } 1855 if (!ClangASTSection) 1856 return; 1857 1858 StringRef ClangASTContents; 1859 error(ClangASTSection.getValue().getContents(ClangASTContents)); 1860 outs().write(ClangASTContents.data(), ClangASTContents.size()); 1861 } 1862 1863 static void printFaultMaps(const ObjectFile *Obj) { 1864 StringRef FaultMapSectionName; 1865 1866 if (isa<ELFObjectFileBase>(Obj)) { 1867 FaultMapSectionName = ".llvm_faultmaps"; 1868 } else if (isa<MachOObjectFile>(Obj)) { 1869 FaultMapSectionName = "__llvm_faultmaps"; 1870 } else { 1871 WithColor::error(errs(), ToolName) 1872 << "This operation is only currently supported " 1873 "for ELF and Mach-O executable files.\n"; 1874 return; 1875 } 1876 1877 Optional<object::SectionRef> FaultMapSection; 1878 1879 for (auto Sec : ToolSectionFilter(*Obj)) { 1880 StringRef Name; 1881 Sec.getName(Name); 1882 if (Name == FaultMapSectionName) { 1883 FaultMapSection = Sec; 1884 break; 1885 } 1886 } 1887 1888 outs() << "FaultMap table:\n"; 1889 1890 if (!FaultMapSection.hasValue()) { 1891 outs() << "<not found>\n"; 1892 return; 1893 } 1894 1895 StringRef FaultMapContents; 1896 error(FaultMapSection.getValue().getContents(FaultMapContents)); 1897 1898 FaultMapParser FMP(FaultMapContents.bytes_begin(), 1899 FaultMapContents.bytes_end()); 1900 1901 outs() << FMP; 1902 } 1903 1904 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) { 1905 if (O->isELF()) { 1906 printELFFileHeader(O); 1907 printELFDynamicSection(O); 1908 printELFSymbolVersionInfo(O); 1909 return; 1910 } 1911 if (O->isCOFF()) 1912 return printCOFFFileHeader(O); 1913 if (O->isWasm()) 1914 return printWasmFileHeader(O); 1915 if (O->isMachO()) { 1916 printMachOFileHeader(O); 1917 if (!OnlyFirst) 1918 printMachOLoadCommands(O); 1919 return; 1920 } 1921 report_error(O->getFileName(), "Invalid/Unsupported object file format"); 1922 } 1923 1924 static void printFileHeaders(const ObjectFile *O) { 1925 if (!O->isELF() && !O->isCOFF()) 1926 report_error(O->getFileName(), "Invalid/Unsupported object file format"); 1927 1928 Triple::ArchType AT = O->getArch(); 1929 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n"; 1930 Expected<uint64_t> StartAddrOrErr = O->getStartAddress(); 1931 if (!StartAddrOrErr) 1932 report_error(O->getFileName(), StartAddrOrErr.takeError()); 1933 1934 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 1935 uint64_t Address = StartAddrOrErr.get(); 1936 outs() << "start address: " 1937 << "0x" << format(Fmt.data(), Address) << "\n\n"; 1938 } 1939 1940 static void printArchiveChild(StringRef Filename, const Archive::Child &C) { 1941 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode(); 1942 if (!ModeOrErr) { 1943 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n"; 1944 consumeError(ModeOrErr.takeError()); 1945 return; 1946 } 1947 sys::fs::perms Mode = ModeOrErr.get(); 1948 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-"); 1949 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-"); 1950 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-"); 1951 outs() << ((Mode & sys::fs::group_read) ? "r" : "-"); 1952 outs() << ((Mode & sys::fs::group_write) ? "w" : "-"); 1953 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-"); 1954 outs() << ((Mode & sys::fs::others_read) ? "r" : "-"); 1955 outs() << ((Mode & sys::fs::others_write) ? "w" : "-"); 1956 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-"); 1957 1958 outs() << " "; 1959 1960 Expected<unsigned> UIDOrErr = C.getUID(); 1961 if (!UIDOrErr) 1962 report_error(Filename, UIDOrErr.takeError()); 1963 unsigned UID = UIDOrErr.get(); 1964 outs() << format("%d/", UID); 1965 1966 Expected<unsigned> GIDOrErr = C.getGID(); 1967 if (!GIDOrErr) 1968 report_error(Filename, GIDOrErr.takeError()); 1969 unsigned GID = GIDOrErr.get(); 1970 outs() << format("%-d ", GID); 1971 1972 Expected<uint64_t> Size = C.getRawSize(); 1973 if (!Size) 1974 report_error(Filename, Size.takeError()); 1975 outs() << format("%6" PRId64, Size.get()) << " "; 1976 1977 StringRef RawLastModified = C.getRawLastModified(); 1978 unsigned Seconds; 1979 if (RawLastModified.getAsInteger(10, Seconds)) 1980 outs() << "(date: \"" << RawLastModified 1981 << "\" contains non-decimal chars) "; 1982 else { 1983 // Since ctime(3) returns a 26 character string of the form: 1984 // "Sun Sep 16 01:03:52 1973\n\0" 1985 // just print 24 characters. 1986 time_t t = Seconds; 1987 outs() << format("%.24s ", ctime(&t)); 1988 } 1989 1990 StringRef Name = ""; 1991 Expected<StringRef> NameOrErr = C.getName(); 1992 if (!NameOrErr) { 1993 consumeError(NameOrErr.takeError()); 1994 Expected<StringRef> RawNameOrErr = C.getRawName(); 1995 if (!RawNameOrErr) 1996 report_error(Filename, NameOrErr.takeError()); 1997 Name = RawNameOrErr.get(); 1998 } else { 1999 Name = NameOrErr.get(); 2000 } 2001 outs() << Name << "\n"; 2002 } 2003 2004 static void dumpObject(ObjectFile *O, const Archive *A = nullptr, 2005 const Archive::Child *C = nullptr) { 2006 // Avoid other output when using a raw option. 2007 if (!RawClangAST) { 2008 outs() << '\n'; 2009 if (A) 2010 outs() << A->getFileName() << "(" << O->getFileName() << ")"; 2011 else 2012 outs() << O->getFileName(); 2013 outs() << ":\tfile format " << O->getFileFormatName() << "\n\n"; 2014 } 2015 2016 StringRef ArchiveName = A ? A->getFileName() : ""; 2017 if (FileHeaders) 2018 printFileHeaders(O); 2019 if (ArchiveHeaders && !MachOOpt && C) 2020 printArchiveChild(ArchiveName, *C); 2021 if (Disassemble) 2022 disassembleObject(O, Relocations); 2023 if (Relocations && !Disassemble) 2024 printRelocations(O); 2025 if (DynamicRelocations) 2026 printDynamicRelocations(O); 2027 if (SectionHeaders) 2028 printSectionHeaders(O); 2029 if (SectionContents) 2030 printSectionContents(O); 2031 if (SymbolTable) 2032 printSymbolTable(O, ArchiveName); 2033 if (UnwindInfo) 2034 printUnwindInfo(O); 2035 if (PrivateHeaders || FirstPrivateHeader) 2036 printPrivateFileHeaders(O, FirstPrivateHeader); 2037 if (ExportsTrie) 2038 printExportsTrie(O); 2039 if (Rebase) 2040 printRebaseTable(O); 2041 if (Bind) 2042 printBindTable(O); 2043 if (LazyBind) 2044 printLazyBindTable(O); 2045 if (WeakBind) 2046 printWeakBindTable(O); 2047 if (RawClangAST) 2048 printRawClangAST(O); 2049 if (PrintFaultMaps) 2050 printFaultMaps(O); 2051 if (DwarfDumpType != DIDT_Null) { 2052 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O); 2053 // Dump the complete DWARF structure. 2054 DIDumpOptions DumpOpts; 2055 DumpOpts.DumpType = DwarfDumpType; 2056 DICtx->dump(outs(), DumpOpts); 2057 } 2058 } 2059 2060 static void dumpObject(const COFFImportFile *I, const Archive *A, 2061 const Archive::Child *C = nullptr) { 2062 StringRef ArchiveName = A ? A->getFileName() : ""; 2063 2064 // Avoid other output when using a raw option. 2065 if (!RawClangAST) 2066 outs() << '\n' 2067 << ArchiveName << "(" << I->getFileName() << ")" 2068 << ":\tfile format COFF-import-file" 2069 << "\n\n"; 2070 2071 if (ArchiveHeaders && !MachOOpt && C) 2072 printArchiveChild(ArchiveName, *C); 2073 if (SymbolTable) 2074 printCOFFSymbolTable(I); 2075 } 2076 2077 /// Dump each object file in \a a; 2078 static void dumpArchive(const Archive *A) { 2079 Error Err = Error::success(); 2080 for (auto &C : A->children(Err)) { 2081 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2082 if (!ChildOrErr) { 2083 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2084 report_error(A->getFileName(), C, std::move(E)); 2085 continue; 2086 } 2087 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 2088 dumpObject(O, A, &C); 2089 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get())) 2090 dumpObject(I, A, &C); 2091 else 2092 report_error(A->getFileName(), object_error::invalid_file_type); 2093 } 2094 if (Err) 2095 report_error(A->getFileName(), std::move(Err)); 2096 } 2097 2098 /// Open file and figure out how to dump it. 2099 static void dumpInput(StringRef file) { 2100 // If we are using the Mach-O specific object file parser, then let it parse 2101 // the file and process the command line options. So the -arch flags can 2102 // be used to select specific slices, etc. 2103 if (MachOOpt) { 2104 parseInputMachO(file); 2105 return; 2106 } 2107 2108 // Attempt to open the binary. 2109 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file); 2110 if (!BinaryOrErr) 2111 report_error(file, BinaryOrErr.takeError()); 2112 Binary &Binary = *BinaryOrErr.get().getBinary(); 2113 2114 if (Archive *A = dyn_cast<Archive>(&Binary)) 2115 dumpArchive(A); 2116 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary)) 2117 dumpObject(O); 2118 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary)) 2119 parseInputMachO(UB); 2120 else 2121 report_error(file, object_error::invalid_file_type); 2122 } 2123 2124 int main(int argc, char **argv) { 2125 InitLLVM X(argc, argv); 2126 2127 // Initialize targets and assembly printers/parsers. 2128 llvm::InitializeAllTargetInfos(); 2129 llvm::InitializeAllTargetMCs(); 2130 llvm::InitializeAllDisassemblers(); 2131 2132 // Register the target printer for --version. 2133 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 2134 2135 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 2136 2137 ToolName = argv[0]; 2138 2139 // Defaults to a.out if no filenames specified. 2140 if (InputFilenames.empty()) 2141 InputFilenames.push_back("a.out"); 2142 2143 if (AllHeaders) 2144 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations = 2145 SectionHeaders = SymbolTable = true; 2146 2147 if (DisassembleAll || PrintSource || PrintLines) 2148 Disassemble = true; 2149 2150 if (!Disassemble 2151 && !Relocations 2152 && !DynamicRelocations 2153 && !SectionHeaders 2154 && !SectionContents 2155 && !SymbolTable 2156 && !UnwindInfo 2157 && !PrivateHeaders 2158 && !FileHeaders 2159 && !FirstPrivateHeader 2160 && !ExportsTrie 2161 && !Rebase 2162 && !Bind 2163 && !LazyBind 2164 && !WeakBind 2165 && !RawClangAST 2166 && !(UniversalHeaders && MachOOpt) 2167 && !ArchiveHeaders 2168 && !(IndirectSymbols && MachOOpt) 2169 && !(DataInCode && MachOOpt) 2170 && !(LinkOptHints && MachOOpt) 2171 && !(InfoPlist && MachOOpt) 2172 && !(DylibsUsed && MachOOpt) 2173 && !(DylibId && MachOOpt) 2174 && !(ObjcMetaData && MachOOpt) 2175 && !(!FilterSections.empty() && MachOOpt) 2176 && !PrintFaultMaps 2177 && DwarfDumpType == DIDT_Null) { 2178 cl::PrintHelpMessage(); 2179 return 2; 2180 } 2181 2182 DisasmFuncsSet.insert(DisassembleFunctions.begin(), 2183 DisassembleFunctions.end()); 2184 2185 llvm::for_each(InputFilenames, dumpInput); 2186 2187 return EXIT_SUCCESS; 2188 } 2189