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