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