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