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