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