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 uint32_t OffsetPadding = (Obj->getBytesInAddress() > 4 ? 16 : 8); 1649 uint32_t TypePadding = 24; 1650 outs() << left_justify("OFFSET", OffsetPadding) << " " 1651 << left_justify("TYPE", TypePadding) << " " 1652 << "VALUE\n"; 1653 1654 for (SectionRef Section : P.second) { 1655 for (const RelocationRef &Reloc : Section.relocations()) { 1656 uint64_t Address = Reloc.getOffset(); 1657 SmallString<32> RelocName; 1658 SmallString<32> ValueStr; 1659 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc)) 1660 continue; 1661 Reloc.getTypeName(RelocName); 1662 if (Error E = getRelocationValueString(Reloc, ValueStr)) 1663 reportError(std::move(E), Obj->getFileName()); 1664 1665 outs() << format(Fmt.data(), Address) << " " 1666 << left_justify(RelocName, TypePadding) << " " << ValueStr 1667 << "\n"; 1668 } 1669 } 1670 outs() << "\n"; 1671 } 1672 } 1673 1674 void printDynamicRelocations(const ObjectFile *Obj) { 1675 // For the moment, this option is for ELF only 1676 if (!Obj->isELF()) 1677 return; 1678 1679 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj); 1680 if (!Elf || Elf->getEType() != ELF::ET_DYN) { 1681 reportError(Obj->getFileName(), "not a dynamic object"); 1682 return; 1683 } 1684 1685 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections(); 1686 if (DynRelSec.empty()) 1687 return; 1688 1689 outs() << "DYNAMIC RELOCATION RECORDS\n"; 1690 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 1691 for (const SectionRef &Section : DynRelSec) 1692 for (const RelocationRef &Reloc : Section.relocations()) { 1693 uint64_t Address = Reloc.getOffset(); 1694 SmallString<32> RelocName; 1695 SmallString<32> ValueStr; 1696 Reloc.getTypeName(RelocName); 1697 if (Error E = getRelocationValueString(Reloc, ValueStr)) 1698 reportError(std::move(E), Obj->getFileName()); 1699 outs() << format(Fmt.data(), Address) << " " << RelocName << " " 1700 << ValueStr << "\n"; 1701 } 1702 } 1703 1704 // Returns true if we need to show LMA column when dumping section headers. We 1705 // show it only when the platform is ELF and either we have at least one section 1706 // whose VMA and LMA are different and/or when --show-lma flag is used. 1707 static bool shouldDisplayLMA(const ObjectFile *Obj) { 1708 if (!Obj->isELF()) 1709 return false; 1710 for (const SectionRef &S : ToolSectionFilter(*Obj)) 1711 if (S.getAddress() != getELFSectionLMA(S)) 1712 return true; 1713 return ShowLMA; 1714 } 1715 1716 static size_t getMaxSectionNameWidth(const ObjectFile *Obj) { 1717 // Default column width for names is 13 even if no names are that long. 1718 size_t MaxWidth = 13; 1719 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1720 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName()); 1721 MaxWidth = std::max(MaxWidth, Name.size()); 1722 } 1723 return MaxWidth; 1724 } 1725 1726 void printSectionHeaders(const ObjectFile *Obj) { 1727 size_t NameWidth = getMaxSectionNameWidth(Obj); 1728 size_t AddressWidth = 2 * Obj->getBytesInAddress(); 1729 bool HasLMAColumn = shouldDisplayLMA(Obj); 1730 if (HasLMAColumn) 1731 outs() << "Sections:\n" 1732 "Idx " 1733 << left_justify("Name", NameWidth) << " Size " 1734 << left_justify("VMA", AddressWidth) << " " 1735 << left_justify("LMA", AddressWidth) << " Type\n"; 1736 else 1737 outs() << "Sections:\n" 1738 "Idx " 1739 << left_justify("Name", NameWidth) << " Size " 1740 << left_justify("VMA", AddressWidth) << " Type\n"; 1741 1742 uint64_t Idx; 1743 for (const SectionRef &Section : ToolSectionFilter(*Obj, &Idx)) { 1744 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName()); 1745 uint64_t VMA = Section.getAddress(); 1746 if (shouldAdjustVA(Section)) 1747 VMA += AdjustVMA; 1748 1749 uint64_t Size = Section.getSize(); 1750 1751 std::string Type = Section.isText() ? "TEXT" : ""; 1752 if (Section.isData()) 1753 Type += Type.empty() ? "DATA" : " DATA"; 1754 if (Section.isBSS()) 1755 Type += Type.empty() ? "BSS" : " BSS"; 1756 1757 if (HasLMAColumn) 1758 outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth, 1759 Name.str().c_str(), Size) 1760 << format_hex_no_prefix(VMA, AddressWidth) << " " 1761 << format_hex_no_prefix(getELFSectionLMA(Section), AddressWidth) 1762 << " " << Type << "\n"; 1763 else 1764 outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth, 1765 Name.str().c_str(), Size) 1766 << format_hex_no_prefix(VMA, AddressWidth) << " " << Type << "\n"; 1767 } 1768 outs() << "\n"; 1769 } 1770 1771 void printSectionContents(const ObjectFile *Obj) { 1772 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1773 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName()); 1774 uint64_t BaseAddr = Section.getAddress(); 1775 uint64_t Size = Section.getSize(); 1776 if (!Size) 1777 continue; 1778 1779 outs() << "Contents of section " << Name << ":\n"; 1780 if (Section.isBSS()) { 1781 outs() << format("<skipping contents of bss section at [%04" PRIx64 1782 ", %04" PRIx64 ")>\n", 1783 BaseAddr, BaseAddr + Size); 1784 continue; 1785 } 1786 1787 StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName()); 1788 1789 // Dump out the content as hex and printable ascii characters. 1790 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) { 1791 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr); 1792 // Dump line of hex. 1793 for (std::size_t I = 0; I < 16; ++I) { 1794 if (I != 0 && I % 4 == 0) 1795 outs() << ' '; 1796 if (Addr + I < End) 1797 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true) 1798 << hexdigit(Contents[Addr + I] & 0xF, true); 1799 else 1800 outs() << " "; 1801 } 1802 // Print ascii. 1803 outs() << " "; 1804 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) { 1805 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF)) 1806 outs() << Contents[Addr + I]; 1807 else 1808 outs() << "."; 1809 } 1810 outs() << "\n"; 1811 } 1812 } 1813 } 1814 1815 void printSymbolTable(const ObjectFile *O, StringRef ArchiveName, 1816 StringRef ArchitectureName) { 1817 outs() << "SYMBOL TABLE:\n"; 1818 1819 if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) { 1820 printCOFFSymbolTable(Coff); 1821 return; 1822 } 1823 1824 const StringRef FileName = O->getFileName(); 1825 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(O); 1826 for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) { 1827 const SymbolRef &Symbol = *I; 1828 uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName, ArchiveName, 1829 ArchitectureName); 1830 if ((Address < StartAddress) || (Address > StopAddress)) 1831 continue; 1832 SymbolRef::Type Type = unwrapOrError(Symbol.getType(), FileName, 1833 ArchiveName, ArchitectureName); 1834 uint32_t Flags = Symbol.getFlags(); 1835 1836 // Don't ask a Mach-O STAB symbol for its section unless you know that 1837 // STAB symbol's section field refers to a valid section index. Otherwise 1838 // the symbol may error trying to load a section that does not exist. 1839 bool isSTAB = false; 1840 if (MachO) { 1841 DataRefImpl SymDRI = Symbol.getRawDataRefImpl(); 1842 uint8_t NType = (MachO->is64Bit() ? 1843 MachO->getSymbol64TableEntry(SymDRI).n_type: 1844 MachO->getSymbolTableEntry(SymDRI).n_type); 1845 if (NType & MachO::N_STAB) 1846 isSTAB = true; 1847 } 1848 section_iterator Section = isSTAB ? O->section_end() : 1849 unwrapOrError(Symbol.getSection(), FileName, 1850 ArchiveName, ArchitectureName); 1851 1852 StringRef Name; 1853 if (Type == SymbolRef::ST_Debug && Section != O->section_end()) { 1854 if (Expected<StringRef> NameOrErr = Section->getName()) 1855 Name = *NameOrErr; 1856 else 1857 consumeError(NameOrErr.takeError()); 1858 1859 } else { 1860 Name = unwrapOrError(Symbol.getName(), FileName, ArchiveName, 1861 ArchitectureName); 1862 } 1863 1864 bool Global = Flags & SymbolRef::SF_Global; 1865 bool Weak = Flags & SymbolRef::SF_Weak; 1866 bool Absolute = Flags & SymbolRef::SF_Absolute; 1867 bool Common = Flags & SymbolRef::SF_Common; 1868 bool Hidden = Flags & SymbolRef::SF_Hidden; 1869 1870 char GlobLoc = ' '; 1871 if (Type != SymbolRef::ST_Unknown) 1872 GlobLoc = Global ? 'g' : 'l'; 1873 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 1874 ? 'd' : ' '; 1875 char FileFunc = ' '; 1876 if (Type == SymbolRef::ST_File) 1877 FileFunc = 'f'; 1878 else if (Type == SymbolRef::ST_Function) 1879 FileFunc = 'F'; 1880 else if (Type == SymbolRef::ST_Data) 1881 FileFunc = 'O'; 1882 1883 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : 1884 "%08" PRIx64; 1885 1886 outs() << format(Fmt, Address) << " " 1887 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 1888 << (Weak ? 'w' : ' ') // Weak? 1889 << ' ' // Constructor. Not supported yet. 1890 << ' ' // Warning. Not supported yet. 1891 << ' ' // Indirect reference to another symbol. 1892 << Debug // Debugging (d) or dynamic (D) symbol. 1893 << FileFunc // Name of function (F), file (f) or object (O). 1894 << ' '; 1895 if (Absolute) { 1896 outs() << "*ABS*"; 1897 } else if (Common) { 1898 outs() << "*COM*"; 1899 } else if (Section == O->section_end()) { 1900 outs() << "*UND*"; 1901 } else { 1902 if (const MachOObjectFile *MachO = 1903 dyn_cast<const MachOObjectFile>(O)) { 1904 DataRefImpl DR = Section->getRawDataRefImpl(); 1905 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 1906 outs() << SegmentName << ","; 1907 } 1908 StringRef SectionName = 1909 unwrapOrError(Section->getName(), O->getFileName()); 1910 outs() << SectionName; 1911 } 1912 1913 if (Common || isa<ELFObjectFileBase>(O)) { 1914 uint64_t Val = 1915 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize(); 1916 outs() << format("\t%08" PRIx64, Val); 1917 } 1918 1919 if (isa<ELFObjectFileBase>(O)) { 1920 uint8_t Other = ELFSymbolRef(Symbol).getOther(); 1921 switch (Other) { 1922 case ELF::STV_DEFAULT: 1923 break; 1924 case ELF::STV_INTERNAL: 1925 outs() << " .internal"; 1926 break; 1927 case ELF::STV_HIDDEN: 1928 outs() << " .hidden"; 1929 break; 1930 case ELF::STV_PROTECTED: 1931 outs() << " .protected"; 1932 break; 1933 default: 1934 outs() << format(" 0x%02x", Other); 1935 break; 1936 } 1937 } else if (Hidden) { 1938 outs() << " .hidden"; 1939 } 1940 1941 if (Demangle) 1942 outs() << ' ' << demangle(std::string(Name)) << '\n'; 1943 else 1944 outs() << ' ' << Name << '\n'; 1945 } 1946 } 1947 1948 static void printUnwindInfo(const ObjectFile *O) { 1949 outs() << "Unwind info:\n\n"; 1950 1951 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O)) 1952 printCOFFUnwindInfo(Coff); 1953 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O)) 1954 printMachOUnwindInfo(MachO); 1955 else 1956 // TODO: Extract DWARF dump tool to objdump. 1957 WithColor::error(errs(), ToolName) 1958 << "This operation is only currently supported " 1959 "for COFF and MachO object files.\n"; 1960 } 1961 1962 /// Dump the raw contents of the __clangast section so the output can be piped 1963 /// into llvm-bcanalyzer. 1964 void printRawClangAST(const ObjectFile *Obj) { 1965 if (outs().is_displayed()) { 1966 WithColor::error(errs(), ToolName) 1967 << "The -raw-clang-ast option will dump the raw binary contents of " 1968 "the clang ast section.\n" 1969 "Please redirect the output to a file or another program such as " 1970 "llvm-bcanalyzer.\n"; 1971 return; 1972 } 1973 1974 StringRef ClangASTSectionName("__clangast"); 1975 if (isa<COFFObjectFile>(Obj)) { 1976 ClangASTSectionName = "clangast"; 1977 } 1978 1979 Optional<object::SectionRef> ClangASTSection; 1980 for (auto Sec : ToolSectionFilter(*Obj)) { 1981 StringRef Name; 1982 if (Expected<StringRef> NameOrErr = Sec.getName()) 1983 Name = *NameOrErr; 1984 else 1985 consumeError(NameOrErr.takeError()); 1986 1987 if (Name == ClangASTSectionName) { 1988 ClangASTSection = Sec; 1989 break; 1990 } 1991 } 1992 if (!ClangASTSection) 1993 return; 1994 1995 StringRef ClangASTContents = unwrapOrError( 1996 ClangASTSection.getValue().getContents(), Obj->getFileName()); 1997 outs().write(ClangASTContents.data(), ClangASTContents.size()); 1998 } 1999 2000 static void printFaultMaps(const ObjectFile *Obj) { 2001 StringRef FaultMapSectionName; 2002 2003 if (isa<ELFObjectFileBase>(Obj)) { 2004 FaultMapSectionName = ".llvm_faultmaps"; 2005 } else if (isa<MachOObjectFile>(Obj)) { 2006 FaultMapSectionName = "__llvm_faultmaps"; 2007 } else { 2008 WithColor::error(errs(), ToolName) 2009 << "This operation is only currently supported " 2010 "for ELF and Mach-O executable files.\n"; 2011 return; 2012 } 2013 2014 Optional<object::SectionRef> FaultMapSection; 2015 2016 for (auto Sec : ToolSectionFilter(*Obj)) { 2017 StringRef Name; 2018 if (Expected<StringRef> NameOrErr = Sec.getName()) 2019 Name = *NameOrErr; 2020 else 2021 consumeError(NameOrErr.takeError()); 2022 2023 if (Name == FaultMapSectionName) { 2024 FaultMapSection = Sec; 2025 break; 2026 } 2027 } 2028 2029 outs() << "FaultMap table:\n"; 2030 2031 if (!FaultMapSection.hasValue()) { 2032 outs() << "<not found>\n"; 2033 return; 2034 } 2035 2036 StringRef FaultMapContents = 2037 unwrapOrError(FaultMapSection.getValue().getContents(), Obj->getFileName()); 2038 FaultMapParser FMP(FaultMapContents.bytes_begin(), 2039 FaultMapContents.bytes_end()); 2040 2041 outs() << FMP; 2042 } 2043 2044 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) { 2045 if (O->isELF()) { 2046 printELFFileHeader(O); 2047 printELFDynamicSection(O); 2048 printELFSymbolVersionInfo(O); 2049 return; 2050 } 2051 if (O->isCOFF()) 2052 return printCOFFFileHeader(O); 2053 if (O->isWasm()) 2054 return printWasmFileHeader(O); 2055 if (O->isMachO()) { 2056 printMachOFileHeader(O); 2057 if (!OnlyFirst) 2058 printMachOLoadCommands(O); 2059 return; 2060 } 2061 reportError(O->getFileName(), "Invalid/Unsupported object file format"); 2062 } 2063 2064 static void printFileHeaders(const ObjectFile *O) { 2065 if (!O->isELF() && !O->isCOFF()) 2066 reportError(O->getFileName(), "Invalid/Unsupported object file format"); 2067 2068 Triple::ArchType AT = O->getArch(); 2069 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n"; 2070 uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName()); 2071 2072 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 2073 outs() << "start address: " 2074 << "0x" << format(Fmt.data(), Address) << "\n\n"; 2075 } 2076 2077 static void printArchiveChild(StringRef Filename, const Archive::Child &C) { 2078 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode(); 2079 if (!ModeOrErr) { 2080 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n"; 2081 consumeError(ModeOrErr.takeError()); 2082 return; 2083 } 2084 sys::fs::perms Mode = ModeOrErr.get(); 2085 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-"); 2086 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-"); 2087 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-"); 2088 outs() << ((Mode & sys::fs::group_read) ? "r" : "-"); 2089 outs() << ((Mode & sys::fs::group_write) ? "w" : "-"); 2090 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-"); 2091 outs() << ((Mode & sys::fs::others_read) ? "r" : "-"); 2092 outs() << ((Mode & sys::fs::others_write) ? "w" : "-"); 2093 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-"); 2094 2095 outs() << " "; 2096 2097 outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename), 2098 unwrapOrError(C.getGID(), Filename), 2099 unwrapOrError(C.getRawSize(), Filename)); 2100 2101 StringRef RawLastModified = C.getRawLastModified(); 2102 unsigned Seconds; 2103 if (RawLastModified.getAsInteger(10, Seconds)) 2104 outs() << "(date: \"" << RawLastModified 2105 << "\" contains non-decimal chars) "; 2106 else { 2107 // Since ctime(3) returns a 26 character string of the form: 2108 // "Sun Sep 16 01:03:52 1973\n\0" 2109 // just print 24 characters. 2110 time_t t = Seconds; 2111 outs() << format("%.24s ", ctime(&t)); 2112 } 2113 2114 StringRef Name = ""; 2115 Expected<StringRef> NameOrErr = C.getName(); 2116 if (!NameOrErr) { 2117 consumeError(NameOrErr.takeError()); 2118 Name = unwrapOrError(C.getRawName(), Filename); 2119 } else { 2120 Name = NameOrErr.get(); 2121 } 2122 outs() << Name << "\n"; 2123 } 2124 2125 // For ELF only now. 2126 static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) { 2127 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj)) { 2128 if (Elf->getEType() != ELF::ET_REL) 2129 return true; 2130 } 2131 return false; 2132 } 2133 2134 static void checkForInvalidStartStopAddress(ObjectFile *Obj, 2135 uint64_t Start, uint64_t Stop) { 2136 if (!shouldWarnForInvalidStartStopAddress(Obj)) 2137 return; 2138 2139 for (const SectionRef &Section : Obj->sections()) 2140 if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) { 2141 uint64_t BaseAddr = Section.getAddress(); 2142 uint64_t Size = Section.getSize(); 2143 if ((Start < BaseAddr + Size) && Stop > BaseAddr) 2144 return; 2145 } 2146 2147 if (StartAddress.getNumOccurrences() == 0) 2148 reportWarning("no section has address less than 0x" + 2149 Twine::utohexstr(Stop) + " specified by --stop-address", 2150 Obj->getFileName()); 2151 else if (StopAddress.getNumOccurrences() == 0) 2152 reportWarning("no section has address greater than or equal to 0x" + 2153 Twine::utohexstr(Start) + " specified by --start-address", 2154 Obj->getFileName()); 2155 else 2156 reportWarning("no section overlaps the range [0x" + 2157 Twine::utohexstr(Start) + ",0x" + Twine::utohexstr(Stop) + 2158 ") specified by --start-address/--stop-address", 2159 Obj->getFileName()); 2160 } 2161 2162 static void dumpObject(ObjectFile *O, const Archive *A = nullptr, 2163 const Archive::Child *C = nullptr) { 2164 // Avoid other output when using a raw option. 2165 if (!RawClangAST) { 2166 outs() << '\n'; 2167 if (A) 2168 outs() << A->getFileName() << "(" << O->getFileName() << ")"; 2169 else 2170 outs() << O->getFileName(); 2171 outs() << ":\tfile format " << O->getFileFormatName() << "\n\n"; 2172 } 2173 2174 if (StartAddress.getNumOccurrences() || StopAddress.getNumOccurrences()) 2175 checkForInvalidStartStopAddress(O, StartAddress, StopAddress); 2176 2177 // Note: the order here matches GNU objdump for compatability. 2178 StringRef ArchiveName = A ? A->getFileName() : ""; 2179 if (ArchiveHeaders && !MachOOpt && C) 2180 printArchiveChild(ArchiveName, *C); 2181 if (FileHeaders) 2182 printFileHeaders(O); 2183 if (PrivateHeaders || FirstPrivateHeader) 2184 printPrivateFileHeaders(O, FirstPrivateHeader); 2185 if (SectionHeaders) 2186 printSectionHeaders(O); 2187 if (SymbolTable) 2188 printSymbolTable(O, ArchiveName); 2189 if (DwarfDumpType != DIDT_Null) { 2190 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O); 2191 // Dump the complete DWARF structure. 2192 DIDumpOptions DumpOpts; 2193 DumpOpts.DumpType = DwarfDumpType; 2194 DICtx->dump(outs(), DumpOpts); 2195 } 2196 if (Relocations && !Disassemble) 2197 printRelocations(O); 2198 if (DynamicRelocations) 2199 printDynamicRelocations(O); 2200 if (SectionContents) 2201 printSectionContents(O); 2202 if (Disassemble) 2203 disassembleObject(O, Relocations); 2204 if (UnwindInfo) 2205 printUnwindInfo(O); 2206 2207 // Mach-O specific options: 2208 if (ExportsTrie) 2209 printExportsTrie(O); 2210 if (Rebase) 2211 printRebaseTable(O); 2212 if (Bind) 2213 printBindTable(O); 2214 if (LazyBind) 2215 printLazyBindTable(O); 2216 if (WeakBind) 2217 printWeakBindTable(O); 2218 2219 // Other special sections: 2220 if (RawClangAST) 2221 printRawClangAST(O); 2222 if (FaultMapSection) 2223 printFaultMaps(O); 2224 } 2225 2226 static void dumpObject(const COFFImportFile *I, const Archive *A, 2227 const Archive::Child *C = nullptr) { 2228 StringRef ArchiveName = A ? A->getFileName() : ""; 2229 2230 // Avoid other output when using a raw option. 2231 if (!RawClangAST) 2232 outs() << '\n' 2233 << ArchiveName << "(" << I->getFileName() << ")" 2234 << ":\tfile format COFF-import-file" 2235 << "\n\n"; 2236 2237 if (ArchiveHeaders && !MachOOpt && C) 2238 printArchiveChild(ArchiveName, *C); 2239 if (SymbolTable) 2240 printCOFFSymbolTable(I); 2241 } 2242 2243 /// Dump each object file in \a a; 2244 static void dumpArchive(const Archive *A) { 2245 Error Err = Error::success(); 2246 unsigned I = -1; 2247 for (auto &C : A->children(Err)) { 2248 ++I; 2249 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2250 if (!ChildOrErr) { 2251 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2252 reportError(std::move(E), getFileNameForError(C, I), A->getFileName()); 2253 continue; 2254 } 2255 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 2256 dumpObject(O, A, &C); 2257 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get())) 2258 dumpObject(I, A, &C); 2259 else 2260 reportError(errorCodeToError(object_error::invalid_file_type), 2261 A->getFileName()); 2262 } 2263 if (Err) 2264 reportError(std::move(Err), A->getFileName()); 2265 } 2266 2267 /// Open file and figure out how to dump it. 2268 static void dumpInput(StringRef file) { 2269 // If we are using the Mach-O specific object file parser, then let it parse 2270 // the file and process the command line options. So the -arch flags can 2271 // be used to select specific slices, etc. 2272 if (MachOOpt) { 2273 parseInputMachO(file); 2274 return; 2275 } 2276 2277 // Attempt to open the binary. 2278 OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file); 2279 Binary &Binary = *OBinary.getBinary(); 2280 2281 if (Archive *A = dyn_cast<Archive>(&Binary)) 2282 dumpArchive(A); 2283 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary)) 2284 dumpObject(O); 2285 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary)) 2286 parseInputMachO(UB); 2287 else 2288 reportError(errorCodeToError(object_error::invalid_file_type), file); 2289 } 2290 } // namespace llvm 2291 2292 int main(int argc, char **argv) { 2293 using namespace llvm; 2294 InitLLVM X(argc, argv); 2295 const cl::OptionCategory *OptionFilters[] = {&ObjdumpCat, &MachOCat}; 2296 cl::HideUnrelatedOptions(OptionFilters); 2297 2298 // Initialize targets and assembly printers/parsers. 2299 InitializeAllTargetInfos(); 2300 InitializeAllTargetMCs(); 2301 InitializeAllDisassemblers(); 2302 2303 // Register the target printer for --version. 2304 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 2305 2306 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 2307 2308 if (StartAddress >= StopAddress) 2309 reportCmdLineError("start address should be less than stop address"); 2310 2311 ToolName = argv[0]; 2312 2313 // Defaults to a.out if no filenames specified. 2314 if (InputFilenames.empty()) 2315 InputFilenames.push_back("a.out"); 2316 2317 if (AllHeaders) 2318 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations = 2319 SectionHeaders = SymbolTable = true; 2320 2321 if (DisassembleAll || PrintSource || PrintLines || 2322 (!DisassembleFunctions.empty())) 2323 Disassemble = true; 2324 2325 if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null && 2326 !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST && 2327 !Relocations && !SectionHeaders && !SectionContents && !SymbolTable && 2328 !UnwindInfo && !FaultMapSection && 2329 !(MachOOpt && 2330 (Bind || DataInCode || DylibId || DylibsUsed || ExportsTrie || 2331 FirstPrivateHeader || IndirectSymbols || InfoPlist || LazyBind || 2332 LinkOptHints || ObjcMetaData || Rebase || UniversalHeaders || 2333 WeakBind || !FilterSections.empty()))) { 2334 cl::PrintHelpMessage(); 2335 return 2; 2336 } 2337 2338 DisasmFuncsSet.insert(DisassembleFunctions.begin(), 2339 DisassembleFunctions.end()); 2340 2341 llvm::for_each(InputFilenames, dumpInput); 2342 2343 warnOnNoMatchForSections(); 2344 2345 return EXIT_SUCCESS; 2346 } 2347