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