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