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