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