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