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