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 cl::opt<bool> objdump::SymbolDescription( 135 "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. Sort such sections to be 1249 // before same-addressed non-empty sections so that symbol lookups prefer the 1250 // non-empty section. 1251 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses; 1252 for (SectionRef Sec : Obj->sections()) 1253 SectionAddresses.emplace_back(Sec.getAddress(), Sec); 1254 llvm::stable_sort(SectionAddresses, [](const auto &LHS, const auto &RHS) { 1255 if (LHS.first != RHS.first) 1256 return LHS.first < RHS.first; 1257 return LHS.second.getSize() < RHS.second.getSize(); 1258 }); 1259 1260 // Linked executables (.exe and .dll files) typically don't include a real 1261 // symbol table but they might contain an export table. 1262 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) { 1263 for (const auto &ExportEntry : COFFObj->export_directories()) { 1264 StringRef Name; 1265 if (std::error_code EC = ExportEntry.getSymbolName(Name)) 1266 reportError(errorCodeToError(EC), Obj->getFileName()); 1267 if (Name.empty()) 1268 continue; 1269 1270 uint32_t RVA; 1271 if (std::error_code EC = ExportEntry.getExportRVA(RVA)) 1272 reportError(errorCodeToError(EC), Obj->getFileName()); 1273 1274 uint64_t VA = COFFObj->getImageBase() + RVA; 1275 auto Sec = partition_point( 1276 SectionAddresses, [VA](const std::pair<uint64_t, SectionRef> &O) { 1277 return O.first <= VA; 1278 }); 1279 if (Sec != SectionAddresses.begin()) { 1280 --Sec; 1281 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE); 1282 } else 1283 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE); 1284 } 1285 } 1286 1287 // Sort all the symbols, this allows us to use a simple binary search to find 1288 // Multiple symbols can have the same address. Use a stable sort to stabilize 1289 // the output. 1290 StringSet<> FoundDisasmSymbolSet; 1291 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols) 1292 stable_sort(SecSyms.second); 1293 stable_sort(AbsoluteSymbols); 1294 1295 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1296 if (FilterSections.empty() && !DisassembleAll && 1297 (!Section.isText() || Section.isVirtual())) 1298 continue; 1299 1300 uint64_t SectionAddr = Section.getAddress(); 1301 uint64_t SectSize = Section.getSize(); 1302 if (!SectSize) 1303 continue; 1304 1305 // Get the list of all the symbols in this section. 1306 SectionSymbolsTy &Symbols = AllSymbols[Section]; 1307 std::vector<MappingSymbolPair> MappingSymbols; 1308 if (hasMappingSymbols(Obj)) { 1309 for (const auto &Symb : Symbols) { 1310 uint64_t Address = Symb.Addr; 1311 StringRef Name = Symb.Name; 1312 if (Name.startswith("$d")) 1313 MappingSymbols.emplace_back(Address - SectionAddr, 'd'); 1314 if (Name.startswith("$x")) 1315 MappingSymbols.emplace_back(Address - SectionAddr, 'x'); 1316 if (Name.startswith("$a")) 1317 MappingSymbols.emplace_back(Address - SectionAddr, 'a'); 1318 if (Name.startswith("$t")) 1319 MappingSymbols.emplace_back(Address - SectionAddr, 't'); 1320 } 1321 } 1322 1323 llvm::sort(MappingSymbols); 1324 1325 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1326 // AMDGPU disassembler uses symbolizer for printing labels 1327 std::unique_ptr<MCRelocationInfo> RelInfo( 1328 TheTarget->createMCRelocationInfo(TripleName, Ctx)); 1329 if (RelInfo) { 1330 std::unique_ptr<MCSymbolizer> Symbolizer( 1331 TheTarget->createMCSymbolizer( 1332 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo))); 1333 DisAsm->setSymbolizer(std::move(Symbolizer)); 1334 } 1335 } 1336 1337 StringRef SegmentName = ""; 1338 if (MachO) { 1339 DataRefImpl DR = Section.getRawDataRefImpl(); 1340 SegmentName = MachO->getSectionFinalSegmentName(DR); 1341 } 1342 1343 StringRef SectionName = unwrapOrError(Section.getName(), Obj->getFileName()); 1344 // If the section has no symbol at the start, just insert a dummy one. 1345 if (Symbols.empty() || Symbols[0].Addr != 0) { 1346 Symbols.insert(Symbols.begin(), 1347 createDummySymbolInfo(Obj, SectionAddr, SectionName, 1348 Section.isText() ? ELF::STT_FUNC 1349 : ELF::STT_OBJECT)); 1350 } 1351 1352 SmallString<40> Comments; 1353 raw_svector_ostream CommentStream(Comments); 1354 1355 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef( 1356 unwrapOrError(Section.getContents(), Obj->getFileName())); 1357 1358 uint64_t VMAAdjustment = 0; 1359 if (shouldAdjustVA(Section)) 1360 VMAAdjustment = AdjustVMA; 1361 1362 uint64_t Size; 1363 uint64_t Index; 1364 bool PrintedSection = false; 1365 std::vector<RelocationRef> Rels = RelocMap[Section]; 1366 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin(); 1367 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end(); 1368 // Disassemble symbol by symbol. 1369 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) { 1370 std::string SymbolName = Symbols[SI].Name.str(); 1371 if (Demangle) 1372 SymbolName = demangle(SymbolName); 1373 1374 // Skip if --disassemble-symbols is not empty and the symbol is not in 1375 // the list. 1376 if (!DisasmSymbolSet.empty() && !DisasmSymbolSet.count(SymbolName)) 1377 continue; 1378 1379 uint64_t Start = Symbols[SI].Addr; 1380 if (Start < SectionAddr || StopAddress <= Start) 1381 continue; 1382 else 1383 FoundDisasmSymbolSet.insert(SymbolName); 1384 1385 // The end is the section end, the beginning of the next symbol, or 1386 // --stop-address. 1387 uint64_t End = std::min<uint64_t>(SectionAddr + SectSize, StopAddress); 1388 if (SI + 1 < SE) 1389 End = std::min(End, Symbols[SI + 1].Addr); 1390 if (Start >= End || End <= StartAddress) 1391 continue; 1392 Start -= SectionAddr; 1393 End -= SectionAddr; 1394 1395 if (!PrintedSection) { 1396 PrintedSection = true; 1397 outs() << "\nDisassembly of section "; 1398 if (!SegmentName.empty()) 1399 outs() << SegmentName << ","; 1400 outs() << SectionName << ":\n"; 1401 } 1402 1403 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) { 1404 if (Symbols[SI].Type == ELF::STT_AMDGPU_HSA_KERNEL) { 1405 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes) 1406 Start += 256; 1407 } 1408 if (SI == SE - 1 || 1409 Symbols[SI + 1].Type == ELF::STT_AMDGPU_HSA_KERNEL) { 1410 // cut trailing zeroes at the end of kernel 1411 // cut up to 256 bytes 1412 const uint64_t EndAlign = 256; 1413 const auto Limit = End - (std::min)(EndAlign, End - Start); 1414 while (End > Limit && 1415 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0) 1416 End -= 4; 1417 } 1418 } 1419 1420 outs() << '\n'; 1421 if (!NoLeadingAddr) 1422 outs() << format(Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " ", 1423 SectionAddr + Start + VMAAdjustment); 1424 if (Obj->isXCOFF() && SymbolDescription) { 1425 outs() << getXCOFFSymbolDescription(Symbols[SI], SymbolName) << ":\n"; 1426 } else 1427 outs() << '<' << SymbolName << ">:\n"; 1428 1429 // Don't print raw contents of a virtual section. A virtual section 1430 // doesn't have any contents in the file. 1431 if (Section.isVirtual()) { 1432 outs() << "...\n"; 1433 continue; 1434 } 1435 1436 // Some targets (like WebAssembly) have a special prelude at the start 1437 // of each symbol. 1438 DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start), 1439 SectionAddr + Start, CommentStream); 1440 Start += Size; 1441 1442 Index = Start; 1443 if (SectionAddr < StartAddress) 1444 Index = std::max<uint64_t>(Index, StartAddress - SectionAddr); 1445 1446 // If there is a data/common symbol inside an ELF text section and we are 1447 // only disassembling text (applicable all architectures), we are in a 1448 // situation where we must print the data and not disassemble it. 1449 if (Obj->isELF() && !DisassembleAll && Section.isText()) { 1450 uint8_t SymTy = Symbols[SI].Type; 1451 if (SymTy == ELF::STT_OBJECT || SymTy == ELF::STT_COMMON) { 1452 dumpELFData(SectionAddr, Index, End, Bytes); 1453 Index = End; 1454 } 1455 } 1456 1457 bool CheckARMELFData = hasMappingSymbols(Obj) && 1458 Symbols[SI].Type != ELF::STT_OBJECT && 1459 !DisassembleAll; 1460 while (Index < End) { 1461 // ARM and AArch64 ELF binaries can interleave data and text in the 1462 // same section. We rely on the markers introduced to understand what 1463 // we need to dump. If the data marker is within a function, it is 1464 // denoted as a word/short etc. 1465 if (CheckARMELFData && 1466 getMappingSymbolKind(MappingSymbols, Index) == 'd') { 1467 Index = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes, 1468 MappingSymbols); 1469 continue; 1470 } 1471 1472 // When -z or --disassemble-zeroes are given we always dissasemble 1473 // them. Otherwise we might want to skip zero bytes we see. 1474 if (!DisassembleZeroes) { 1475 uint64_t MaxOffset = End - Index; 1476 // For --reloc: print zero blocks patched by relocations, so that 1477 // relocations can be shown in the dump. 1478 if (RelCur != RelEnd) 1479 MaxOffset = RelCur->getOffset() - Index; 1480 1481 if (size_t N = 1482 countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) { 1483 outs() << "\t\t..." << '\n'; 1484 Index += N; 1485 continue; 1486 } 1487 } 1488 1489 if (SecondarySTI) { 1490 if (getMappingSymbolKind(MappingSymbols, Index) == 'a') { 1491 STI = PrimaryIsThumb ? SecondarySTI : PrimarySTI; 1492 DisAsm = PrimaryIsThumb ? SecondaryDisAsm : PrimaryDisAsm; 1493 } else if (getMappingSymbolKind(MappingSymbols, Index) == 't') { 1494 STI = PrimaryIsThumb ? PrimarySTI : SecondarySTI; 1495 DisAsm = PrimaryIsThumb ? PrimaryDisAsm : SecondaryDisAsm; 1496 } 1497 } 1498 1499 // Disassemble a real instruction or a data when disassemble all is 1500 // provided 1501 MCInst Inst; 1502 bool Disassembled = DisAsm->getInstruction( 1503 Inst, Size, Bytes.slice(Index), SectionAddr + Index, CommentStream); 1504 if (Size == 0) 1505 Size = 1; 1506 1507 PIP.printInst(*IP, Disassembled ? &Inst : nullptr, 1508 Bytes.slice(Index, Size), 1509 {SectionAddr + Index + VMAAdjustment, Section.getIndex()}, 1510 outs(), "", *STI, &SP, Obj->getFileName(), &Rels); 1511 outs() << CommentStream.str(); 1512 Comments.clear(); 1513 1514 // If disassembly has failed, avoid analysing invalid/incomplete 1515 // instruction information. Otherwise, try to resolve the target of a 1516 // call, tail call, etc. to a specific symbol. 1517 if (Disassembled && MIA && 1518 (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) || 1519 MIA->isConditionalBranch(Inst))) { 1520 uint64_t Target; 1521 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) { 1522 // In a relocatable object, the target's section must reside in 1523 // the same section as the call instruction or it is accessed 1524 // through a relocation. 1525 // 1526 // In a non-relocatable object, the target may be in any section. 1527 // In that case, locate the section(s) containing the target address 1528 // and find the symbol in one of those, if possible. 1529 // 1530 // N.B. We don't walk the relocations in the relocatable case yet. 1531 std::vector<const SectionSymbolsTy *> TargetSectionSymbols; 1532 if (!Obj->isRelocatableObject()) { 1533 auto It = llvm::partition_point( 1534 SectionAddresses, 1535 [=](const std::pair<uint64_t, SectionRef> &O) { 1536 return O.first <= Target; 1537 }); 1538 uint64_t TargetSecAddr = 0; 1539 while (It != SectionAddresses.begin()) { 1540 --It; 1541 if (TargetSecAddr == 0) 1542 TargetSecAddr = It->first; 1543 if (It->first != TargetSecAddr) 1544 break; 1545 TargetSectionSymbols.push_back(&AllSymbols[It->second]); 1546 } 1547 } else { 1548 TargetSectionSymbols.push_back(&Symbols); 1549 } 1550 TargetSectionSymbols.push_back(&AbsoluteSymbols); 1551 1552 // Find the last symbol in the first candidate section whose offset 1553 // is less than or equal to the target. If there are no such 1554 // symbols, try in the next section and so on, before finally using 1555 // the nearest preceding absolute symbol (if any), if there are no 1556 // other valid symbols. 1557 const SymbolInfoTy *TargetSym = nullptr; 1558 for (const SectionSymbolsTy *TargetSymbols : TargetSectionSymbols) { 1559 auto It = llvm::partition_point( 1560 *TargetSymbols, 1561 [=](const SymbolInfoTy &O) { return O.Addr <= Target; }); 1562 if (It != TargetSymbols->begin()) { 1563 TargetSym = &*(It - 1); 1564 break; 1565 } 1566 } 1567 1568 if (TargetSym != nullptr) { 1569 uint64_t TargetAddress = TargetSym->Addr; 1570 std::string TargetName = TargetSym->Name.str(); 1571 if (Demangle) 1572 TargetName = demangle(TargetName); 1573 1574 outs() << " <" << TargetName; 1575 uint64_t Disp = Target - TargetAddress; 1576 if (Disp) 1577 outs() << "+0x" << Twine::utohexstr(Disp); 1578 outs() << '>'; 1579 } 1580 } 1581 } 1582 outs() << "\n"; 1583 1584 // Hexagon does this in pretty printer 1585 if (Obj->getArch() != Triple::hexagon) { 1586 // Print relocation for instruction and data. 1587 while (RelCur != RelEnd) { 1588 uint64_t Offset = RelCur->getOffset(); 1589 // If this relocation is hidden, skip it. 1590 if (getHidden(*RelCur) || SectionAddr + Offset < StartAddress) { 1591 ++RelCur; 1592 continue; 1593 } 1594 1595 // Stop when RelCur's offset is past the disassembled 1596 // instruction/data. Note that it's possible the disassembled data 1597 // is not the complete data: we might see the relocation printed in 1598 // the middle of the data, but this matches the binutils objdump 1599 // output. 1600 if (Offset >= Index + Size) 1601 break; 1602 1603 // When --adjust-vma is used, update the address printed. 1604 if (RelCur->getSymbol() != Obj->symbol_end()) { 1605 Expected<section_iterator> SymSI = 1606 RelCur->getSymbol()->getSection(); 1607 if (SymSI && *SymSI != Obj->section_end() && 1608 shouldAdjustVA(**SymSI)) 1609 Offset += AdjustVMA; 1610 } 1611 1612 printRelocation(Obj->getFileName(), *RelCur, SectionAddr + Offset, 1613 Is64Bits); 1614 ++RelCur; 1615 } 1616 } 1617 1618 Index += Size; 1619 } 1620 } 1621 } 1622 StringSet<> MissingDisasmSymbolSet = 1623 set_difference(DisasmSymbolSet, FoundDisasmSymbolSet); 1624 for (StringRef Sym : MissingDisasmSymbolSet.keys()) 1625 reportWarning("failed to disassemble missing symbol " + Sym, FileName); 1626 } 1627 1628 static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) { 1629 const Target *TheTarget = getTarget(Obj); 1630 1631 // Package up features to be passed to target/subtarget 1632 SubtargetFeatures Features = Obj->getFeatures(); 1633 if (!MAttrs.empty()) 1634 for (unsigned I = 0; I != MAttrs.size(); ++I) 1635 Features.AddFeature(MAttrs[I]); 1636 1637 std::unique_ptr<const MCRegisterInfo> MRI( 1638 TheTarget->createMCRegInfo(TripleName)); 1639 if (!MRI) 1640 reportError(Obj->getFileName(), 1641 "no register info for target " + TripleName); 1642 1643 // Set up disassembler. 1644 MCTargetOptions MCOptions; 1645 std::unique_ptr<const MCAsmInfo> AsmInfo( 1646 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions)); 1647 if (!AsmInfo) 1648 reportError(Obj->getFileName(), 1649 "no assembly info for target " + TripleName); 1650 std::unique_ptr<const MCSubtargetInfo> STI( 1651 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString())); 1652 if (!STI) 1653 reportError(Obj->getFileName(), 1654 "no subtarget info for target " + TripleName); 1655 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); 1656 if (!MII) 1657 reportError(Obj->getFileName(), 1658 "no instruction info for target " + TripleName); 1659 MCObjectFileInfo MOFI; 1660 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI); 1661 // FIXME: for now initialize MCObjectFileInfo with default values 1662 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx); 1663 1664 std::unique_ptr<MCDisassembler> DisAsm( 1665 TheTarget->createMCDisassembler(*STI, Ctx)); 1666 if (!DisAsm) 1667 reportError(Obj->getFileName(), "no disassembler for target " + TripleName); 1668 1669 // If we have an ARM object file, we need a second disassembler, because 1670 // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode. 1671 // We use mapping symbols to switch between the two assemblers, where 1672 // appropriate. 1673 std::unique_ptr<MCDisassembler> SecondaryDisAsm; 1674 std::unique_ptr<const MCSubtargetInfo> SecondarySTI; 1675 if (isArmElf(Obj) && !STI->checkFeatures("+mclass")) { 1676 if (STI->checkFeatures("+thumb-mode")) 1677 Features.AddFeature("-thumb-mode"); 1678 else 1679 Features.AddFeature("+thumb-mode"); 1680 SecondarySTI.reset(TheTarget->createMCSubtargetInfo(TripleName, MCPU, 1681 Features.getString())); 1682 SecondaryDisAsm.reset(TheTarget->createMCDisassembler(*SecondarySTI, Ctx)); 1683 } 1684 1685 std::unique_ptr<const MCInstrAnalysis> MIA( 1686 TheTarget->createMCInstrAnalysis(MII.get())); 1687 1688 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 1689 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 1690 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI)); 1691 if (!IP) 1692 reportError(Obj->getFileName(), 1693 "no instruction printer for target " + TripleName); 1694 IP->setPrintImmHex(PrintImmHex); 1695 IP->setPrintBranchImmAsAddress(true); 1696 1697 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName)); 1698 SourcePrinter SP(Obj, TheTarget->getName()); 1699 1700 for (StringRef Opt : DisassemblerOptions) 1701 if (!IP->applyTargetSpecificCLOption(Opt)) 1702 reportError(Obj->getFileName(), 1703 "Unrecognized disassembler option: " + Opt); 1704 1705 disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), SecondaryDisAsm.get(), 1706 MIA.get(), IP.get(), STI.get(), SecondarySTI.get(), PIP, 1707 SP, InlineRelocs); 1708 } 1709 1710 void printRelocations(const ObjectFile *Obj) { 1711 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : 1712 "%08" PRIx64; 1713 // Regular objdump doesn't print relocations in non-relocatable object 1714 // files. 1715 if (!Obj->isRelocatableObject()) 1716 return; 1717 1718 // Build a mapping from relocation target to a vector of relocation 1719 // sections. Usually, there is an only one relocation section for 1720 // each relocated section. 1721 MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec; 1722 uint64_t Ndx; 1723 for (const SectionRef &Section : ToolSectionFilter(*Obj, &Ndx)) { 1724 if (Section.relocation_begin() == Section.relocation_end()) 1725 continue; 1726 Expected<section_iterator> SecOrErr = Section.getRelocatedSection(); 1727 if (!SecOrErr) 1728 reportError(Obj->getFileName(), 1729 "section (" + Twine(Ndx) + 1730 "): unable to get a relocation target: " + 1731 toString(SecOrErr.takeError())); 1732 SecToRelSec[**SecOrErr].push_back(Section); 1733 } 1734 1735 for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) { 1736 StringRef SecName = unwrapOrError(P.first.getName(), Obj->getFileName()); 1737 outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n"; 1738 uint32_t OffsetPadding = (Obj->getBytesInAddress() > 4 ? 16 : 8); 1739 uint32_t TypePadding = 24; 1740 outs() << left_justify("OFFSET", OffsetPadding) << " " 1741 << left_justify("TYPE", TypePadding) << " " 1742 << "VALUE\n"; 1743 1744 for (SectionRef Section : P.second) { 1745 for (const RelocationRef &Reloc : Section.relocations()) { 1746 uint64_t Address = Reloc.getOffset(); 1747 SmallString<32> RelocName; 1748 SmallString<32> ValueStr; 1749 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc)) 1750 continue; 1751 Reloc.getTypeName(RelocName); 1752 if (Error E = getRelocationValueString(Reloc, ValueStr)) 1753 reportError(std::move(E), Obj->getFileName()); 1754 1755 outs() << format(Fmt.data(), Address) << " " 1756 << left_justify(RelocName, TypePadding) << " " << ValueStr 1757 << "\n"; 1758 } 1759 } 1760 outs() << "\n"; 1761 } 1762 } 1763 1764 void printDynamicRelocations(const ObjectFile *Obj) { 1765 // For the moment, this option is for ELF only 1766 if (!Obj->isELF()) 1767 return; 1768 1769 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj); 1770 if (!Elf || Elf->getEType() != ELF::ET_DYN) { 1771 reportError(Obj->getFileName(), "not a dynamic object"); 1772 return; 1773 } 1774 1775 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections(); 1776 if (DynRelSec.empty()) 1777 return; 1778 1779 outs() << "DYNAMIC RELOCATION RECORDS\n"; 1780 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 1781 for (const SectionRef &Section : DynRelSec) 1782 for (const RelocationRef &Reloc : Section.relocations()) { 1783 uint64_t Address = Reloc.getOffset(); 1784 SmallString<32> RelocName; 1785 SmallString<32> ValueStr; 1786 Reloc.getTypeName(RelocName); 1787 if (Error E = getRelocationValueString(Reloc, ValueStr)) 1788 reportError(std::move(E), Obj->getFileName()); 1789 outs() << format(Fmt.data(), Address) << " " << RelocName << " " 1790 << ValueStr << "\n"; 1791 } 1792 } 1793 1794 // Returns true if we need to show LMA column when dumping section headers. We 1795 // show it only when the platform is ELF and either we have at least one section 1796 // whose VMA and LMA are different and/or when --show-lma flag is used. 1797 static bool shouldDisplayLMA(const ObjectFile *Obj) { 1798 if (!Obj->isELF()) 1799 return false; 1800 for (const SectionRef &S : ToolSectionFilter(*Obj)) 1801 if (S.getAddress() != getELFSectionLMA(S)) 1802 return true; 1803 return ShowLMA; 1804 } 1805 1806 static size_t getMaxSectionNameWidth(const ObjectFile *Obj) { 1807 // Default column width for names is 13 even if no names are that long. 1808 size_t MaxWidth = 13; 1809 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1810 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName()); 1811 MaxWidth = std::max(MaxWidth, Name.size()); 1812 } 1813 return MaxWidth; 1814 } 1815 1816 void printSectionHeaders(const ObjectFile *Obj) { 1817 size_t NameWidth = getMaxSectionNameWidth(Obj); 1818 size_t AddressWidth = 2 * Obj->getBytesInAddress(); 1819 bool HasLMAColumn = shouldDisplayLMA(Obj); 1820 if (HasLMAColumn) 1821 outs() << "Sections:\n" 1822 "Idx " 1823 << left_justify("Name", NameWidth) << " Size " 1824 << left_justify("VMA", AddressWidth) << " " 1825 << left_justify("LMA", AddressWidth) << " Type\n"; 1826 else 1827 outs() << "Sections:\n" 1828 "Idx " 1829 << left_justify("Name", NameWidth) << " Size " 1830 << left_justify("VMA", AddressWidth) << " Type\n"; 1831 1832 uint64_t Idx; 1833 for (const SectionRef &Section : ToolSectionFilter(*Obj, &Idx)) { 1834 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName()); 1835 uint64_t VMA = Section.getAddress(); 1836 if (shouldAdjustVA(Section)) 1837 VMA += AdjustVMA; 1838 1839 uint64_t Size = Section.getSize(); 1840 1841 std::string Type = Section.isText() ? "TEXT" : ""; 1842 if (Section.isData()) 1843 Type += Type.empty() ? "DATA" : " DATA"; 1844 if (Section.isBSS()) 1845 Type += Type.empty() ? "BSS" : " BSS"; 1846 1847 if (HasLMAColumn) 1848 outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth, 1849 Name.str().c_str(), Size) 1850 << format_hex_no_prefix(VMA, AddressWidth) << " " 1851 << format_hex_no_prefix(getELFSectionLMA(Section), AddressWidth) 1852 << " " << Type << "\n"; 1853 else 1854 outs() << format("%3" PRIu64 " %-*s %08" PRIx64 " ", Idx, NameWidth, 1855 Name.str().c_str(), Size) 1856 << format_hex_no_prefix(VMA, AddressWidth) << " " << Type << "\n"; 1857 } 1858 outs() << "\n"; 1859 } 1860 1861 void printSectionContents(const ObjectFile *Obj) { 1862 for (const SectionRef &Section : ToolSectionFilter(*Obj)) { 1863 StringRef Name = unwrapOrError(Section.getName(), Obj->getFileName()); 1864 uint64_t BaseAddr = Section.getAddress(); 1865 uint64_t Size = Section.getSize(); 1866 if (!Size) 1867 continue; 1868 1869 outs() << "Contents of section " << Name << ":\n"; 1870 if (Section.isBSS()) { 1871 outs() << format("<skipping contents of bss section at [%04" PRIx64 1872 ", %04" PRIx64 ")>\n", 1873 BaseAddr, BaseAddr + Size); 1874 continue; 1875 } 1876 1877 StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName()); 1878 1879 // Dump out the content as hex and printable ascii characters. 1880 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) { 1881 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr); 1882 // Dump line of hex. 1883 for (std::size_t I = 0; I < 16; ++I) { 1884 if (I != 0 && I % 4 == 0) 1885 outs() << ' '; 1886 if (Addr + I < End) 1887 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true) 1888 << hexdigit(Contents[Addr + I] & 0xF, true); 1889 else 1890 outs() << " "; 1891 } 1892 // Print ascii. 1893 outs() << " "; 1894 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) { 1895 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF)) 1896 outs() << Contents[Addr + I]; 1897 else 1898 outs() << "."; 1899 } 1900 outs() << "\n"; 1901 } 1902 } 1903 } 1904 1905 void printSymbolTable(const ObjectFile *O, StringRef ArchiveName, 1906 StringRef ArchitectureName, bool DumpDynamic) { 1907 if (O->isCOFF() && !DumpDynamic) { 1908 outs() << "SYMBOL TABLE:\n"; 1909 printCOFFSymbolTable(cast<const COFFObjectFile>(O)); 1910 return; 1911 } 1912 1913 const StringRef FileName = O->getFileName(); 1914 1915 if (!DumpDynamic) { 1916 outs() << "SYMBOL TABLE:\n"; 1917 for (auto I = O->symbol_begin(); I != O->symbol_end(); ++I) 1918 printSymbol(O, *I, FileName, ArchiveName, ArchitectureName, DumpDynamic); 1919 return; 1920 } 1921 1922 outs() << "DYNAMIC SYMBOL TABLE:\n"; 1923 if (!O->isELF()) { 1924 reportWarning( 1925 "this operation is not currently supported for this file format", 1926 FileName); 1927 return; 1928 } 1929 1930 const ELFObjectFileBase *ELF = cast<const ELFObjectFileBase>(O); 1931 for (auto I = ELF->getDynamicSymbolIterators().begin(); 1932 I != ELF->getDynamicSymbolIterators().end(); ++I) 1933 printSymbol(O, *I, FileName, ArchiveName, ArchitectureName, DumpDynamic); 1934 } 1935 1936 void printSymbol(const ObjectFile *O, const SymbolRef &Symbol, 1937 StringRef FileName, StringRef ArchiveName, 1938 StringRef ArchitectureName, bool DumpDynamic) { 1939 const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(O); 1940 uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName, ArchiveName, 1941 ArchitectureName); 1942 if ((Address < StartAddress) || (Address > StopAddress)) 1943 return; 1944 SymbolRef::Type Type = 1945 unwrapOrError(Symbol.getType(), FileName, ArchiveName, ArchitectureName); 1946 uint32_t Flags = 1947 unwrapOrError(Symbol.getFlags(), FileName, ArchiveName, ArchitectureName); 1948 1949 // Don't ask a Mach-O STAB symbol for its section unless you know that 1950 // STAB symbol's section field refers to a valid section index. Otherwise 1951 // the symbol may error trying to load a section that does not exist. 1952 bool IsSTAB = false; 1953 if (MachO) { 1954 DataRefImpl SymDRI = Symbol.getRawDataRefImpl(); 1955 uint8_t NType = 1956 (MachO->is64Bit() ? MachO->getSymbol64TableEntry(SymDRI).n_type 1957 : MachO->getSymbolTableEntry(SymDRI).n_type); 1958 if (NType & MachO::N_STAB) 1959 IsSTAB = true; 1960 } 1961 section_iterator Section = IsSTAB 1962 ? O->section_end() 1963 : unwrapOrError(Symbol.getSection(), FileName, 1964 ArchiveName, ArchitectureName); 1965 1966 StringRef Name; 1967 if (Type == SymbolRef::ST_Debug && Section != O->section_end()) { 1968 if (Expected<StringRef> NameOrErr = Section->getName()) 1969 Name = *NameOrErr; 1970 else 1971 consumeError(NameOrErr.takeError()); 1972 1973 } else { 1974 Name = unwrapOrError(Symbol.getName(), FileName, ArchiveName, 1975 ArchitectureName); 1976 } 1977 1978 bool Global = Flags & SymbolRef::SF_Global; 1979 bool Weak = Flags & SymbolRef::SF_Weak; 1980 bool Absolute = Flags & SymbolRef::SF_Absolute; 1981 bool Common = Flags & SymbolRef::SF_Common; 1982 bool Hidden = Flags & SymbolRef::SF_Hidden; 1983 1984 char GlobLoc = ' '; 1985 if ((Section != O->section_end() || Absolute) && !Weak) 1986 GlobLoc = Global ? 'g' : 'l'; 1987 char IFunc = ' '; 1988 if (O->isELF()) { 1989 if (ELFSymbolRef(Symbol).getELFType() == ELF::STT_GNU_IFUNC) 1990 IFunc = 'i'; 1991 if (ELFSymbolRef(Symbol).getBinding() == ELF::STB_GNU_UNIQUE) 1992 GlobLoc = 'u'; 1993 } 1994 1995 char Debug = ' '; 1996 if (DumpDynamic) 1997 Debug = 'D'; 1998 else if (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 1999 Debug = 'd'; 2000 2001 char FileFunc = ' '; 2002 if (Type == SymbolRef::ST_File) 2003 FileFunc = 'f'; 2004 else if (Type == SymbolRef::ST_Function) 2005 FileFunc = 'F'; 2006 else if (Type == SymbolRef::ST_Data) 2007 FileFunc = 'O'; 2008 2009 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 2010 2011 outs() << format(Fmt, Address) << " " 2012 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 2013 << (Weak ? 'w' : ' ') // Weak? 2014 << ' ' // Constructor. Not supported yet. 2015 << ' ' // Warning. Not supported yet. 2016 << IFunc // Indirect reference to another symbol. 2017 << Debug // Debugging (d) or dynamic (D) symbol. 2018 << FileFunc // Name of function (F), file (f) or object (O). 2019 << ' '; 2020 if (Absolute) { 2021 outs() << "*ABS*"; 2022 } else if (Common) { 2023 outs() << "*COM*"; 2024 } else if (Section == O->section_end()) { 2025 outs() << "*UND*"; 2026 } else { 2027 if (MachO) { 2028 DataRefImpl DR = Section->getRawDataRefImpl(); 2029 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 2030 outs() << SegmentName << ","; 2031 } 2032 StringRef SectionName = unwrapOrError(Section->getName(), FileName); 2033 outs() << SectionName; 2034 } 2035 2036 if (Common || O->isELF()) { 2037 uint64_t Val = 2038 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize(); 2039 outs() << '\t' << format(Fmt, Val); 2040 } 2041 2042 if (O->isELF()) { 2043 uint8_t Other = ELFSymbolRef(Symbol).getOther(); 2044 switch (Other) { 2045 case ELF::STV_DEFAULT: 2046 break; 2047 case ELF::STV_INTERNAL: 2048 outs() << " .internal"; 2049 break; 2050 case ELF::STV_HIDDEN: 2051 outs() << " .hidden"; 2052 break; 2053 case ELF::STV_PROTECTED: 2054 outs() << " .protected"; 2055 break; 2056 default: 2057 outs() << format(" 0x%02x", Other); 2058 break; 2059 } 2060 } else if (Hidden) { 2061 outs() << " .hidden"; 2062 } 2063 2064 if (Demangle) 2065 outs() << ' ' << demangle(std::string(Name)) << '\n'; 2066 else 2067 outs() << ' ' << Name << '\n'; 2068 } 2069 2070 static void printUnwindInfo(const ObjectFile *O) { 2071 outs() << "Unwind info:\n\n"; 2072 2073 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O)) 2074 printCOFFUnwindInfo(Coff); 2075 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O)) 2076 printMachOUnwindInfo(MachO); 2077 else 2078 // TODO: Extract DWARF dump tool to objdump. 2079 WithColor::error(errs(), ToolName) 2080 << "This operation is only currently supported " 2081 "for COFF and MachO object files.\n"; 2082 } 2083 2084 /// Dump the raw contents of the __clangast section so the output can be piped 2085 /// into llvm-bcanalyzer. 2086 void printRawClangAST(const ObjectFile *Obj) { 2087 if (outs().is_displayed()) { 2088 WithColor::error(errs(), ToolName) 2089 << "The -raw-clang-ast option will dump the raw binary contents of " 2090 "the clang ast section.\n" 2091 "Please redirect the output to a file or another program such as " 2092 "llvm-bcanalyzer.\n"; 2093 return; 2094 } 2095 2096 StringRef ClangASTSectionName("__clangast"); 2097 if (Obj->isCOFF()) { 2098 ClangASTSectionName = "clangast"; 2099 } 2100 2101 Optional<object::SectionRef> ClangASTSection; 2102 for (auto Sec : ToolSectionFilter(*Obj)) { 2103 StringRef Name; 2104 if (Expected<StringRef> NameOrErr = Sec.getName()) 2105 Name = *NameOrErr; 2106 else 2107 consumeError(NameOrErr.takeError()); 2108 2109 if (Name == ClangASTSectionName) { 2110 ClangASTSection = Sec; 2111 break; 2112 } 2113 } 2114 if (!ClangASTSection) 2115 return; 2116 2117 StringRef ClangASTContents = unwrapOrError( 2118 ClangASTSection.getValue().getContents(), Obj->getFileName()); 2119 outs().write(ClangASTContents.data(), ClangASTContents.size()); 2120 } 2121 2122 static void printFaultMaps(const ObjectFile *Obj) { 2123 StringRef FaultMapSectionName; 2124 2125 if (Obj->isELF()) { 2126 FaultMapSectionName = ".llvm_faultmaps"; 2127 } else if (Obj->isMachO()) { 2128 FaultMapSectionName = "__llvm_faultmaps"; 2129 } else { 2130 WithColor::error(errs(), ToolName) 2131 << "This operation is only currently supported " 2132 "for ELF and Mach-O executable files.\n"; 2133 return; 2134 } 2135 2136 Optional<object::SectionRef> FaultMapSection; 2137 2138 for (auto Sec : ToolSectionFilter(*Obj)) { 2139 StringRef Name; 2140 if (Expected<StringRef> NameOrErr = Sec.getName()) 2141 Name = *NameOrErr; 2142 else 2143 consumeError(NameOrErr.takeError()); 2144 2145 if (Name == FaultMapSectionName) { 2146 FaultMapSection = Sec; 2147 break; 2148 } 2149 } 2150 2151 outs() << "FaultMap table:\n"; 2152 2153 if (!FaultMapSection.hasValue()) { 2154 outs() << "<not found>\n"; 2155 return; 2156 } 2157 2158 StringRef FaultMapContents = 2159 unwrapOrError(FaultMapSection.getValue().getContents(), Obj->getFileName()); 2160 FaultMapParser FMP(FaultMapContents.bytes_begin(), 2161 FaultMapContents.bytes_end()); 2162 2163 outs() << FMP; 2164 } 2165 2166 static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) { 2167 if (O->isELF()) { 2168 printELFFileHeader(O); 2169 printELFDynamicSection(O); 2170 printELFSymbolVersionInfo(O); 2171 return; 2172 } 2173 if (O->isCOFF()) 2174 return printCOFFFileHeader(O); 2175 if (O->isWasm()) 2176 return printWasmFileHeader(O); 2177 if (O->isMachO()) { 2178 printMachOFileHeader(O); 2179 if (!OnlyFirst) 2180 printMachOLoadCommands(O); 2181 return; 2182 } 2183 reportError(O->getFileName(), "Invalid/Unsupported object file format"); 2184 } 2185 2186 static void printFileHeaders(const ObjectFile *O) { 2187 if (!O->isELF() && !O->isCOFF()) 2188 reportError(O->getFileName(), "Invalid/Unsupported object file format"); 2189 2190 Triple::ArchType AT = O->getArch(); 2191 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n"; 2192 uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName()); 2193 2194 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; 2195 outs() << "start address: " 2196 << "0x" << format(Fmt.data(), Address) << "\n\n"; 2197 } 2198 2199 static void printArchiveChild(StringRef Filename, const Archive::Child &C) { 2200 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode(); 2201 if (!ModeOrErr) { 2202 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n"; 2203 consumeError(ModeOrErr.takeError()); 2204 return; 2205 } 2206 sys::fs::perms Mode = ModeOrErr.get(); 2207 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-"); 2208 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-"); 2209 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-"); 2210 outs() << ((Mode & sys::fs::group_read) ? "r" : "-"); 2211 outs() << ((Mode & sys::fs::group_write) ? "w" : "-"); 2212 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-"); 2213 outs() << ((Mode & sys::fs::others_read) ? "r" : "-"); 2214 outs() << ((Mode & sys::fs::others_write) ? "w" : "-"); 2215 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-"); 2216 2217 outs() << " "; 2218 2219 outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename), 2220 unwrapOrError(C.getGID(), Filename), 2221 unwrapOrError(C.getRawSize(), Filename)); 2222 2223 StringRef RawLastModified = C.getRawLastModified(); 2224 unsigned Seconds; 2225 if (RawLastModified.getAsInteger(10, Seconds)) 2226 outs() << "(date: \"" << RawLastModified 2227 << "\" contains non-decimal chars) "; 2228 else { 2229 // Since ctime(3) returns a 26 character string of the form: 2230 // "Sun Sep 16 01:03:52 1973\n\0" 2231 // just print 24 characters. 2232 time_t t = Seconds; 2233 outs() << format("%.24s ", ctime(&t)); 2234 } 2235 2236 StringRef Name = ""; 2237 Expected<StringRef> NameOrErr = C.getName(); 2238 if (!NameOrErr) { 2239 consumeError(NameOrErr.takeError()); 2240 Name = unwrapOrError(C.getRawName(), Filename); 2241 } else { 2242 Name = NameOrErr.get(); 2243 } 2244 outs() << Name << "\n"; 2245 } 2246 2247 // For ELF only now. 2248 static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) { 2249 if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj)) { 2250 if (Elf->getEType() != ELF::ET_REL) 2251 return true; 2252 } 2253 return false; 2254 } 2255 2256 static void checkForInvalidStartStopAddress(ObjectFile *Obj, 2257 uint64_t Start, uint64_t Stop) { 2258 if (!shouldWarnForInvalidStartStopAddress(Obj)) 2259 return; 2260 2261 for (const SectionRef &Section : Obj->sections()) 2262 if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) { 2263 uint64_t BaseAddr = Section.getAddress(); 2264 uint64_t Size = Section.getSize(); 2265 if ((Start < BaseAddr + Size) && Stop > BaseAddr) 2266 return; 2267 } 2268 2269 if (StartAddress.getNumOccurrences() == 0) 2270 reportWarning("no section has address less than 0x" + 2271 Twine::utohexstr(Stop) + " specified by --stop-address", 2272 Obj->getFileName()); 2273 else if (StopAddress.getNumOccurrences() == 0) 2274 reportWarning("no section has address greater than or equal to 0x" + 2275 Twine::utohexstr(Start) + " specified by --start-address", 2276 Obj->getFileName()); 2277 else 2278 reportWarning("no section overlaps the range [0x" + 2279 Twine::utohexstr(Start) + ",0x" + Twine::utohexstr(Stop) + 2280 ") specified by --start-address/--stop-address", 2281 Obj->getFileName()); 2282 } 2283 2284 static void dumpObject(ObjectFile *O, const Archive *A = nullptr, 2285 const Archive::Child *C = nullptr) { 2286 // Avoid other output when using a raw option. 2287 if (!RawClangAST) { 2288 outs() << '\n'; 2289 if (A) 2290 outs() << A->getFileName() << "(" << O->getFileName() << ")"; 2291 else 2292 outs() << O->getFileName(); 2293 outs() << ":\tfile format " << O->getFileFormatName().lower() << "\n\n"; 2294 } 2295 2296 if (StartAddress.getNumOccurrences() || StopAddress.getNumOccurrences()) 2297 checkForInvalidStartStopAddress(O, StartAddress, StopAddress); 2298 2299 // Note: the order here matches GNU objdump for compatability. 2300 StringRef ArchiveName = A ? A->getFileName() : ""; 2301 if (ArchiveHeaders && !MachOOpt && C) 2302 printArchiveChild(ArchiveName, *C); 2303 if (FileHeaders) 2304 printFileHeaders(O); 2305 if (PrivateHeaders || FirstPrivateHeader) 2306 printPrivateFileHeaders(O, FirstPrivateHeader); 2307 if (SectionHeaders) 2308 printSectionHeaders(O); 2309 if (SymbolTable) 2310 printSymbolTable(O, ArchiveName); 2311 if (DynamicSymbolTable) 2312 printSymbolTable(O, ArchiveName, /*ArchitectureName=*/"", 2313 /*DumpDynamic=*/true); 2314 if (DwarfDumpType != DIDT_Null) { 2315 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O); 2316 // Dump the complete DWARF structure. 2317 DIDumpOptions DumpOpts; 2318 DumpOpts.DumpType = DwarfDumpType; 2319 DICtx->dump(outs(), DumpOpts); 2320 } 2321 if (Relocations && !Disassemble) 2322 printRelocations(O); 2323 if (DynamicRelocations) 2324 printDynamicRelocations(O); 2325 if (SectionContents) 2326 printSectionContents(O); 2327 if (Disassemble) 2328 disassembleObject(O, Relocations); 2329 if (UnwindInfo) 2330 printUnwindInfo(O); 2331 2332 // Mach-O specific options: 2333 if (ExportsTrie) 2334 printExportsTrie(O); 2335 if (Rebase) 2336 printRebaseTable(O); 2337 if (Bind) 2338 printBindTable(O); 2339 if (LazyBind) 2340 printLazyBindTable(O); 2341 if (WeakBind) 2342 printWeakBindTable(O); 2343 2344 // Other special sections: 2345 if (RawClangAST) 2346 printRawClangAST(O); 2347 if (FaultMapSection) 2348 printFaultMaps(O); 2349 } 2350 2351 static void dumpObject(const COFFImportFile *I, const Archive *A, 2352 const Archive::Child *C = nullptr) { 2353 StringRef ArchiveName = A ? A->getFileName() : ""; 2354 2355 // Avoid other output when using a raw option. 2356 if (!RawClangAST) 2357 outs() << '\n' 2358 << ArchiveName << "(" << I->getFileName() << ")" 2359 << ":\tfile format COFF-import-file" 2360 << "\n\n"; 2361 2362 if (ArchiveHeaders && !MachOOpt && C) 2363 printArchiveChild(ArchiveName, *C); 2364 if (SymbolTable) 2365 printCOFFSymbolTable(I); 2366 } 2367 2368 /// Dump each object file in \a a; 2369 static void dumpArchive(const Archive *A) { 2370 Error Err = Error::success(); 2371 unsigned I = -1; 2372 for (auto &C : A->children(Err)) { 2373 ++I; 2374 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2375 if (!ChildOrErr) { 2376 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2377 reportError(std::move(E), getFileNameForError(C, I), A->getFileName()); 2378 continue; 2379 } 2380 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 2381 dumpObject(O, A, &C); 2382 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get())) 2383 dumpObject(I, A, &C); 2384 else 2385 reportError(errorCodeToError(object_error::invalid_file_type), 2386 A->getFileName()); 2387 } 2388 if (Err) 2389 reportError(std::move(Err), A->getFileName()); 2390 } 2391 2392 /// Open file and figure out how to dump it. 2393 static void dumpInput(StringRef file) { 2394 // If we are using the Mach-O specific object file parser, then let it parse 2395 // the file and process the command line options. So the -arch flags can 2396 // be used to select specific slices, etc. 2397 if (MachOOpt) { 2398 parseInputMachO(file); 2399 return; 2400 } 2401 2402 // Attempt to open the binary. 2403 OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file); 2404 Binary &Binary = *OBinary.getBinary(); 2405 2406 if (Archive *A = dyn_cast<Archive>(&Binary)) 2407 dumpArchive(A); 2408 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary)) 2409 dumpObject(O); 2410 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary)) 2411 parseInputMachO(UB); 2412 else 2413 reportError(errorCodeToError(object_error::invalid_file_type), file); 2414 } 2415 } // namespace llvm 2416 2417 int main(int argc, char **argv) { 2418 using namespace llvm; 2419 InitLLVM X(argc, argv); 2420 const cl::OptionCategory *OptionFilters[] = {&ObjdumpCat, &MachOCat}; 2421 cl::HideUnrelatedOptions(OptionFilters); 2422 2423 // Initialize targets and assembly printers/parsers. 2424 InitializeAllTargetInfos(); 2425 InitializeAllTargetMCs(); 2426 InitializeAllDisassemblers(); 2427 2428 // Register the target printer for --version. 2429 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 2430 2431 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n", nullptr, 2432 /*EnvVar=*/nullptr, 2433 /*LongOptionsUseDoubleDash=*/true); 2434 2435 if (StartAddress >= StopAddress) 2436 reportCmdLineError("start address should be less than stop address"); 2437 2438 ToolName = argv[0]; 2439 2440 // Defaults to a.out if no filenames specified. 2441 if (InputFilenames.empty()) 2442 InputFilenames.push_back("a.out"); 2443 2444 if (AllHeaders) 2445 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations = 2446 SectionHeaders = SymbolTable = true; 2447 2448 if (DisassembleAll || PrintSource || PrintLines || 2449 !DisassembleSymbols.empty()) 2450 Disassemble = true; 2451 2452 if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null && 2453 !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST && 2454 !Relocations && !SectionHeaders && !SectionContents && !SymbolTable && 2455 !DynamicSymbolTable && !UnwindInfo && !FaultMapSection && 2456 !(MachOOpt && 2457 (Bind || DataInCode || DylibId || DylibsUsed || ExportsTrie || 2458 FirstPrivateHeader || IndirectSymbols || InfoPlist || LazyBind || 2459 LinkOptHints || ObjcMetaData || Rebase || UniversalHeaders || 2460 WeakBind || !FilterSections.empty()))) { 2461 cl::PrintHelpMessage(); 2462 return 2; 2463 } 2464 2465 DisasmSymbolSet.insert(DisassembleSymbols.begin(), DisassembleSymbols.end()); 2466 2467 llvm::for_each(InputFilenames, dumpInput); 2468 2469 warnOnNoMatchForSections(); 2470 2471 return EXIT_SUCCESS; 2472 } 2473