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