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