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