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