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