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