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