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