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