1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the MachO-specific dumper for llvm-objdump.
12 //===----------------------------------------------------------------------===//
14 #include "llvm-objdump.h"
15 #include "llvm-c/Disassembler.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/DebugInfo/DIContext.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCDisassembler.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCInstPrinter.h"
26 #include "llvm/MC/MCInstrDesc.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/Object/MachO.h"
31 #include "llvm/Object/MachOUniversal.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Endian.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/Support/GraphWriter.h"
39 #include "llvm/Support/MachO.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/TargetSelect.h"
43 #include "llvm/Support/raw_ostream.h"
46 #include <system_error>
53 using namespace object;
57 cl::desc("Print line information from debug info if available"));
59 static cl::opt<std::string> DSYMFile("dsym",
60 cl::desc("Use .dSYM file for debug info"));
62 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
63 cl::desc("Print full leading address"));
66 PrintImmHex("print-imm-hex",
67 cl::desc("Use hex format for immediate values"));
69 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
70 cl::desc("Print Mach-O universal headers "
71 "(requires -macho)"));
74 llvm::ArchiveHeaders("archive-headers",
75 cl::desc("Print archive headers for Mach-O archives "
76 "(requires -macho)"));
79 llvm::IndirectSymbols("indirect-symbols",
80 cl::desc("Print indirect symbol table for Mach-O "
81 "objects (requires -macho)"));
84 llvm::DataInCode("data-in-code",
85 cl::desc("Print the data in code table for Mach-O objects "
86 "(requires -macho)"));
88 static cl::list<std::string>
89 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
93 static std::string ThumbTripleName;
95 static const Target *GetTarget(const MachOObjectFile *MachOObj,
96 const char **McpuDefault,
97 const Target **ThumbTarget) {
98 // Figure out the target triple.
99 if (TripleName.empty()) {
100 llvm::Triple TT("unknown-unknown-unknown");
101 llvm::Triple ThumbTriple = Triple();
102 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
103 TripleName = TT.str();
104 ThumbTripleName = ThumbTriple.str();
107 // Get the target specific parser.
109 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
110 if (TheTarget && ThumbTripleName.empty())
113 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
117 errs() << "llvm-objdump: error: unable to get target for '";
119 errs() << TripleName;
121 errs() << ThumbTripleName;
122 errs() << "', see --version and --triple.\n";
126 struct SymbolSorter {
127 bool operator()(const SymbolRef &A, const SymbolRef &B) {
128 SymbolRef::Type AType, BType;
132 uint64_t AAddr, BAddr;
133 if (AType != SymbolRef::ST_Function)
137 if (BType != SymbolRef::ST_Function)
141 return AAddr < BAddr;
145 // Types for the storted data in code table that is built before disassembly
146 // and the predicate function to sort them.
147 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
148 typedef std::vector<DiceTableEntry> DiceTable;
149 typedef DiceTable::iterator dice_table_iterator;
151 // This is used to search for a data in code table entry for the PC being
152 // disassembled. The j parameter has the PC in j.first. A single data in code
153 // table entry can cover many bytes for each of its Kind's. So if the offset,
154 // aka the i.first value, of the data in code table entry plus its Length
155 // covers the PC being searched for this will return true. If not it will
157 static bool compareDiceTableEntries(const DiceTableEntry &i,
158 const DiceTableEntry &j) {
160 i.second.getLength(Length);
162 return j.first >= i.first && j.first < i.first + Length;
165 static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
166 unsigned short Kind) {
167 uint32_t Value, Size = 1;
171 case MachO::DICE_KIND_DATA:
174 DumpBytes(StringRef(bytes, 4));
175 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
176 outs() << "\t.long " << Value;
178 } else if (Length >= 2) {
180 DumpBytes(StringRef(bytes, 2));
181 Value = bytes[1] << 8 | bytes[0];
182 outs() << "\t.short " << Value;
186 DumpBytes(StringRef(bytes, 2));
188 outs() << "\t.byte " << Value;
191 if (Kind == MachO::DICE_KIND_DATA)
192 outs() << "\t@ KIND_DATA\n";
194 outs() << "\t@ data in code kind = " << Kind << "\n";
196 case MachO::DICE_KIND_JUMP_TABLE8:
198 DumpBytes(StringRef(bytes, 1));
200 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
203 case MachO::DICE_KIND_JUMP_TABLE16:
205 DumpBytes(StringRef(bytes, 2));
206 Value = bytes[1] << 8 | bytes[0];
207 outs() << "\t.short " << format("%5u", Value & 0xffff)
208 << "\t@ KIND_JUMP_TABLE16\n";
211 case MachO::DICE_KIND_JUMP_TABLE32:
212 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
214 DumpBytes(StringRef(bytes, 4));
215 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
216 outs() << "\t.long " << Value;
217 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
218 outs() << "\t@ KIND_JUMP_TABLE32\n";
220 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
227 static void getSectionsAndSymbols(const MachO::mach_header Header,
228 MachOObjectFile *MachOObj,
229 std::vector<SectionRef> &Sections,
230 std::vector<SymbolRef> &Symbols,
231 SmallVectorImpl<uint64_t> &FoundFns,
232 uint64_t &BaseSegmentAddress) {
233 for (const SymbolRef &Symbol : MachOObj->symbols()) {
235 Symbol.getName(SymName);
236 if (!SymName.startswith("ltmp"))
237 Symbols.push_back(Symbol);
240 for (const SectionRef &Section : MachOObj->sections()) {
242 Section.getName(SectName);
243 Sections.push_back(Section);
246 MachOObjectFile::LoadCommandInfo Command =
247 MachOObj->getFirstLoadCommandInfo();
248 bool BaseSegmentAddressSet = false;
249 for (unsigned i = 0;; ++i) {
250 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
251 // We found a function starts segment, parse the addresses for later
253 MachO::linkedit_data_command LLC =
254 MachOObj->getLinkeditDataLoadCommand(Command);
256 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
257 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
258 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
259 StringRef SegName = SLC.segname;
260 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
261 BaseSegmentAddressSet = true;
262 BaseSegmentAddress = SLC.vmaddr;
266 if (i == Header.ncmds - 1)
269 Command = MachOObj->getNextLoadCommandInfo(Command);
273 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
274 uint32_t n, uint32_t count,
275 uint32_t stride, uint64_t addr) {
276 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
277 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
278 if (n > nindirectsyms)
279 outs() << " (entries start past the end of the indirect symbol "
280 "table) (reserved1 field greater than the table size)";
281 else if (n + count > nindirectsyms)
282 outs() << " (entries extends past the end of the indirect symbol "
285 uint32_t cputype = O->getHeader().cputype;
286 if (cputype & MachO::CPU_ARCH_ABI64)
287 outs() << "address index";
289 outs() << "address index";
294 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
295 if (cputype & MachO::CPU_ARCH_ABI64)
296 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
298 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
299 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
300 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
301 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
305 if (indirect_symbol ==
306 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
307 outs() << "LOCAL ABSOLUTE\n";
310 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
311 outs() << "ABSOLUTE\n";
314 outs() << format("%5u ", indirect_symbol);
315 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
316 if (indirect_symbol < Symtab.nsyms) {
317 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
318 SymbolRef Symbol = *Sym;
320 Symbol.getName(SymName);
329 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
330 uint32_t LoadCommandCount = O->getHeader().ncmds;
331 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
332 for (unsigned I = 0;; ++I) {
333 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
334 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
335 for (unsigned J = 0; J < Seg.nsects; ++J) {
336 MachO::section_64 Sec = O->getSection64(Load, J);
337 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
338 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
339 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
340 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
341 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
342 section_type == MachO::S_SYMBOL_STUBS) {
344 if (section_type == MachO::S_SYMBOL_STUBS)
345 stride = Sec.reserved2;
349 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
350 << Sec.sectname << ") "
351 << "(size of stubs in reserved2 field is zero)\n";
354 uint32_t count = Sec.size / stride;
355 outs() << "Indirect symbols for (" << Sec.segname << ","
356 << Sec.sectname << ") " << count << " entries";
357 uint32_t n = Sec.reserved1;
358 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
361 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
362 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
363 for (unsigned J = 0; J < Seg.nsects; ++J) {
364 MachO::section Sec = O->getSection(Load, J);
365 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
366 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
367 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
368 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
369 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
370 section_type == MachO::S_SYMBOL_STUBS) {
372 if (section_type == MachO::S_SYMBOL_STUBS)
373 stride = Sec.reserved2;
377 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
378 << Sec.sectname << ") "
379 << "(size of stubs in reserved2 field is zero)\n";
382 uint32_t count = Sec.size / stride;
383 outs() << "Indirect symbols for (" << Sec.segname << ","
384 << Sec.sectname << ") " << count << " entries";
385 uint32_t n = Sec.reserved1;
386 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
390 if (I == LoadCommandCount - 1)
393 Load = O->getNextLoadCommandInfo(Load);
397 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
398 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
399 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
400 outs() << "Data in code table (" << nentries << " entries)\n";
401 outs() << "offset length kind\n";
402 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
405 DI->getOffset(Offset);
406 outs() << format("0x%08" PRIx32, Offset) << " ";
408 DI->getLength(Length);
409 outs() << format("%6u", Length) << " ";
414 case MachO::DICE_KIND_DATA:
417 case MachO::DICE_KIND_JUMP_TABLE8:
418 outs() << "JUMP_TABLE8";
420 case MachO::DICE_KIND_JUMP_TABLE16:
421 outs() << "JUMP_TABLE16";
423 case MachO::DICE_KIND_JUMP_TABLE32:
424 outs() << "JUMP_TABLE32";
426 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
427 outs() << "ABS_JUMP_TABLE32";
430 outs() << format("0x%04" PRIx32, Kind);
434 outs() << format("0x%04" PRIx32, Kind);
439 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
440 // and if it is and there is a list of architecture flags is specified then
441 // check to make sure this Mach-O file is one of those architectures or all
442 // architectures were specified. If not then an error is generated and this
443 // routine returns false. Else it returns true.
444 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
445 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
446 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
447 bool ArchFound = false;
448 MachO::mach_header H;
449 MachO::mach_header_64 H_64;
451 if (MachO->is64Bit()) {
452 H_64 = MachO->MachOObjectFile::getHeader64();
453 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
455 H = MachO->MachOObjectFile::getHeader();
456 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
459 for (i = 0; i < ArchFlags.size(); ++i) {
460 if (ArchFlags[i] == T.getArchName())
465 errs() << "llvm-objdump: file: " + Filename + " does not contain "
466 << "architecture: " + ArchFlags[i] + "\n";
473 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF);
475 // ProcessMachO() is passed a single opened Mach-O file, which may be an
476 // archive member and or in a slice of a universal file. It prints the
477 // the file name and header info and then processes it according to the
478 // command line options.
479 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
480 StringRef ArchiveMemberName = StringRef(),
481 StringRef ArchitectureName = StringRef()) {
482 // If we are doing some processing here on the Mach-O file print the header
483 // info. And don't print it otherwise like in the case of printing the
484 // UniversalHeaders or ArchiveHeaders.
485 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
486 LazyBind || WeakBind || IndirectSymbols || DataInCode) {
488 if (!ArchiveMemberName.empty())
489 outs() << '(' << ArchiveMemberName << ')';
490 if (!ArchitectureName.empty())
491 outs() << " (architecture " << ArchitectureName << ")";
496 DisassembleMachO(Filename, MachOOF);
498 PrintIndirectSymbols(MachOOF, true);
500 PrintDataInCodeTable(MachOOF, true);
502 PrintRelocations(MachOOF);
504 PrintSectionHeaders(MachOOF);
506 PrintSectionContents(MachOOF);
508 PrintSymbolTable(MachOOF);
510 printMachOUnwindInfo(MachOOF);
512 printMachOFileHeader(MachOOF);
514 printExportsTrie(MachOOF);
516 printRebaseTable(MachOOF);
518 printBindTable(MachOOF);
520 printLazyBindTable(MachOOF);
522 printWeakBindTable(MachOOF);
525 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
526 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
527 outs() << " cputype (" << cputype << ")\n";
528 outs() << " cpusubtype (" << cpusubtype << ")\n";
531 // printCPUType() helps print_fat_headers by printing the cputype and
532 // pusubtype (symbolically for the one's it knows about).
533 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
535 case MachO::CPU_TYPE_I386:
536 switch (cpusubtype) {
537 case MachO::CPU_SUBTYPE_I386_ALL:
538 outs() << " cputype CPU_TYPE_I386\n";
539 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
542 printUnknownCPUType(cputype, cpusubtype);
546 case MachO::CPU_TYPE_X86_64:
547 switch (cpusubtype) {
548 case MachO::CPU_SUBTYPE_X86_64_ALL:
549 outs() << " cputype CPU_TYPE_X86_64\n";
550 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
552 case MachO::CPU_SUBTYPE_X86_64_H:
553 outs() << " cputype CPU_TYPE_X86_64\n";
554 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
557 printUnknownCPUType(cputype, cpusubtype);
561 case MachO::CPU_TYPE_ARM:
562 switch (cpusubtype) {
563 case MachO::CPU_SUBTYPE_ARM_ALL:
564 outs() << " cputype CPU_TYPE_ARM\n";
565 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
567 case MachO::CPU_SUBTYPE_ARM_V4T:
568 outs() << " cputype CPU_TYPE_ARM\n";
569 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
571 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
572 outs() << " cputype CPU_TYPE_ARM\n";
573 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
575 case MachO::CPU_SUBTYPE_ARM_XSCALE:
576 outs() << " cputype CPU_TYPE_ARM\n";
577 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
579 case MachO::CPU_SUBTYPE_ARM_V6:
580 outs() << " cputype CPU_TYPE_ARM\n";
581 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
583 case MachO::CPU_SUBTYPE_ARM_V6M:
584 outs() << " cputype CPU_TYPE_ARM\n";
585 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
587 case MachO::CPU_SUBTYPE_ARM_V7:
588 outs() << " cputype CPU_TYPE_ARM\n";
589 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
591 case MachO::CPU_SUBTYPE_ARM_V7EM:
592 outs() << " cputype CPU_TYPE_ARM\n";
593 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
595 case MachO::CPU_SUBTYPE_ARM_V7K:
596 outs() << " cputype CPU_TYPE_ARM\n";
597 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
599 case MachO::CPU_SUBTYPE_ARM_V7M:
600 outs() << " cputype CPU_TYPE_ARM\n";
601 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
603 case MachO::CPU_SUBTYPE_ARM_V7S:
604 outs() << " cputype CPU_TYPE_ARM\n";
605 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
608 printUnknownCPUType(cputype, cpusubtype);
612 case MachO::CPU_TYPE_ARM64:
613 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
614 case MachO::CPU_SUBTYPE_ARM64_ALL:
615 outs() << " cputype CPU_TYPE_ARM64\n";
616 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
619 printUnknownCPUType(cputype, cpusubtype);
624 printUnknownCPUType(cputype, cpusubtype);
629 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
631 outs() << "Fat headers\n";
633 outs() << "fat_magic FAT_MAGIC\n";
635 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
637 uint32_t nfat_arch = UB->getNumberOfObjects();
638 StringRef Buf = UB->getData();
639 uint64_t size = Buf.size();
640 uint64_t big_size = sizeof(struct MachO::fat_header) +
641 nfat_arch * sizeof(struct MachO::fat_arch);
642 outs() << "nfat_arch " << UB->getNumberOfObjects();
644 outs() << " (malformed, contains zero architecture types)\n";
645 else if (big_size > size)
646 outs() << " (malformed, architectures past end of file)\n";
650 for (uint32_t i = 0; i < nfat_arch; ++i) {
651 MachOUniversalBinary::ObjectForArch OFA(UB, i);
652 uint32_t cputype = OFA.getCPUType();
653 uint32_t cpusubtype = OFA.getCPUSubType();
654 outs() << "architecture ";
655 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
656 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
657 uint32_t other_cputype = other_OFA.getCPUType();
658 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
659 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
660 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
661 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
662 outs() << "(illegal duplicate architecture) ";
667 outs() << OFA.getArchTypeName() << "\n";
668 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
671 outs() << " cputype " << cputype << "\n";
672 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
676 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
677 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
679 outs() << " capabilities "
680 << format("0x%" PRIx32,
681 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
682 outs() << " offset " << OFA.getOffset();
683 if (OFA.getOffset() > size)
684 outs() << " (past end of file)";
685 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
686 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
688 outs() << " size " << OFA.getSize();
689 big_size = OFA.getOffset() + OFA.getSize();
691 outs() << " (past end of file)";
693 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
698 static void printArchiveChild(Archive::Child &C, bool verbose,
701 outs() << C.getChildOffset() << "\t";
702 sys::fs::perms Mode = C.getAccessMode();
704 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
705 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
707 if (Mode & sys::fs::owner_read)
711 if (Mode & sys::fs::owner_write)
715 if (Mode & sys::fs::owner_exe)
719 if (Mode & sys::fs::group_read)
723 if (Mode & sys::fs::group_write)
727 if (Mode & sys::fs::group_exe)
731 if (Mode & sys::fs::others_read)
735 if (Mode & sys::fs::others_write)
739 if (Mode & sys::fs::others_exe)
744 outs() << format("0%o ", Mode);
747 unsigned UID = C.getUID();
748 outs() << format("%3d/", UID);
749 unsigned GID = C.getGID();
750 outs() << format("%-3d ", GID);
751 uint64_t Size = C.getRawSize();
752 outs() << format("%5d ", Size);
754 StringRef RawLastModified = C.getRawLastModified();
757 if (RawLastModified.getAsInteger(10, Seconds))
758 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
760 // Since cime(3) returns a 26 character string of the form:
761 // "Sun Sep 16 01:03:52 1973\n\0"
762 // just print 24 characters.
764 outs() << format("%.24s ", ctime(&t));
767 outs() << RawLastModified << " ";
771 ErrorOr<StringRef> NameOrErr = C.getName();
772 if (NameOrErr.getError()) {
773 StringRef RawName = C.getRawName();
774 outs() << RawName << "\n";
776 StringRef Name = NameOrErr.get();
777 outs() << Name << "\n";
780 StringRef RawName = C.getRawName();
781 outs() << RawName << "\n";
785 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
786 if (A->hasSymbolTable()) {
787 Archive::child_iterator S = A->getSymbolTableChild();
788 Archive::Child C = *S;
789 printArchiveChild(C, verbose, print_offset);
791 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
793 Archive::Child C = *I;
794 printArchiveChild(C, verbose, print_offset);
798 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
799 // -arch flags selecting just those slices as specified by them and also parses
800 // archive files. Then for each individual Mach-O file ProcessMachO() is
801 // called to process the file based on the command line options.
802 void llvm::ParseInputMachO(StringRef Filename) {
803 // Check for -arch all and verifiy the -arch flags are valid.
804 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
805 if (ArchFlags[i] == "all") {
808 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
809 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
810 "'for the -arch option\n";
816 // Attempt to open the binary.
817 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
818 if (std::error_code EC = BinaryOrErr.getError()) {
819 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
822 Binary &Bin = *BinaryOrErr.get().getBinary();
824 if (Archive *A = dyn_cast<Archive>(&Bin)) {
825 outs() << "Archive : " << Filename << "\n";
827 printArchiveHeaders(A, true, false);
828 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
830 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
831 if (ChildOrErr.getError())
833 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
834 if (!checkMachOAndArchFlags(O, Filename))
836 ProcessMachO(Filename, O, O->getFileName());
841 if (UniversalHeaders) {
842 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
843 printMachOUniversalHeaders(UB, true);
845 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
846 // If we have a list of architecture flags specified dump only those.
847 if (!ArchAll && ArchFlags.size() != 0) {
848 // Look for a slice in the universal binary that matches each ArchFlag.
850 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
852 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
853 E = UB->end_objects();
855 if (ArchFlags[i] == I->getArchTypeName()) {
857 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
858 I->getAsObjectFile();
859 std::string ArchitectureName = "";
860 if (ArchFlags.size() > 1)
861 ArchitectureName = I->getArchTypeName();
863 ObjectFile &O = *ObjOrErr.get();
864 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
865 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
866 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
868 std::unique_ptr<Archive> &A = *AOrErr;
869 outs() << "Archive : " << Filename;
870 if (!ArchitectureName.empty())
871 outs() << " (architecture " << ArchitectureName << ")";
874 printArchiveHeaders(A.get(), true, false);
875 for (Archive::child_iterator AI = A->child_begin(),
878 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
879 if (ChildOrErr.getError())
881 if (MachOObjectFile *O =
882 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
883 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
889 errs() << "llvm-objdump: file: " + Filename + " does not contain "
890 << "architecture: " + ArchFlags[i] + "\n";
896 // No architecture flags were specified so if this contains a slice that
897 // matches the host architecture dump only that.
899 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
900 E = UB->end_objects();
902 if (MachOObjectFile::getHostArch().getArchName() ==
903 I->getArchTypeName()) {
904 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
905 std::string ArchiveName;
908 ObjectFile &O = *ObjOrErr.get();
909 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
910 ProcessMachO(Filename, MachOOF);
911 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
913 std::unique_ptr<Archive> &A = *AOrErr;
914 outs() << "Archive : " << Filename << "\n";
916 printArchiveHeaders(A.get(), true, false);
917 for (Archive::child_iterator AI = A->child_begin(),
920 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
921 if (ChildOrErr.getError())
923 if (MachOObjectFile *O =
924 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
925 ProcessMachO(Filename, O, O->getFileName());
932 // Either all architectures have been specified or none have been specified
933 // and this does not contain the host architecture so dump all the slices.
934 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
935 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
936 E = UB->end_objects();
938 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
939 std::string ArchitectureName = "";
941 ArchitectureName = I->getArchTypeName();
943 ObjectFile &Obj = *ObjOrErr.get();
944 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
945 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
946 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
947 std::unique_ptr<Archive> &A = *AOrErr;
948 outs() << "Archive : " << Filename;
949 if (!ArchitectureName.empty())
950 outs() << " (architecture " << ArchitectureName << ")";
953 printArchiveHeaders(A.get(), true, false);
954 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
956 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
957 if (ChildOrErr.getError())
959 if (MachOObjectFile *O =
960 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
961 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
962 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
970 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
971 if (!checkMachOAndArchFlags(O, Filename))
973 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
974 ProcessMachO(Filename, MachOOF);
976 errs() << "llvm-objdump: '" << Filename << "': "
977 << "Object is not a Mach-O file type.\n";
979 errs() << "llvm-objdump: '" << Filename << "': "
980 << "Unrecognized file type.\n";
983 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
984 typedef std::pair<uint64_t, const char *> BindInfoEntry;
985 typedef std::vector<BindInfoEntry> BindTable;
986 typedef BindTable::iterator bind_table_iterator;
988 // The block of info used by the Symbolizer call backs.
989 struct DisassembleInfo {
993 SymbolAddressMap *AddrMap;
994 std::vector<SectionRef> *Sections;
995 const char *class_name;
996 const char *selector_name;
998 char *demangled_name;
1001 BindTable *bindtable;
1004 // GuessSymbolName is passed the address of what might be a symbol and a
1005 // pointer to the DisassembleInfo struct. It returns the name of a symbol
1006 // with that address or nullptr if no symbol is found with that address.
1007 static const char *GuessSymbolName(uint64_t value,
1008 struct DisassembleInfo *info) {
1009 const char *SymbolName = nullptr;
1010 // A DenseMap can't lookup up some values.
1011 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1012 StringRef name = info->AddrMap->lookup(value);
1014 SymbolName = name.data();
1019 // SymbolizerGetOpInfo() is the operand information call back function.
1020 // This is called to get the symbolic information for operand(s) of an
1021 // instruction when it is being done. This routine does this from
1022 // the relocation information, symbol table, etc. That block of information
1023 // is a pointer to the struct DisassembleInfo that was passed when the
1024 // disassembler context was created and passed to back to here when
1025 // called back by the disassembler for instruction operands that could have
1026 // relocation information. The address of the instruction containing operand is
1027 // at the Pc parameter. The immediate value the operand has is passed in
1028 // op_info->Value and is at Offset past the start of the instruction and has a
1029 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1030 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1031 // names and addends of the symbolic expression to add for the operand. The
1032 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1033 // information is returned then this function returns 1 else it returns 0.
1034 int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1035 uint64_t Size, int TagType, void *TagBuf) {
1036 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1037 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1038 uint64_t value = op_info->Value;
1040 // Make sure all fields returned are zero if we don't set them.
1041 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1042 op_info->Value = value;
1044 // If the TagType is not the value 1 which it code knows about or if no
1045 // verbose symbolic information is wanted then just return 0, indicating no
1046 // information is being returned.
1047 if (TagType != 1 || info->verbose == false)
1050 unsigned int Arch = info->O->getArch();
1051 if (Arch == Triple::x86) {
1052 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1054 // First search the section's relocation entries (if any) for an entry
1055 // for this section offset.
1056 uint32_t sect_addr = info->S.getAddress();
1057 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1058 bool reloc_found = false;
1060 MachO::any_relocation_info RE;
1061 bool isExtern = false;
1063 bool r_scattered = false;
1064 uint32_t r_value, pair_r_value, r_type;
1065 for (const RelocationRef &Reloc : info->S.relocations()) {
1066 uint64_t RelocOffset;
1067 Reloc.getOffset(RelocOffset);
1068 if (RelocOffset == sect_offset) {
1069 Rel = Reloc.getRawDataRefImpl();
1070 RE = info->O->getRelocation(Rel);
1071 r_type = info->O->getAnyRelocationType(RE);
1072 r_scattered = info->O->isRelocationScattered(RE);
1074 r_value = info->O->getScatteredRelocationValue(RE);
1075 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1076 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1077 DataRefImpl RelNext = Rel;
1078 info->O->moveRelocationNext(RelNext);
1079 MachO::any_relocation_info RENext;
1080 RENext = info->O->getRelocation(RelNext);
1081 if (info->O->isRelocationScattered(RENext))
1082 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1087 isExtern = info->O->getPlainRelocationExternal(RE);
1089 symbol_iterator RelocSym = Reloc.getSymbol();
1097 if (reloc_found && isExtern) {
1099 Symbol.getName(SymName);
1100 const char *name = SymName.data();
1101 op_info->AddSymbol.Present = 1;
1102 op_info->AddSymbol.Name = name;
1103 // For i386 extern relocation entries the value in the instruction is
1104 // the offset from the symbol, and value is already set in op_info->Value.
1107 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1108 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1109 const char *add = GuessSymbolName(r_value, info);
1110 const char *sub = GuessSymbolName(pair_r_value, info);
1111 uint32_t offset = value - (r_value - pair_r_value);
1112 op_info->AddSymbol.Present = 1;
1114 op_info->AddSymbol.Name = add;
1116 op_info->AddSymbol.Value = r_value;
1117 op_info->SubtractSymbol.Present = 1;
1119 op_info->SubtractSymbol.Name = sub;
1121 op_info->SubtractSymbol.Value = pair_r_value;
1122 op_info->Value = offset;
1126 // Second search the external relocation entries of a fully linked image
1127 // (if any) for an entry that matches this segment offset.
1128 // uint32_t seg_offset = (Pc + Offset);
1130 } else if (Arch == Triple::x86_64) {
1131 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1133 // First search the section's relocation entries (if any) for an entry
1134 // for this section offset.
1135 uint64_t sect_addr = info->S.getAddress();
1136 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1137 bool reloc_found = false;
1139 MachO::any_relocation_info RE;
1140 bool isExtern = false;
1142 for (const RelocationRef &Reloc : info->S.relocations()) {
1143 uint64_t RelocOffset;
1144 Reloc.getOffset(RelocOffset);
1145 if (RelocOffset == sect_offset) {
1146 Rel = Reloc.getRawDataRefImpl();
1147 RE = info->O->getRelocation(Rel);
1148 // NOTE: Scattered relocations don't exist on x86_64.
1149 isExtern = info->O->getPlainRelocationExternal(RE);
1151 symbol_iterator RelocSym = Reloc.getSymbol();
1158 if (reloc_found && isExtern) {
1159 // The Value passed in will be adjusted by the Pc if the instruction
1160 // adds the Pc. But for x86_64 external relocation entries the Value
1161 // is the offset from the external symbol.
1162 if (info->O->getAnyRelocationPCRel(RE))
1163 op_info->Value -= Pc + Offset + Size;
1165 Symbol.getName(SymName);
1166 const char *name = SymName.data();
1167 unsigned Type = info->O->getAnyRelocationType(RE);
1168 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1169 DataRefImpl RelNext = Rel;
1170 info->O->moveRelocationNext(RelNext);
1171 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1172 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1173 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1174 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1175 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1176 op_info->SubtractSymbol.Present = 1;
1177 op_info->SubtractSymbol.Name = name;
1178 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1179 Symbol = *RelocSymNext;
1180 StringRef SymNameNext;
1181 Symbol.getName(SymNameNext);
1182 name = SymNameNext.data();
1185 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1186 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1187 op_info->AddSymbol.Present = 1;
1188 op_info->AddSymbol.Name = name;
1192 // Second search the external relocation entries of a fully linked image
1193 // (if any) for an entry that matches this segment offset.
1194 // uint64_t seg_offset = (Pc + Offset);
1196 } else if (Arch == Triple::arm) {
1197 if (Offset != 0 || (Size != 4 && Size != 2))
1199 // First search the section's relocation entries (if any) for an entry
1200 // for this section offset.
1201 uint32_t sect_addr = info->S.getAddress();
1202 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1203 bool reloc_found = false;
1205 MachO::any_relocation_info RE;
1206 bool isExtern = false;
1208 bool r_scattered = false;
1209 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1210 for (const RelocationRef &Reloc : info->S.relocations()) {
1211 uint64_t RelocOffset;
1212 Reloc.getOffset(RelocOffset);
1213 if (RelocOffset == sect_offset) {
1214 Rel = Reloc.getRawDataRefImpl();
1215 RE = info->O->getRelocation(Rel);
1216 r_length = info->O->getAnyRelocationLength(RE);
1217 r_scattered = info->O->isRelocationScattered(RE);
1219 r_value = info->O->getScatteredRelocationValue(RE);
1220 r_type = info->O->getScatteredRelocationType(RE);
1222 r_type = info->O->getAnyRelocationType(RE);
1223 isExtern = info->O->getPlainRelocationExternal(RE);
1225 symbol_iterator RelocSym = Reloc.getSymbol();
1229 if (r_type == MachO::ARM_RELOC_HALF ||
1230 r_type == MachO::ARM_RELOC_SECTDIFF ||
1231 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1232 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1233 DataRefImpl RelNext = Rel;
1234 info->O->moveRelocationNext(RelNext);
1235 MachO::any_relocation_info RENext;
1236 RENext = info->O->getRelocation(RelNext);
1237 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1238 if (info->O->isRelocationScattered(RENext))
1239 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1245 if (reloc_found && isExtern) {
1247 Symbol.getName(SymName);
1248 const char *name = SymName.data();
1249 op_info->AddSymbol.Present = 1;
1250 op_info->AddSymbol.Name = name;
1253 case MachO::ARM_RELOC_HALF:
1254 if ((r_length & 0x1) == 1) {
1255 op_info->Value = value << 16 | other_half;
1256 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1258 op_info->Value = other_half << 16 | value;
1259 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1267 case MachO::ARM_RELOC_HALF:
1268 if ((r_length & 0x1) == 1) {
1269 op_info->Value = value << 16 | other_half;
1270 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1272 op_info->Value = other_half << 16 | value;
1273 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1282 // If we have a branch that is not an external relocation entry then
1283 // return 0 so the code in tryAddingSymbolicOperand() can use the
1284 // SymbolLookUp call back with the branch target address to look up the
1285 // symbol and possiblity add an annotation for a symbol stub.
1286 if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1287 r_type == MachO::ARM_THUMB_RELOC_BR22))
1290 uint32_t offset = 0;
1292 if (r_type == MachO::ARM_RELOC_HALF ||
1293 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1294 if ((r_length & 0x1) == 1)
1295 value = value << 16 | other_half;
1297 value = other_half << 16 | value;
1299 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1300 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1301 offset = value - r_value;
1306 if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1307 if ((r_length & 0x1) == 1)
1308 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1310 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1311 const char *add = GuessSymbolName(r_value, info);
1312 const char *sub = GuessSymbolName(pair_r_value, info);
1313 int32_t offset = value - (r_value - pair_r_value);
1314 op_info->AddSymbol.Present = 1;
1316 op_info->AddSymbol.Name = add;
1318 op_info->AddSymbol.Value = r_value;
1319 op_info->SubtractSymbol.Present = 1;
1321 op_info->SubtractSymbol.Name = sub;
1323 op_info->SubtractSymbol.Value = pair_r_value;
1324 op_info->Value = offset;
1328 if (reloc_found == false)
1331 op_info->AddSymbol.Present = 1;
1332 op_info->Value = offset;
1334 if (r_type == MachO::ARM_RELOC_HALF) {
1335 if ((r_length & 0x1) == 1)
1336 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1338 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1341 const char *add = GuessSymbolName(value, info);
1342 if (add != nullptr) {
1343 op_info->AddSymbol.Name = add;
1346 op_info->AddSymbol.Value = value;
1348 } else if (Arch == Triple::aarch64) {
1349 if (Offset != 0 || Size != 4)
1351 // First search the section's relocation entries (if any) for an entry
1352 // for this section offset.
1353 uint64_t sect_addr = info->S.getAddress();
1354 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1355 bool reloc_found = false;
1357 MachO::any_relocation_info RE;
1358 bool isExtern = false;
1360 uint32_t r_type = 0;
1361 for (const RelocationRef &Reloc : info->S.relocations()) {
1362 uint64_t RelocOffset;
1363 Reloc.getOffset(RelocOffset);
1364 if (RelocOffset == sect_offset) {
1365 Rel = Reloc.getRawDataRefImpl();
1366 RE = info->O->getRelocation(Rel);
1367 r_type = info->O->getAnyRelocationType(RE);
1368 if (r_type == MachO::ARM64_RELOC_ADDEND) {
1369 DataRefImpl RelNext = Rel;
1370 info->O->moveRelocationNext(RelNext);
1371 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1373 value = info->O->getPlainRelocationSymbolNum(RENext);
1374 op_info->Value = value;
1377 // NOTE: Scattered relocations don't exist on arm64.
1378 isExtern = info->O->getPlainRelocationExternal(RE);
1380 symbol_iterator RelocSym = Reloc.getSymbol();
1387 if (reloc_found && isExtern) {
1389 Symbol.getName(SymName);
1390 const char *name = SymName.data();
1391 op_info->AddSymbol.Present = 1;
1392 op_info->AddSymbol.Name = name;
1395 case MachO::ARM64_RELOC_PAGE21:
1397 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
1399 case MachO::ARM64_RELOC_PAGEOFF12:
1401 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
1403 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
1405 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
1407 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
1409 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
1411 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
1412 /* @tvlppage is not implemented in llvm-mc */
1413 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
1415 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
1416 /* @tvlppageoff is not implemented in llvm-mc */
1417 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
1420 case MachO::ARM64_RELOC_BRANCH26:
1421 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
1432 // GuessCstringPointer is passed the address of what might be a pointer to a
1433 // literal string in a cstring section. If that address is in a cstring section
1434 // it returns a pointer to that string. Else it returns nullptr.
1435 const char *GuessCstringPointer(uint64_t ReferenceValue,
1436 struct DisassembleInfo *info) {
1437 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1438 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1439 for (unsigned I = 0;; ++I) {
1440 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1441 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1442 for (unsigned J = 0; J < Seg.nsects; ++J) {
1443 MachO::section_64 Sec = info->O->getSection64(Load, J);
1444 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1445 if (section_type == MachO::S_CSTRING_LITERALS &&
1446 ReferenceValue >= Sec.addr &&
1447 ReferenceValue < Sec.addr + Sec.size) {
1448 uint64_t sect_offset = ReferenceValue - Sec.addr;
1449 uint64_t object_offset = Sec.offset + sect_offset;
1450 StringRef MachOContents = info->O->getData();
1451 uint64_t object_size = MachOContents.size();
1452 const char *object_addr = (const char *)MachOContents.data();
1453 if (object_offset < object_size) {
1454 const char *name = object_addr + object_offset;
1461 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1462 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
1463 for (unsigned J = 0; J < Seg.nsects; ++J) {
1464 MachO::section Sec = info->O->getSection(Load, J);
1465 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1466 if (section_type == MachO::S_CSTRING_LITERALS &&
1467 ReferenceValue >= Sec.addr &&
1468 ReferenceValue < Sec.addr + Sec.size) {
1469 uint64_t sect_offset = ReferenceValue - Sec.addr;
1470 uint64_t object_offset = Sec.offset + sect_offset;
1471 StringRef MachOContents = info->O->getData();
1472 uint64_t object_size = MachOContents.size();
1473 const char *object_addr = (const char *)MachOContents.data();
1474 if (object_offset < object_size) {
1475 const char *name = object_addr + object_offset;
1483 if (I == LoadCommandCount - 1)
1486 Load = info->O->getNextLoadCommandInfo(Load);
1491 // GuessIndirectSymbol returns the name of the indirect symbol for the
1492 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
1493 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
1494 // symbol name being referenced by the stub or pointer.
1495 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
1496 struct DisassembleInfo *info) {
1497 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1498 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1499 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
1500 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
1501 for (unsigned I = 0;; ++I) {
1502 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1503 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1504 for (unsigned J = 0; J < Seg.nsects; ++J) {
1505 MachO::section_64 Sec = info->O->getSection64(Load, J);
1506 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1507 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1508 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1509 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1510 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
1511 section_type == MachO::S_SYMBOL_STUBS) &&
1512 ReferenceValue >= Sec.addr &&
1513 ReferenceValue < Sec.addr + Sec.size) {
1515 if (section_type == MachO::S_SYMBOL_STUBS)
1516 stride = Sec.reserved2;
1521 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
1522 if (index < Dysymtab.nindirectsyms) {
1523 uint32_t indirect_symbol =
1524 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
1525 if (indirect_symbol < Symtab.nsyms) {
1526 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1527 SymbolRef Symbol = *Sym;
1529 Symbol.getName(SymName);
1530 const char *name = SymName.data();
1536 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1537 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
1538 for (unsigned J = 0; J < Seg.nsects; ++J) {
1539 MachO::section Sec = info->O->getSection(Load, J);
1540 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1541 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1542 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1543 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1544 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
1545 section_type == MachO::S_SYMBOL_STUBS) &&
1546 ReferenceValue >= Sec.addr &&
1547 ReferenceValue < Sec.addr + Sec.size) {
1549 if (section_type == MachO::S_SYMBOL_STUBS)
1550 stride = Sec.reserved2;
1555 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
1556 if (index < Dysymtab.nindirectsyms) {
1557 uint32_t indirect_symbol =
1558 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
1559 if (indirect_symbol < Symtab.nsyms) {
1560 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1561 SymbolRef Symbol = *Sym;
1563 Symbol.getName(SymName);
1564 const char *name = SymName.data();
1571 if (I == LoadCommandCount - 1)
1574 Load = info->O->getNextLoadCommandInfo(Load);
1579 // method_reference() is called passing it the ReferenceName that might be
1580 // a reference it to an Objective-C method call. If so then it allocates and
1581 // assembles a method call string with the values last seen and saved in
1582 // the DisassembleInfo's class_name and selector_name fields. This is saved
1583 // into the method field of the info and any previous string is free'ed.
1584 // Then the class_name field in the info is set to nullptr. The method call
1585 // string is set into ReferenceName and ReferenceType is set to
1586 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
1587 // then both ReferenceType and ReferenceName are left unchanged.
1588 static void method_reference(struct DisassembleInfo *info,
1589 uint64_t *ReferenceType,
1590 const char **ReferenceName) {
1591 unsigned int Arch = info->O->getArch();
1592 if (*ReferenceName != nullptr) {
1593 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
1594 if (info->selector_name != nullptr) {
1595 if (info->method != nullptr)
1597 if (info->class_name != nullptr) {
1598 info->method = (char *)malloc(5 + strlen(info->class_name) +
1599 strlen(info->selector_name));
1600 if (info->method != nullptr) {
1601 strcpy(info->method, "+[");
1602 strcat(info->method, info->class_name);
1603 strcat(info->method, " ");
1604 strcat(info->method, info->selector_name);
1605 strcat(info->method, "]");
1606 *ReferenceName = info->method;
1607 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1610 info->method = (char *)malloc(9 + strlen(info->selector_name));
1611 if (info->method != nullptr) {
1612 if (Arch == Triple::x86_64)
1613 strcpy(info->method, "-[%rdi ");
1614 else if (Arch == Triple::aarch64)
1615 strcpy(info->method, "-[x0 ");
1617 strcpy(info->method, "-[r? ");
1618 strcat(info->method, info->selector_name);
1619 strcat(info->method, "]");
1620 *ReferenceName = info->method;
1621 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1624 info->class_name = nullptr;
1626 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
1627 if (info->selector_name != nullptr) {
1628 if (info->method != nullptr)
1630 info->method = (char *)malloc(17 + strlen(info->selector_name));
1631 if (info->method != nullptr) {
1632 if (Arch == Triple::x86_64)
1633 strcpy(info->method, "-[[%rdi super] ");
1634 else if (Arch == Triple::aarch64)
1635 strcpy(info->method, "-[[x0 super] ");
1637 strcpy(info->method, "-[[r? super] ");
1638 strcat(info->method, info->selector_name);
1639 strcat(info->method, "]");
1640 *ReferenceName = info->method;
1641 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1643 info->class_name = nullptr;
1649 // GuessPointerPointer() is passed the address of what might be a pointer to
1650 // a reference to an Objective-C class, selector, message ref or cfstring.
1651 // If so the value of the pointer is returned and one of the booleans are set
1652 // to true. If not zero is returned and all the booleans are set to false.
1653 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
1654 struct DisassembleInfo *info,
1655 bool &classref, bool &selref, bool &msgref,
1661 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1662 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1663 for (unsigned I = 0;; ++I) {
1664 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1665 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1666 for (unsigned J = 0; J < Seg.nsects; ++J) {
1667 MachO::section_64 Sec = info->O->getSection64(Load, J);
1668 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
1669 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
1670 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
1671 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
1672 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
1673 ReferenceValue >= Sec.addr &&
1674 ReferenceValue < Sec.addr + Sec.size) {
1675 uint64_t sect_offset = ReferenceValue - Sec.addr;
1676 uint64_t object_offset = Sec.offset + sect_offset;
1677 StringRef MachOContents = info->O->getData();
1678 uint64_t object_size = MachOContents.size();
1679 const char *object_addr = (const char *)MachOContents.data();
1680 if (object_offset < object_size) {
1681 uint64_t pointer_value;
1682 memcpy(&pointer_value, object_addr + object_offset,
1684 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1685 sys::swapByteOrder(pointer_value);
1686 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
1688 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
1689 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
1691 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
1692 ReferenceValue + 8 < Sec.addr + Sec.size) {
1694 memcpy(&pointer_value, object_addr + object_offset + 8,
1696 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1697 sys::swapByteOrder(pointer_value);
1698 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
1700 return pointer_value;
1707 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
1708 if (I == LoadCommandCount - 1)
1711 Load = info->O->getNextLoadCommandInfo(Load);
1716 // get_pointer_64 returns a pointer to the bytes in the object file at the
1717 // Address from a section in the Mach-O file. And indirectly returns the
1718 // offset into the section, number of bytes left in the section past the offset
1719 // and which section is was being referenced. If the Address is not in a
1720 // section nullptr is returned.
1721 const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left,
1722 SectionRef &S, DisassembleInfo *info) {
1726 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
1727 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
1728 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
1729 if (Address >= SectAddress && Address < SectAddress + SectSize) {
1730 S = (*(info->Sections))[SectIdx];
1731 offset = Address - SectAddress;
1732 left = SectSize - offset;
1733 StringRef SectContents;
1734 ((*(info->Sections))[SectIdx]).getContents(SectContents);
1735 return SectContents.data() + offset;
1741 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
1742 // the symbol indirectly through n_value. Based on the relocation information
1743 // for the specified section offset in the specified section reference.
1744 const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
1745 DisassembleInfo *info, uint64_t &n_value) {
1747 if (info->verbose == false)
1750 // See if there is an external relocation entry at the sect_offset.
1751 bool reloc_found = false;
1753 MachO::any_relocation_info RE;
1754 bool isExtern = false;
1756 for (const RelocationRef &Reloc : S.relocations()) {
1757 uint64_t RelocOffset;
1758 Reloc.getOffset(RelocOffset);
1759 if (RelocOffset == sect_offset) {
1760 Rel = Reloc.getRawDataRefImpl();
1761 RE = info->O->getRelocation(Rel);
1762 if (info->O->isRelocationScattered(RE))
1764 isExtern = info->O->getPlainRelocationExternal(RE);
1766 symbol_iterator RelocSym = Reloc.getSymbol();
1773 // If there is an external relocation entry for a symbol in this section
1774 // at this section_offset then use that symbol's value for the n_value
1775 // and return its name.
1776 const char *SymbolName = nullptr;
1777 if (reloc_found && isExtern) {
1778 Symbol.getAddress(n_value);
1780 Symbol.getName(name);
1781 if (!name.empty()) {
1782 SymbolName = name.data();
1787 // TODO: For fully linked images, look through the external relocation
1788 // entries off the dynamic symtab command. For these the r_offset is from the
1789 // start of the first writeable segment in the Mach-O file. So the offset
1790 // to this section from that segment is passed to this routine by the caller,
1791 // as the database_offset. Which is the difference of the section's starting
1792 // address and the first writable segment.
1794 // NOTE: need add passing the database_offset to this routine.
1796 // TODO: We did not find an external relocation entry so look up the
1797 // ReferenceValue as an address of a symbol and if found return that symbol's
1800 // NOTE: need add passing the ReferenceValue to this routine. Then that code
1801 // would simply be this:
1802 // SymbolName = GuessSymbolName(ReferenceValue, info);
1807 // These are structs in the Objective-C meta data and read to produce the
1808 // comments for disassembly. While these are part of the ABI they are no
1809 // public defintions. So the are here not in include/llvm/Support/MachO.h .
1811 // The cfstring object in a 64-bit Mach-O file.
1812 struct cfstring64_t {
1813 uint64_t isa; // class64_t * (64-bit pointer)
1814 uint64_t flags; // flag bits
1815 uint64_t characters; // char * (64-bit pointer)
1816 uint64_t length; // number of non-NULL characters in above
1819 // The class object in a 64-bit Mach-O file.
1821 uint64_t isa; // class64_t * (64-bit pointer)
1822 uint64_t superclass; // class64_t * (64-bit pointer)
1823 uint64_t cache; // Cache (64-bit pointer)
1824 uint64_t vtable; // IMP * (64-bit pointer)
1825 uint64_t data; // class_ro64_t * (64-bit pointer)
1828 struct class_ro64_t {
1830 uint32_t instanceStart;
1831 uint32_t instanceSize;
1833 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
1834 uint64_t name; // const char * (64-bit pointer)
1835 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
1836 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
1837 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
1838 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
1839 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
1842 inline void swapStruct(struct cfstring64_t &cfs) {
1843 sys::swapByteOrder(cfs.isa);
1844 sys::swapByteOrder(cfs.flags);
1845 sys::swapByteOrder(cfs.characters);
1846 sys::swapByteOrder(cfs.length);
1849 inline void swapStruct(struct class64_t &c) {
1850 sys::swapByteOrder(c.isa);
1851 sys::swapByteOrder(c.superclass);
1852 sys::swapByteOrder(c.cache);
1853 sys::swapByteOrder(c.vtable);
1854 sys::swapByteOrder(c.data);
1857 inline void swapStruct(struct class_ro64_t &cro) {
1858 sys::swapByteOrder(cro.flags);
1859 sys::swapByteOrder(cro.instanceStart);
1860 sys::swapByteOrder(cro.instanceSize);
1861 sys::swapByteOrder(cro.reserved);
1862 sys::swapByteOrder(cro.ivarLayout);
1863 sys::swapByteOrder(cro.name);
1864 sys::swapByteOrder(cro.baseMethods);
1865 sys::swapByteOrder(cro.baseProtocols);
1866 sys::swapByteOrder(cro.ivars);
1867 sys::swapByteOrder(cro.weakIvarLayout);
1868 sys::swapByteOrder(cro.baseProperties);
1871 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
1872 struct DisassembleInfo *info);
1874 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
1875 // to an Objective-C class and returns the class name. It is also passed the
1876 // address of the pointer, so when the pointer is zero as it can be in an .o
1877 // file, that is used to look for an external relocation entry with a symbol
1879 const char *get_objc2_64bit_class_name(uint64_t pointer_value,
1880 uint64_t ReferenceValue,
1881 struct DisassembleInfo *info) {
1883 uint32_t offset, left;
1886 // The pointer_value can be 0 in an object file and have a relocation
1887 // entry for the class symbol at the ReferenceValue (the address of the
1889 if (pointer_value == 0) {
1890 r = get_pointer_64(ReferenceValue, offset, left, S, info);
1891 if (r == nullptr || left < sizeof(uint64_t))
1894 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1895 if (symbol_name == nullptr)
1897 const char *class_name = strrchr(symbol_name, '$');
1898 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
1899 return class_name + 2;
1904 // The case were the pointer_value is non-zero and points to a class defined
1905 // in this Mach-O file.
1906 r = get_pointer_64(pointer_value, offset, left, S, info);
1907 if (r == nullptr || left < sizeof(struct class64_t))
1910 memcpy(&c, r, sizeof(struct class64_t));
1911 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1915 r = get_pointer_64(c.data, offset, left, S, info);
1916 if (r == nullptr || left < sizeof(struct class_ro64_t))
1918 struct class_ro64_t cro;
1919 memcpy(&cro, r, sizeof(struct class_ro64_t));
1920 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1924 const char *name = get_pointer_64(cro.name, offset, left, S, info);
1928 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
1929 // pointer to a cfstring and returns its name or nullptr.
1930 const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
1931 struct DisassembleInfo *info) {
1932 const char *r, *name;
1933 uint32_t offset, left;
1935 struct cfstring64_t cfs;
1936 uint64_t cfs_characters;
1938 r = get_pointer_64(ReferenceValue, offset, left, S, info);
1939 if (r == nullptr || left < sizeof(struct cfstring64_t))
1941 memcpy(&cfs, r, sizeof(struct cfstring64_t));
1942 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1944 if (cfs.characters == 0) {
1946 const char *symbol_name = get_symbol_64(
1947 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
1948 if (symbol_name == nullptr)
1950 cfs_characters = n_value;
1952 cfs_characters = cfs.characters;
1953 name = get_pointer_64(cfs_characters, offset, left, S, info);
1958 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
1959 // of a pointer to an Objective-C selector reference when the pointer value is
1960 // zero as in a .o file and is likely to have a external relocation entry with
1961 // who's symbol's n_value is the real pointer to the selector name. If that is
1962 // the case the real pointer to the selector name is returned else 0 is
1964 uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
1965 struct DisassembleInfo *info) {
1966 uint32_t offset, left;
1969 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
1970 if (r == nullptr || left < sizeof(uint64_t))
1973 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1974 if (symbol_name == nullptr)
1979 // GuessLiteralPointer returns a string which for the item in the Mach-O file
1980 // for the address passed in as ReferenceValue for printing as a comment with
1981 // the instruction and also returns the corresponding type of that item
1982 // indirectly through ReferenceType.
1984 // If ReferenceValue is an address of literal cstring then a pointer to the
1985 // cstring is returned and ReferenceType is set to
1986 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
1988 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
1989 // Class ref that name is returned and the ReferenceType is set accordingly.
1991 // Lastly, literals which are Symbol address in a literal pool are looked for
1992 // and if found the symbol name is returned and ReferenceType is set to
1993 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
1995 // If there is no item in the Mach-O file for the address passed in as
1996 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
1997 const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC,
1998 uint64_t *ReferenceType,
1999 struct DisassembleInfo *info) {
2000 // First see if there is an external relocation entry at the ReferencePC.
2001 uint64_t sect_addr = info->S.getAddress();
2002 uint64_t sect_offset = ReferencePC - sect_addr;
2003 bool reloc_found = false;
2005 MachO::any_relocation_info RE;
2006 bool isExtern = false;
2008 for (const RelocationRef &Reloc : info->S.relocations()) {
2009 uint64_t RelocOffset;
2010 Reloc.getOffset(RelocOffset);
2011 if (RelocOffset == sect_offset) {
2012 Rel = Reloc.getRawDataRefImpl();
2013 RE = info->O->getRelocation(Rel);
2014 if (info->O->isRelocationScattered(RE))
2016 isExtern = info->O->getPlainRelocationExternal(RE);
2018 symbol_iterator RelocSym = Reloc.getSymbol();
2025 // If there is an external relocation entry for a symbol in a section
2026 // then used that symbol's value for the value of the reference.
2027 if (reloc_found && isExtern) {
2028 if (info->O->getAnyRelocationPCRel(RE)) {
2029 unsigned Type = info->O->getAnyRelocationType(RE);
2030 if (Type == MachO::X86_64_RELOC_SIGNED) {
2031 Symbol.getAddress(ReferenceValue);
2036 // Look for literals such as Objective-C CFStrings refs, Selector refs,
2037 // Message refs and Class refs.
2038 bool classref, selref, msgref, cfstring;
2039 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
2040 selref, msgref, cfstring);
2041 if (classref == true && pointer_value == 0) {
2042 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
2043 // And the pointer_value in that section is typically zero as it will be
2044 // set by dyld as part of the "bind information".
2045 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
2046 if (name != nullptr) {
2047 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2048 const char *class_name = strrchr(name, '$');
2049 if (class_name != nullptr && class_name[1] == '_' &&
2050 class_name[2] != '\0') {
2051 info->class_name = class_name + 2;
2057 if (classref == true) {
2058 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2060 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
2061 if (name != nullptr)
2062 info->class_name = name;
2064 name = "bad class ref";
2068 if (cfstring == true) {
2069 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
2070 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
2074 if (selref == true && pointer_value == 0)
2075 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
2077 if (pointer_value != 0)
2078 ReferenceValue = pointer_value;
2080 const char *name = GuessCstringPointer(ReferenceValue, info);
2082 if (pointer_value != 0 && selref == true) {
2083 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
2084 info->selector_name = name;
2085 } else if (pointer_value != 0 && msgref == true) {
2086 info->class_name = nullptr;
2087 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
2088 info->selector_name = name;
2090 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
2094 // Lastly look for an indirect symbol with this ReferenceValue which is in
2095 // a literal pool. If found return that symbol name.
2096 name = GuessIndirectSymbol(ReferenceValue, info);
2098 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
2105 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
2106 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
2107 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
2108 // is created and returns the symbol name that matches the ReferenceValue or
2109 // nullptr if none. The ReferenceType is passed in for the IN type of
2110 // reference the instruction is making from the values in defined in the header
2111 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
2112 // Out type and the ReferenceName will also be set which is added as a comment
2113 // to the disassembled instruction.
2116 // If the symbol name is a C++ mangled name then the demangled name is
2117 // returned through ReferenceName and ReferenceType is set to
2118 // LLVMDisassembler_ReferenceType_DeMangled_Name .
2121 // When this is called to get a symbol name for a branch target then the
2122 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
2123 // SymbolValue will be looked for in the indirect symbol table to determine if
2124 // it is an address for a symbol stub. If so then the symbol name for that
2125 // stub is returned indirectly through ReferenceName and then ReferenceType is
2126 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
2128 // When this is called with an value loaded via a PC relative load then
2129 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
2130 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
2131 // or an Objective-C meta data reference. If so the output ReferenceType is
2132 // set to correspond to that as well as setting the ReferenceName.
2133 const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue,
2134 uint64_t *ReferenceType,
2135 uint64_t ReferencePC,
2136 const char **ReferenceName) {
2137 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2138 // If no verbose symbolic information is wanted then just return nullptr.
2139 if (info->verbose == false) {
2140 *ReferenceName = nullptr;
2141 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2145 const char *SymbolName = GuessSymbolName(ReferenceValue, info);
2147 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
2148 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
2149 if (*ReferenceName != nullptr) {
2150 method_reference(info, ReferenceType, ReferenceName);
2151 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
2152 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
2155 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2156 if (info->demangled_name != nullptr)
2157 free(info->demangled_name);
2159 info->demangled_name =
2160 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2161 if (info->demangled_name != nullptr) {
2162 *ReferenceName = info->demangled_name;
2163 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2165 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2168 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2169 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
2171 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2173 method_reference(info, ReferenceType, ReferenceName);
2175 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2176 // If this is arm64 and the reference is an adrp instruction save the
2177 // instruction, passed in ReferenceValue and the address of the instruction
2178 // for use later if we see and add immediate instruction.
2179 } else if (info->O->getArch() == Triple::aarch64 &&
2180 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
2181 info->adrp_inst = ReferenceValue;
2182 info->adrp_addr = ReferencePC;
2183 SymbolName = nullptr;
2184 *ReferenceName = nullptr;
2185 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2186 // If this is arm64 and reference is an add immediate instruction and we
2188 // seen an adrp instruction just before it and the adrp's Xd register
2190 // this add's Xn register reconstruct the value being referenced and look to
2191 // see if it is a literal pointer. Note the add immediate instruction is
2192 // passed in ReferenceValue.
2193 } else if (info->O->getArch() == Triple::aarch64 &&
2194 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
2195 ReferencePC - 4 == info->adrp_addr &&
2196 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2197 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2198 uint32_t addxri_inst;
2199 uint64_t adrp_imm, addxri_imm;
2202 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2203 if (info->adrp_inst & 0x0200000)
2204 adrp_imm |= 0xfffffffffc000000LL;
2206 addxri_inst = ReferenceValue;
2207 addxri_imm = (addxri_inst >> 10) & 0xfff;
2208 if (((addxri_inst >> 22) & 0x3) == 1)
2211 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2212 (adrp_imm << 12) + addxri_imm;
2215 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2216 if (*ReferenceName == nullptr)
2217 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2218 // If this is arm64 and the reference is a load register instruction and we
2219 // have seen an adrp instruction just before it and the adrp's Xd register
2220 // matches this add's Xn register reconstruct the value being referenced and
2221 // look to see if it is a literal pointer. Note the load register
2222 // instruction is passed in ReferenceValue.
2223 } else if (info->O->getArch() == Triple::aarch64 &&
2224 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
2225 ReferencePC - 4 == info->adrp_addr &&
2226 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2227 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2228 uint32_t ldrxui_inst;
2229 uint64_t adrp_imm, ldrxui_imm;
2232 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2233 if (info->adrp_inst & 0x0200000)
2234 adrp_imm |= 0xfffffffffc000000LL;
2236 ldrxui_inst = ReferenceValue;
2237 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
2239 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2240 (adrp_imm << 12) + (ldrxui_imm << 3);
2243 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2244 if (*ReferenceName == nullptr)
2245 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2247 // If this arm64 and is an load register (PC-relative) instruction the
2248 // ReferenceValue is the PC plus the immediate value.
2249 else if (info->O->getArch() == Triple::aarch64 &&
2250 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
2251 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
2253 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2254 if (*ReferenceName == nullptr)
2255 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2258 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2259 if (info->demangled_name != nullptr)
2260 free(info->demangled_name);
2262 info->demangled_name =
2263 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2264 if (info->demangled_name != nullptr) {
2265 *ReferenceName = info->demangled_name;
2266 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2271 *ReferenceName = nullptr;
2272 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2278 /// \brief Emits the comments that are stored in the CommentStream.
2279 /// Each comment in the CommentStream must end with a newline.
2280 static void emitComments(raw_svector_ostream &CommentStream,
2281 SmallString<128> &CommentsToEmit,
2282 formatted_raw_ostream &FormattedOS,
2283 const MCAsmInfo &MAI) {
2284 // Flush the stream before taking its content.
2285 CommentStream.flush();
2286 StringRef Comments = CommentsToEmit.str();
2287 // Get the default information for printing a comment.
2288 const char *CommentBegin = MAI.getCommentString();
2289 unsigned CommentColumn = MAI.getCommentColumn();
2290 bool IsFirst = true;
2291 while (!Comments.empty()) {
2293 FormattedOS << '\n';
2294 // Emit a line of comments.
2295 FormattedOS.PadToColumn(CommentColumn);
2296 size_t Position = Comments.find('\n');
2297 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
2298 // Move after the newline character.
2299 Comments = Comments.substr(Position + 1);
2302 FormattedOS.flush();
2304 // Tell the comment stream that the vector changed underneath it.
2305 CommentsToEmit.clear();
2306 CommentStream.resync();
2309 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF) {
2310 const char *McpuDefault = nullptr;
2311 const Target *ThumbTarget = nullptr;
2312 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
2314 // GetTarget prints out stuff.
2317 if (MCPU.empty() && McpuDefault)
2320 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
2321 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
2323 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
2325 // Package up features to be passed to target/subtarget
2326 std::string FeaturesStr;
2327 if (MAttrs.size()) {
2328 SubtargetFeatures Features;
2329 for (unsigned i = 0; i != MAttrs.size(); ++i)
2330 Features.AddFeature(MAttrs[i]);
2331 FeaturesStr = Features.getString();
2334 // Set up disassembler.
2335 std::unique_ptr<const MCRegisterInfo> MRI(
2336 TheTarget->createMCRegInfo(TripleName));
2337 std::unique_ptr<const MCAsmInfo> AsmInfo(
2338 TheTarget->createMCAsmInfo(*MRI, TripleName));
2339 std::unique_ptr<const MCSubtargetInfo> STI(
2340 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
2341 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
2342 std::unique_ptr<MCDisassembler> DisAsm(
2343 TheTarget->createMCDisassembler(*STI, Ctx));
2344 std::unique_ptr<MCSymbolizer> Symbolizer;
2345 struct DisassembleInfo SymbolizerInfo;
2346 std::unique_ptr<MCRelocationInfo> RelInfo(
2347 TheTarget->createMCRelocationInfo(TripleName, Ctx));
2349 Symbolizer.reset(TheTarget->createMCSymbolizer(
2350 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2351 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
2352 DisAsm->setSymbolizer(std::move(Symbolizer));
2354 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
2355 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
2356 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
2357 // Set the display preference for hex vs. decimal immediates.
2358 IP->setPrintImmHex(PrintImmHex);
2359 // Comment stream and backing vector.
2360 SmallString<128> CommentsToEmit;
2361 raw_svector_ostream CommentStream(CommentsToEmit);
2362 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
2363 // if it is done then arm64 comments for string literals don't get printed
2364 // and some constant get printed instead and not setting it causes intel
2365 // (32-bit and 64-bit) comments printed with different spacing before the
2366 // comment causing different diffs with the 'C' disassembler library API.
2367 // IP->setCommentStream(CommentStream);
2369 if (!AsmInfo || !STI || !DisAsm || !IP) {
2370 errs() << "error: couldn't initialize disassembler for target "
2371 << TripleName << '\n';
2375 // Set up thumb disassembler.
2376 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
2377 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
2378 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
2379 std::unique_ptr<MCDisassembler> ThumbDisAsm;
2380 std::unique_ptr<MCInstPrinter> ThumbIP;
2381 std::unique_ptr<MCContext> ThumbCtx;
2382 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
2383 struct DisassembleInfo ThumbSymbolizerInfo;
2384 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
2386 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
2388 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
2390 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
2391 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
2392 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
2393 MCContext *PtrThumbCtx = ThumbCtx.get();
2395 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
2397 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
2398 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2399 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
2400 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
2402 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
2403 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
2404 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
2406 // Set the display preference for hex vs. decimal immediates.
2407 ThumbIP->setPrintImmHex(PrintImmHex);
2410 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
2411 errs() << "error: couldn't initialize disassembler for target "
2412 << ThumbTripleName << '\n';
2416 MachO::mach_header Header = MachOOF->getHeader();
2418 // FIXME: Using the -cfg command line option, this code used to be able to
2419 // annotate relocations with the referenced symbol's name, and if this was
2420 // inside a __[cf]string section, the data it points to. This is now replaced
2421 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
2422 std::vector<SectionRef> Sections;
2423 std::vector<SymbolRef> Symbols;
2424 SmallVector<uint64_t, 8> FoundFns;
2425 uint64_t BaseSegmentAddress;
2427 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
2428 BaseSegmentAddress);
2430 // Sort the symbols by address, just in case they didn't come in that way.
2431 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
2433 // Build a data in code table that is sorted on by the address of each entry.
2434 uint64_t BaseAddress = 0;
2435 if (Header.filetype == MachO::MH_OBJECT)
2436 BaseAddress = Sections[0].getAddress();
2438 BaseAddress = BaseSegmentAddress;
2440 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
2443 DI->getOffset(Offset);
2444 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
2446 array_pod_sort(Dices.begin(), Dices.end());
2449 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
2451 raw_ostream &DebugOut = nulls();
2454 std::unique_ptr<DIContext> diContext;
2455 ObjectFile *DbgObj = MachOOF;
2456 // Try to find debug info and set up the DIContext for it.
2458 // A separate DSym file path was specified, parse it as a macho file,
2459 // get the sections and supply it to the section name parsing machinery.
2460 if (!DSYMFile.empty()) {
2461 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
2462 MemoryBuffer::getFileOrSTDIN(DSYMFile);
2463 if (std::error_code EC = BufOrErr.getError()) {
2464 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
2468 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
2473 // Setup the DIContext
2474 diContext.reset(DIContext::getDWARFContext(*DbgObj));
2477 // TODO: For now this only disassembles the (__TEXT,__text) section (see the
2478 // checks in the code below at the top of this loop). It should allow a
2479 // darwin otool(1) like -s option to disassemble any named segment & section
2480 // that is marked as containing instructions with the attributes
2481 // S_ATTR_PURE_INSTRUCTIONS or S_ATTR_SOME_INSTRUCTIONS in the flags field of
2482 // the section structure.
2483 outs() << "(__TEXT,__text) section\n";
2485 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
2487 bool SectIsText = Sections[SectIdx].isText();
2488 if (SectIsText == false)
2492 if (Sections[SectIdx].getName(SectName) || SectName != "__text")
2493 continue; // Skip non-text sections
2495 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
2497 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
2498 if (SegmentName != "__TEXT")
2502 Sections[SectIdx].getContents(BytesStr);
2503 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
2505 uint64_t SectAddress = Sections[SectIdx].getAddress();
2507 bool symbolTableWorked = false;
2509 // Parse relocations.
2510 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
2511 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
2512 uint64_t RelocOffset;
2513 Reloc.getOffset(RelocOffset);
2514 uint64_t SectionAddress = Sections[SectIdx].getAddress();
2515 RelocOffset -= SectionAddress;
2517 symbol_iterator RelocSym = Reloc.getSymbol();
2519 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
2521 array_pod_sort(Relocs.begin(), Relocs.end());
2523 // Create a map of symbol addresses to symbol names for use by
2524 // the SymbolizerSymbolLookUp() routine.
2525 SymbolAddressMap AddrMap;
2526 for (const SymbolRef &Symbol : MachOOF->symbols()) {
2529 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
2530 ST == SymbolRef::ST_Other) {
2532 Symbol.getAddress(Address);
2534 Symbol.getName(SymName);
2535 AddrMap[Address] = SymName;
2538 // Set up the block of info used by the Symbolizer call backs.
2539 SymbolizerInfo.verbose = true;
2540 SymbolizerInfo.O = MachOOF;
2541 SymbolizerInfo.S = Sections[SectIdx];
2542 SymbolizerInfo.AddrMap = &AddrMap;
2543 SymbolizerInfo.Sections = &Sections;
2544 SymbolizerInfo.class_name = nullptr;
2545 SymbolizerInfo.selector_name = nullptr;
2546 SymbolizerInfo.method = nullptr;
2547 SymbolizerInfo.demangled_name = nullptr;
2548 SymbolizerInfo.bindtable = nullptr;
2549 SymbolizerInfo.adrp_addr = 0;
2550 SymbolizerInfo.adrp_inst = 0;
2551 // Same for the ThumbSymbolizer
2552 ThumbSymbolizerInfo.verbose = true;
2553 ThumbSymbolizerInfo.O = MachOOF;
2554 ThumbSymbolizerInfo.S = Sections[SectIdx];
2555 ThumbSymbolizerInfo.AddrMap = &AddrMap;
2556 ThumbSymbolizerInfo.Sections = &Sections;
2557 ThumbSymbolizerInfo.class_name = nullptr;
2558 ThumbSymbolizerInfo.selector_name = nullptr;
2559 ThumbSymbolizerInfo.method = nullptr;
2560 ThumbSymbolizerInfo.demangled_name = nullptr;
2561 ThumbSymbolizerInfo.bindtable = nullptr;
2562 ThumbSymbolizerInfo.adrp_addr = 0;
2563 ThumbSymbolizerInfo.adrp_inst = 0;
2565 // Disassemble symbol by symbol.
2566 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
2568 Symbols[SymIdx].getName(SymName);
2571 Symbols[SymIdx].getType(ST);
2572 if (ST != SymbolRef::ST_Function)
2575 // Make sure the symbol is defined in this section.
2576 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
2580 // Start at the address of the symbol relative to the section's address.
2582 uint64_t SectionAddress = Sections[SectIdx].getAddress();
2583 Symbols[SymIdx].getAddress(Start);
2584 Start -= SectionAddress;
2586 // Stop disassembling either at the beginning of the next symbol or at
2587 // the end of the section.
2588 bool containsNextSym = false;
2589 uint64_t NextSym = 0;
2590 uint64_t NextSymIdx = SymIdx + 1;
2591 while (Symbols.size() > NextSymIdx) {
2592 SymbolRef::Type NextSymType;
2593 Symbols[NextSymIdx].getType(NextSymType);
2594 if (NextSymType == SymbolRef::ST_Function) {
2596 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
2597 Symbols[NextSymIdx].getAddress(NextSym);
2598 NextSym -= SectionAddress;
2604 uint64_t SectSize = Sections[SectIdx].getSize();
2605 uint64_t End = containsNextSym ? NextSym : SectSize;
2608 symbolTableWorked = true;
2610 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
2612 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
2614 outs() << SymName << ":\n";
2615 DILineInfo lastLine;
2616 for (uint64_t Index = Start; Index < End; Index += Size) {
2619 uint64_t PC = SectAddress + Index;
2620 if (FullLeadingAddr) {
2621 if (MachOOF->is64Bit())
2622 outs() << format("%016" PRIx64, PC);
2624 outs() << format("%08" PRIx64, PC);
2626 outs() << format("%8" PRIx64 ":", PC);
2631 // Check the data in code table here to see if this is data not an
2632 // instruction to be disassembled.
2634 Dice.push_back(std::make_pair(PC, DiceRef()));
2635 dice_table_iterator DTI =
2636 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
2637 compareDiceTableEntries);
2638 if (DTI != Dices.end()) {
2640 DTI->second.getLength(Length);
2642 DTI->second.getKind(Kind);
2643 Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
2646 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
2647 (PC == (DTI->first + Length - 1)) && (Length & 1))
2652 SmallVector<char, 64> AnnotationsBytes;
2653 raw_svector_ostream Annotations(AnnotationsBytes);
2657 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
2658 PC, DebugOut, Annotations);
2660 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
2661 DebugOut, Annotations);
2663 if (!NoShowRawInsn) {
2664 DumpBytes(StringRef(
2665 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
2667 formatted_raw_ostream FormattedOS(outs());
2668 Annotations.flush();
2669 StringRef AnnotationsStr = Annotations.str();
2671 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
2673 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
2674 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
2676 // Print debug info.
2678 DILineInfo dli = diContext->getLineInfoForAddress(PC);
2679 // Print valid line info if it changed.
2680 if (dli != lastLine && dli.Line != 0)
2681 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
2687 unsigned int Arch = MachOOF->getArch();
2688 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
2689 outs() << format("\t.byte 0x%02x #bad opcode\n",
2690 *(Bytes.data() + Index) & 0xff);
2691 Size = 1; // skip exactly one illegible byte and move on.
2692 } else if (Arch == Triple::aarch64) {
2693 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
2694 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
2695 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
2696 (*(Bytes.data() + Index + 3) & 0xff) << 24;
2697 outs() << format("\t.long\t0x%08x\n", opcode);
2700 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2702 Size = 1; // skip illegible bytes
2707 if (!symbolTableWorked) {
2708 // Reading the symbol table didn't work, disassemble the whole section.
2709 uint64_t SectAddress = Sections[SectIdx].getAddress();
2710 uint64_t SectSize = Sections[SectIdx].getSize();
2712 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
2715 uint64_t PC = SectAddress + Index;
2716 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
2717 DebugOut, nulls())) {
2718 if (FullLeadingAddr) {
2719 if (MachOOF->is64Bit())
2720 outs() << format("%016" PRIx64, PC);
2722 outs() << format("%08" PRIx64, PC);
2724 outs() << format("%8" PRIx64 ":", PC);
2726 if (!NoShowRawInsn) {
2729 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
2732 IP->printInst(&Inst, outs(), "");
2735 unsigned int Arch = MachOOF->getArch();
2736 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
2737 outs() << format("\t.byte 0x%02x #bad opcode\n",
2738 *(Bytes.data() + Index) & 0xff);
2739 InstSize = 1; // skip exactly one illegible byte and move on.
2741 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2743 InstSize = 1; // skip illegible bytes
2748 // The TripleName's need to be reset if we are called again for a different
2751 ThumbTripleName = "";
2753 if (SymbolizerInfo.method != nullptr)
2754 free(SymbolizerInfo.method);
2755 if (SymbolizerInfo.demangled_name != nullptr)
2756 free(SymbolizerInfo.demangled_name);
2757 if (SymbolizerInfo.bindtable != nullptr)
2758 delete SymbolizerInfo.bindtable;
2759 if (ThumbSymbolizerInfo.method != nullptr)
2760 free(ThumbSymbolizerInfo.method);
2761 if (ThumbSymbolizerInfo.demangled_name != nullptr)
2762 free(ThumbSymbolizerInfo.demangled_name);
2763 if (ThumbSymbolizerInfo.bindtable != nullptr)
2764 delete ThumbSymbolizerInfo.bindtable;
2768 //===----------------------------------------------------------------------===//
2769 // __compact_unwind section dumping
2770 //===----------------------------------------------------------------------===//
2774 template <typename T> static uint64_t readNext(const char *&Buf) {
2775 using llvm::support::little;
2776 using llvm::support::unaligned;
2778 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
2783 struct CompactUnwindEntry {
2784 uint32_t OffsetInSection;
2786 uint64_t FunctionAddr;
2788 uint32_t CompactEncoding;
2789 uint64_t PersonalityAddr;
2792 RelocationRef FunctionReloc;
2793 RelocationRef PersonalityReloc;
2794 RelocationRef LSDAReloc;
2796 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
2797 : OffsetInSection(Offset) {
2799 read<uint64_t>(Contents.data() + Offset);
2801 read<uint32_t>(Contents.data() + Offset);
2805 template <typename UIntPtr> void read(const char *Buf) {
2806 FunctionAddr = readNext<UIntPtr>(Buf);
2807 Length = readNext<uint32_t>(Buf);
2808 CompactEncoding = readNext<uint32_t>(Buf);
2809 PersonalityAddr = readNext<UIntPtr>(Buf);
2810 LSDAAddr = readNext<UIntPtr>(Buf);
2815 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
2816 /// and data being relocated, determine the best base Name and Addend to use for
2817 /// display purposes.
2819 /// 1. An Extern relocation will directly reference a symbol (and the data is
2820 /// then already an addend), so use that.
2821 /// 2. Otherwise the data is an offset in the object file's layout; try to find
2822 // a symbol before it in the same section, and use the offset from there.
2823 /// 3. Finally, if all that fails, fall back to an offset from the start of the
2824 /// referenced section.
2825 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
2826 std::map<uint64_t, SymbolRef> &Symbols,
2827 const RelocationRef &Reloc, uint64_t Addr,
2828 StringRef &Name, uint64_t &Addend) {
2829 if (Reloc.getSymbol() != Obj->symbol_end()) {
2830 Reloc.getSymbol()->getName(Name);
2835 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
2836 SectionRef RelocSection = Obj->getRelocationSection(RE);
2838 uint64_t SectionAddr = RelocSection.getAddress();
2840 auto Sym = Symbols.upper_bound(Addr);
2841 if (Sym == Symbols.begin()) {
2842 // The first symbol in the object is after this reference, the best we can
2843 // do is section-relative notation.
2844 RelocSection.getName(Name);
2845 Addend = Addr - SectionAddr;
2849 // Go back one so that SymbolAddress <= Addr.
2852 section_iterator SymSection = Obj->section_end();
2853 Sym->second.getSection(SymSection);
2854 if (RelocSection == *SymSection) {
2855 // There's a valid symbol in the same section before this reference.
2856 Sym->second.getName(Name);
2857 Addend = Addr - Sym->first;
2861 // There is a symbol before this reference, but it's in a different
2862 // section. Probably not helpful to mention it, so use the section name.
2863 RelocSection.getName(Name);
2864 Addend = Addr - SectionAddr;
2867 static void printUnwindRelocDest(const MachOObjectFile *Obj,
2868 std::map<uint64_t, SymbolRef> &Symbols,
2869 const RelocationRef &Reloc, uint64_t Addr) {
2873 if (!Reloc.getObjectFile())
2876 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
2880 outs() << " + " << format("0x%" PRIx64, Addend);
2884 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
2885 std::map<uint64_t, SymbolRef> &Symbols,
2886 const SectionRef &CompactUnwind) {
2888 assert(Obj->isLittleEndian() &&
2889 "There should not be a big-endian .o with __compact_unwind");
2891 bool Is64 = Obj->is64Bit();
2892 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
2893 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
2896 CompactUnwind.getContents(Contents);
2898 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
2900 // First populate the initial raw offsets, encodings and so on from the entry.
2901 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
2902 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
2903 CompactUnwinds.push_back(Entry);
2906 // Next we need to look at the relocations to find out what objects are
2907 // actually being referred to.
2908 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
2909 uint64_t RelocAddress;
2910 Reloc.getOffset(RelocAddress);
2912 uint32_t EntryIdx = RelocAddress / EntrySize;
2913 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
2914 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
2916 if (OffsetInEntry == 0)
2917 Entry.FunctionReloc = Reloc;
2918 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
2919 Entry.PersonalityReloc = Reloc;
2920 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
2921 Entry.LSDAReloc = Reloc;
2923 llvm_unreachable("Unexpected relocation in __compact_unwind section");
2926 // Finally, we're ready to print the data we've gathered.
2927 outs() << "Contents of __compact_unwind section:\n";
2928 for (auto &Entry : CompactUnwinds) {
2929 outs() << " Entry at offset "
2930 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
2932 // 1. Start of the region this entry applies to.
2933 outs() << " start: " << format("0x%" PRIx64,
2934 Entry.FunctionAddr) << ' ';
2935 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
2938 // 2. Length of the region this entry applies to.
2939 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
2941 // 3. The 32-bit compact encoding.
2942 outs() << " compact encoding: "
2943 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
2945 // 4. The personality function, if present.
2946 if (Entry.PersonalityReloc.getObjectFile()) {
2947 outs() << " personality function: "
2948 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
2949 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
2950 Entry.PersonalityAddr);
2954 // 5. This entry's language-specific data area.
2955 if (Entry.LSDAReloc.getObjectFile()) {
2956 outs() << " LSDA: " << format("0x%" PRIx64,
2957 Entry.LSDAAddr) << ' ';
2958 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
2964 //===----------------------------------------------------------------------===//
2965 // __unwind_info section dumping
2966 //===----------------------------------------------------------------------===//
2968 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
2969 const char *Pos = PageStart;
2970 uint32_t Kind = readNext<uint32_t>(Pos);
2972 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
2974 uint16_t EntriesStart = readNext<uint16_t>(Pos);
2975 uint16_t NumEntries = readNext<uint16_t>(Pos);
2977 Pos = PageStart + EntriesStart;
2978 for (unsigned i = 0; i < NumEntries; ++i) {
2979 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2980 uint32_t Encoding = readNext<uint32_t>(Pos);
2982 outs() << " [" << i << "]: "
2983 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2985 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
2989 static void printCompressedSecondLevelUnwindPage(
2990 const char *PageStart, uint32_t FunctionBase,
2991 const SmallVectorImpl<uint32_t> &CommonEncodings) {
2992 const char *Pos = PageStart;
2993 uint32_t Kind = readNext<uint32_t>(Pos);
2995 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
2997 uint16_t EntriesStart = readNext<uint16_t>(Pos);
2998 uint16_t NumEntries = readNext<uint16_t>(Pos);
3000 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
3001 readNext<uint16_t>(Pos);
3002 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
3003 PageStart + EncodingsStart);
3005 Pos = PageStart + EntriesStart;
3006 for (unsigned i = 0; i < NumEntries; ++i) {
3007 uint32_t Entry = readNext<uint32_t>(Pos);
3008 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
3009 uint32_t EncodingIdx = Entry >> 24;
3012 if (EncodingIdx < CommonEncodings.size())
3013 Encoding = CommonEncodings[EncodingIdx];
3015 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
3017 outs() << " [" << i << "]: "
3018 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3020 << "encoding[" << EncodingIdx
3021 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
3025 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
3026 std::map<uint64_t, SymbolRef> &Symbols,
3027 const SectionRef &UnwindInfo) {
3029 assert(Obj->isLittleEndian() &&
3030 "There should not be a big-endian .o with __unwind_info");
3032 outs() << "Contents of __unwind_info section:\n";
3035 UnwindInfo.getContents(Contents);
3036 const char *Pos = Contents.data();
3038 //===----------------------------------
3040 //===----------------------------------
3042 uint32_t Version = readNext<uint32_t>(Pos);
3043 outs() << " Version: "
3044 << format("0x%" PRIx32, Version) << '\n';
3045 assert(Version == 1 && "only understand version 1");
3047 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
3048 outs() << " Common encodings array section offset: "
3049 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
3050 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
3051 outs() << " Number of common encodings in array: "
3052 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
3054 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
3055 outs() << " Personality function array section offset: "
3056 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
3057 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
3058 outs() << " Number of personality functions in array: "
3059 << format("0x%" PRIx32, NumPersonalities) << '\n';
3061 uint32_t IndicesStart = readNext<uint32_t>(Pos);
3062 outs() << " Index array section offset: "
3063 << format("0x%" PRIx32, IndicesStart) << '\n';
3064 uint32_t NumIndices = readNext<uint32_t>(Pos);
3065 outs() << " Number of indices in array: "
3066 << format("0x%" PRIx32, NumIndices) << '\n';
3068 //===----------------------------------
3069 // A shared list of common encodings
3070 //===----------------------------------
3072 // These occupy indices in the range [0, N] whenever an encoding is referenced
3073 // from a compressed 2nd level index table. In practice the linker only
3074 // creates ~128 of these, so that indices are available to embed encodings in
3075 // the 2nd level index.
3077 SmallVector<uint32_t, 64> CommonEncodings;
3078 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
3079 Pos = Contents.data() + CommonEncodingsStart;
3080 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
3081 uint32_t Encoding = readNext<uint32_t>(Pos);
3082 CommonEncodings.push_back(Encoding);
3084 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
3088 //===----------------------------------
3089 // Personality functions used in this executable
3090 //===----------------------------------
3092 // There should be only a handful of these (one per source language,
3093 // roughly). Particularly since they only get 2 bits in the compact encoding.
3095 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
3096 Pos = Contents.data() + PersonalitiesStart;
3097 for (unsigned i = 0; i < NumPersonalities; ++i) {
3098 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
3099 outs() << " personality[" << i + 1
3100 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
3103 //===----------------------------------
3104 // The level 1 index entries
3105 //===----------------------------------
3107 // These specify an approximate place to start searching for the more detailed
3108 // information, sorted by PC.
3111 uint32_t FunctionOffset;
3112 uint32_t SecondLevelPageStart;
3116 SmallVector<IndexEntry, 4> IndexEntries;
3118 outs() << " Top level indices: (count = " << NumIndices << ")\n";
3119 Pos = Contents.data() + IndicesStart;
3120 for (unsigned i = 0; i < NumIndices; ++i) {
3123 Entry.FunctionOffset = readNext<uint32_t>(Pos);
3124 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
3125 Entry.LSDAStart = readNext<uint32_t>(Pos);
3126 IndexEntries.push_back(Entry);
3128 outs() << " [" << i << "]: "
3129 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
3131 << "2nd level page offset="
3132 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
3133 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
3136 //===----------------------------------
3137 // Next come the LSDA tables
3138 //===----------------------------------
3140 // The LSDA layout is rather implicit: it's a contiguous array of entries from
3141 // the first top-level index's LSDAOffset to the last (sentinel).
3143 outs() << " LSDA descriptors:\n";
3144 Pos = Contents.data() + IndexEntries[0].LSDAStart;
3145 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
3146 (2 * sizeof(uint32_t));
3147 for (int i = 0; i < NumLSDAs; ++i) {
3148 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3149 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
3150 outs() << " [" << i << "]: "
3151 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3153 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
3156 //===----------------------------------
3157 // Finally, the 2nd level indices
3158 //===----------------------------------
3160 // Generally these are 4K in size, and have 2 possible forms:
3161 // + Regular stores up to 511 entries with disparate encodings
3162 // + Compressed stores up to 1021 entries if few enough compact encoding
3164 outs() << " Second level indices:\n";
3165 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
3166 // The final sentinel top-level index has no associated 2nd level page
3167 if (IndexEntries[i].SecondLevelPageStart == 0)
3170 outs() << " Second level index[" << i << "]: "
3171 << "offset in section="
3172 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
3174 << "base function offset="
3175 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
3177 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
3178 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
3180 printRegularSecondLevelUnwindPage(Pos);
3182 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
3185 llvm_unreachable("Do not know how to print this kind of 2nd level page");
3189 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
3190 std::map<uint64_t, SymbolRef> Symbols;
3191 for (const SymbolRef &SymRef : Obj->symbols()) {
3192 // Discard any undefined or absolute symbols. They're not going to take part
3193 // in the convenience lookup for unwind info and just take up resources.
3194 section_iterator Section = Obj->section_end();
3195 SymRef.getSection(Section);
3196 if (Section == Obj->section_end())
3200 SymRef.getAddress(Addr);
3201 Symbols.insert(std::make_pair(Addr, SymRef));
3204 for (const SectionRef &Section : Obj->sections()) {
3206 Section.getName(SectName);
3207 if (SectName == "__compact_unwind")
3208 printMachOCompactUnwindSection(Obj, Symbols, Section);
3209 else if (SectName == "__unwind_info")
3210 printMachOUnwindInfoSection(Obj, Symbols, Section);
3211 else if (SectName == "__eh_frame")
3212 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
3216 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
3217 uint32_t cpusubtype, uint32_t filetype,
3218 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
3220 outs() << "Mach header\n";
3221 outs() << " magic cputype cpusubtype caps filetype ncmds "
3222 "sizeofcmds flags\n";
3224 if (magic == MachO::MH_MAGIC)
3225 outs() << " MH_MAGIC";
3226 else if (magic == MachO::MH_MAGIC_64)
3227 outs() << "MH_MAGIC_64";
3229 outs() << format(" 0x%08" PRIx32, magic);
3231 case MachO::CPU_TYPE_I386:
3233 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3234 case MachO::CPU_SUBTYPE_I386_ALL:
3238 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3242 case MachO::CPU_TYPE_X86_64:
3243 outs() << " X86_64";
3244 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3245 case MachO::CPU_SUBTYPE_X86_64_ALL:
3248 case MachO::CPU_SUBTYPE_X86_64_H:
3249 outs() << " Haswell";
3252 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3256 case MachO::CPU_TYPE_ARM:
3258 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3259 case MachO::CPU_SUBTYPE_ARM_ALL:
3262 case MachO::CPU_SUBTYPE_ARM_V4T:
3265 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
3268 case MachO::CPU_SUBTYPE_ARM_XSCALE:
3269 outs() << " XSCALE";
3271 case MachO::CPU_SUBTYPE_ARM_V6:
3274 case MachO::CPU_SUBTYPE_ARM_V6M:
3277 case MachO::CPU_SUBTYPE_ARM_V7:
3280 case MachO::CPU_SUBTYPE_ARM_V7EM:
3283 case MachO::CPU_SUBTYPE_ARM_V7K:
3286 case MachO::CPU_SUBTYPE_ARM_V7M:
3289 case MachO::CPU_SUBTYPE_ARM_V7S:
3293 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3297 case MachO::CPU_TYPE_ARM64:
3299 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3300 case MachO::CPU_SUBTYPE_ARM64_ALL:
3304 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3308 case MachO::CPU_TYPE_POWERPC:
3310 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3311 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3315 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3319 case MachO::CPU_TYPE_POWERPC64:
3321 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3322 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3326 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3331 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
3334 outs() << format(" 0x%02" PRIx32,
3335 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3338 case MachO::MH_OBJECT:
3339 outs() << " OBJECT";
3341 case MachO::MH_EXECUTE:
3342 outs() << " EXECUTE";
3344 case MachO::MH_FVMLIB:
3345 outs() << " FVMLIB";
3347 case MachO::MH_CORE:
3350 case MachO::MH_PRELOAD:
3351 outs() << " PRELOAD";
3353 case MachO::MH_DYLIB:
3356 case MachO::MH_DYLIB_STUB:
3357 outs() << " DYLIB_STUB";
3359 case MachO::MH_DYLINKER:
3360 outs() << " DYLINKER";
3362 case MachO::MH_BUNDLE:
3363 outs() << " BUNDLE";
3365 case MachO::MH_DSYM:
3368 case MachO::MH_KEXT_BUNDLE:
3369 outs() << " KEXTBUNDLE";
3372 outs() << format(" %10u", filetype);
3375 outs() << format(" %5u", ncmds);
3376 outs() << format(" %10u", sizeofcmds);
3378 if (f & MachO::MH_NOUNDEFS) {
3379 outs() << " NOUNDEFS";
3380 f &= ~MachO::MH_NOUNDEFS;
3382 if (f & MachO::MH_INCRLINK) {
3383 outs() << " INCRLINK";
3384 f &= ~MachO::MH_INCRLINK;
3386 if (f & MachO::MH_DYLDLINK) {
3387 outs() << " DYLDLINK";
3388 f &= ~MachO::MH_DYLDLINK;
3390 if (f & MachO::MH_BINDATLOAD) {
3391 outs() << " BINDATLOAD";
3392 f &= ~MachO::MH_BINDATLOAD;
3394 if (f & MachO::MH_PREBOUND) {
3395 outs() << " PREBOUND";
3396 f &= ~MachO::MH_PREBOUND;
3398 if (f & MachO::MH_SPLIT_SEGS) {
3399 outs() << " SPLIT_SEGS";
3400 f &= ~MachO::MH_SPLIT_SEGS;
3402 if (f & MachO::MH_LAZY_INIT) {
3403 outs() << " LAZY_INIT";
3404 f &= ~MachO::MH_LAZY_INIT;
3406 if (f & MachO::MH_TWOLEVEL) {
3407 outs() << " TWOLEVEL";
3408 f &= ~MachO::MH_TWOLEVEL;
3410 if (f & MachO::MH_FORCE_FLAT) {
3411 outs() << " FORCE_FLAT";
3412 f &= ~MachO::MH_FORCE_FLAT;
3414 if (f & MachO::MH_NOMULTIDEFS) {
3415 outs() << " NOMULTIDEFS";
3416 f &= ~MachO::MH_NOMULTIDEFS;
3418 if (f & MachO::MH_NOFIXPREBINDING) {
3419 outs() << " NOFIXPREBINDING";
3420 f &= ~MachO::MH_NOFIXPREBINDING;
3422 if (f & MachO::MH_PREBINDABLE) {
3423 outs() << " PREBINDABLE";
3424 f &= ~MachO::MH_PREBINDABLE;
3426 if (f & MachO::MH_ALLMODSBOUND) {
3427 outs() << " ALLMODSBOUND";
3428 f &= ~MachO::MH_ALLMODSBOUND;
3430 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
3431 outs() << " SUBSECTIONS_VIA_SYMBOLS";
3432 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
3434 if (f & MachO::MH_CANONICAL) {
3435 outs() << " CANONICAL";
3436 f &= ~MachO::MH_CANONICAL;
3438 if (f & MachO::MH_WEAK_DEFINES) {
3439 outs() << " WEAK_DEFINES";
3440 f &= ~MachO::MH_WEAK_DEFINES;
3442 if (f & MachO::MH_BINDS_TO_WEAK) {
3443 outs() << " BINDS_TO_WEAK";
3444 f &= ~MachO::MH_BINDS_TO_WEAK;
3446 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
3447 outs() << " ALLOW_STACK_EXECUTION";
3448 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
3450 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
3451 outs() << " DEAD_STRIPPABLE_DYLIB";
3452 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
3454 if (f & MachO::MH_PIE) {
3456 f &= ~MachO::MH_PIE;
3458 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
3459 outs() << " NO_REEXPORTED_DYLIBS";
3460 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
3462 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
3463 outs() << " MH_HAS_TLV_DESCRIPTORS";
3464 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
3466 if (f & MachO::MH_NO_HEAP_EXECUTION) {
3467 outs() << " MH_NO_HEAP_EXECUTION";
3468 f &= ~MachO::MH_NO_HEAP_EXECUTION;
3470 if (f & MachO::MH_APP_EXTENSION_SAFE) {
3471 outs() << " APP_EXTENSION_SAFE";
3472 f &= ~MachO::MH_APP_EXTENSION_SAFE;
3474 if (f != 0 || flags == 0)
3475 outs() << format(" 0x%08" PRIx32, f);
3477 outs() << format(" 0x%08" PRIx32, magic);
3478 outs() << format(" %7d", cputype);
3479 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3480 outs() << format(" 0x%02" PRIx32,
3481 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3482 outs() << format(" %10u", filetype);
3483 outs() << format(" %5u", ncmds);
3484 outs() << format(" %10u", sizeofcmds);
3485 outs() << format(" 0x%08" PRIx32, flags);
3490 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
3491 StringRef SegName, uint64_t vmaddr,
3492 uint64_t vmsize, uint64_t fileoff,
3493 uint64_t filesize, uint32_t maxprot,
3494 uint32_t initprot, uint32_t nsects,
3495 uint32_t flags, uint32_t object_size,
3497 uint64_t expected_cmdsize;
3498 if (cmd == MachO::LC_SEGMENT) {
3499 outs() << " cmd LC_SEGMENT\n";
3500 expected_cmdsize = nsects;
3501 expected_cmdsize *= sizeof(struct MachO::section);
3502 expected_cmdsize += sizeof(struct MachO::segment_command);
3504 outs() << " cmd LC_SEGMENT_64\n";
3505 expected_cmdsize = nsects;
3506 expected_cmdsize *= sizeof(struct MachO::section_64);
3507 expected_cmdsize += sizeof(struct MachO::segment_command_64);
3509 outs() << " cmdsize " << cmdsize;
3510 if (cmdsize != expected_cmdsize)
3511 outs() << " Inconsistent size\n";
3514 outs() << " segname " << SegName << "\n";
3515 if (cmd == MachO::LC_SEGMENT_64) {
3516 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
3517 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
3519 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
3520 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
3522 outs() << " fileoff " << fileoff;
3523 if (fileoff > object_size)
3524 outs() << " (past end of file)\n";
3527 outs() << " filesize " << filesize;
3528 if (fileoff + filesize > object_size)
3529 outs() << " (past end of file)\n";
3534 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3535 MachO::VM_PROT_EXECUTE)) != 0)
3536 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
3538 if (maxprot & MachO::VM_PROT_READ)
3539 outs() << " maxprot r";
3541 outs() << " maxprot -";
3542 if (maxprot & MachO::VM_PROT_WRITE)
3546 if (maxprot & MachO::VM_PROT_EXECUTE)
3552 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3553 MachO::VM_PROT_EXECUTE)) != 0)
3554 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
3556 if (initprot & MachO::VM_PROT_READ)
3557 outs() << " initprot r";
3559 outs() << " initprot -";
3560 if (initprot & MachO::VM_PROT_WRITE)
3564 if (initprot & MachO::VM_PROT_EXECUTE)
3570 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
3571 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
3573 outs() << " nsects " << nsects << "\n";
3577 outs() << " (none)\n";
3579 if (flags & MachO::SG_HIGHVM) {
3580 outs() << " HIGHVM";
3581 flags &= ~MachO::SG_HIGHVM;
3583 if (flags & MachO::SG_FVMLIB) {
3584 outs() << " FVMLIB";
3585 flags &= ~MachO::SG_FVMLIB;
3587 if (flags & MachO::SG_NORELOC) {
3588 outs() << " NORELOC";
3589 flags &= ~MachO::SG_NORELOC;
3591 if (flags & MachO::SG_PROTECTED_VERSION_1) {
3592 outs() << " PROTECTED_VERSION_1";
3593 flags &= ~MachO::SG_PROTECTED_VERSION_1;
3596 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
3601 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
3605 static void PrintSection(const char *sectname, const char *segname,
3606 uint64_t addr, uint64_t size, uint32_t offset,
3607 uint32_t align, uint32_t reloff, uint32_t nreloc,
3608 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
3609 uint32_t cmd, const char *sg_segname,
3610 uint32_t filetype, uint32_t object_size,
3612 outs() << "Section\n";
3613 outs() << " sectname " << format("%.16s\n", sectname);
3614 outs() << " segname " << format("%.16s", segname);
3615 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
3616 outs() << " (does not match segment)\n";
3619 if (cmd == MachO::LC_SEGMENT_64) {
3620 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
3621 outs() << " size " << format("0x%016" PRIx64, size);
3623 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
3624 outs() << " size " << format("0x%08" PRIx64, size);
3626 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
3627 outs() << " (past end of file)\n";
3630 outs() << " offset " << offset;
3631 if (offset > object_size)
3632 outs() << " (past end of file)\n";
3635 uint32_t align_shifted = 1 << align;
3636 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
3637 outs() << " reloff " << reloff;
3638 if (reloff > object_size)
3639 outs() << " (past end of file)\n";
3642 outs() << " nreloc " << nreloc;
3643 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
3644 outs() << " (past end of file)\n";
3647 uint32_t section_type = flags & MachO::SECTION_TYPE;
3650 if (section_type == MachO::S_REGULAR)
3651 outs() << " S_REGULAR\n";
3652 else if (section_type == MachO::S_ZEROFILL)
3653 outs() << " S_ZEROFILL\n";
3654 else if (section_type == MachO::S_CSTRING_LITERALS)
3655 outs() << " S_CSTRING_LITERALS\n";
3656 else if (section_type == MachO::S_4BYTE_LITERALS)
3657 outs() << " S_4BYTE_LITERALS\n";
3658 else if (section_type == MachO::S_8BYTE_LITERALS)
3659 outs() << " S_8BYTE_LITERALS\n";
3660 else if (section_type == MachO::S_16BYTE_LITERALS)
3661 outs() << " S_16BYTE_LITERALS\n";
3662 else if (section_type == MachO::S_LITERAL_POINTERS)
3663 outs() << " S_LITERAL_POINTERS\n";
3664 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
3665 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
3666 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
3667 outs() << " S_LAZY_SYMBOL_POINTERS\n";
3668 else if (section_type == MachO::S_SYMBOL_STUBS)
3669 outs() << " S_SYMBOL_STUBS\n";
3670 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
3671 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
3672 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
3673 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
3674 else if (section_type == MachO::S_COALESCED)
3675 outs() << " S_COALESCED\n";
3676 else if (section_type == MachO::S_INTERPOSING)
3677 outs() << " S_INTERPOSING\n";
3678 else if (section_type == MachO::S_DTRACE_DOF)
3679 outs() << " S_DTRACE_DOF\n";
3680 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
3681 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
3682 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
3683 outs() << " S_THREAD_LOCAL_REGULAR\n";
3684 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
3685 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
3686 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
3687 outs() << " S_THREAD_LOCAL_VARIABLES\n";
3688 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
3689 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
3690 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
3691 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
3693 outs() << format("0x%08" PRIx32, section_type) << "\n";
3694 outs() << "attributes";
3695 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
3696 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
3697 outs() << " PURE_INSTRUCTIONS";
3698 if (section_attributes & MachO::S_ATTR_NO_TOC)
3699 outs() << " NO_TOC";
3700 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
3701 outs() << " STRIP_STATIC_SYMS";
3702 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
3703 outs() << " NO_DEAD_STRIP";
3704 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
3705 outs() << " LIVE_SUPPORT";
3706 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
3707 outs() << " SELF_MODIFYING_CODE";
3708 if (section_attributes & MachO::S_ATTR_DEBUG)
3710 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
3711 outs() << " SOME_INSTRUCTIONS";
3712 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
3713 outs() << " EXT_RELOC";
3714 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
3715 outs() << " LOC_RELOC";
3716 if (section_attributes == 0)
3717 outs() << " (none)";
3720 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
3721 outs() << " reserved1 " << reserved1;
3722 if (section_type == MachO::S_SYMBOL_STUBS ||
3723 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3724 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3725 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3726 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
3727 outs() << " (index into indirect symbol table)\n";
3730 outs() << " reserved2 " << reserved2;
3731 if (section_type == MachO::S_SYMBOL_STUBS)
3732 outs() << " (size of stubs)\n";
3737 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
3738 uint32_t object_size) {
3739 outs() << " cmd LC_SYMTAB\n";
3740 outs() << " cmdsize " << st.cmdsize;
3741 if (st.cmdsize != sizeof(struct MachO::symtab_command))
3742 outs() << " Incorrect size\n";
3745 outs() << " symoff " << st.symoff;
3746 if (st.symoff > object_size)
3747 outs() << " (past end of file)\n";
3750 outs() << " nsyms " << st.nsyms;
3753 big_size = st.nsyms;
3754 big_size *= sizeof(struct MachO::nlist_64);
3755 big_size += st.symoff;
3756 if (big_size > object_size)
3757 outs() << " (past end of file)\n";
3761 big_size = st.nsyms;
3762 big_size *= sizeof(struct MachO::nlist);
3763 big_size += st.symoff;
3764 if (big_size > object_size)
3765 outs() << " (past end of file)\n";
3769 outs() << " stroff " << st.stroff;
3770 if (st.stroff > object_size)
3771 outs() << " (past end of file)\n";
3774 outs() << " strsize " << st.strsize;
3775 big_size = st.stroff;
3776 big_size += st.strsize;
3777 if (big_size > object_size)
3778 outs() << " (past end of file)\n";
3783 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
3784 uint32_t nsyms, uint32_t object_size,
3786 outs() << " cmd LC_DYSYMTAB\n";
3787 outs() << " cmdsize " << dyst.cmdsize;
3788 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
3789 outs() << " Incorrect size\n";
3792 outs() << " ilocalsym " << dyst.ilocalsym;
3793 if (dyst.ilocalsym > nsyms)
3794 outs() << " (greater than the number of symbols)\n";
3797 outs() << " nlocalsym " << dyst.nlocalsym;
3799 big_size = dyst.ilocalsym;
3800 big_size += dyst.nlocalsym;
3801 if (big_size > nsyms)
3802 outs() << " (past the end of the symbol table)\n";
3805 outs() << " iextdefsym " << dyst.iextdefsym;
3806 if (dyst.iextdefsym > nsyms)
3807 outs() << " (greater than the number of symbols)\n";
3810 outs() << " nextdefsym " << dyst.nextdefsym;
3811 big_size = dyst.iextdefsym;
3812 big_size += dyst.nextdefsym;
3813 if (big_size > nsyms)
3814 outs() << " (past the end of the symbol table)\n";
3817 outs() << " iundefsym " << dyst.iundefsym;
3818 if (dyst.iundefsym > nsyms)
3819 outs() << " (greater than the number of symbols)\n";
3822 outs() << " nundefsym " << dyst.nundefsym;
3823 big_size = dyst.iundefsym;
3824 big_size += dyst.nundefsym;
3825 if (big_size > nsyms)
3826 outs() << " (past the end of the symbol table)\n";
3829 outs() << " tocoff " << dyst.tocoff;
3830 if (dyst.tocoff > object_size)
3831 outs() << " (past end of file)\n";
3834 outs() << " ntoc " << dyst.ntoc;
3835 big_size = dyst.ntoc;
3836 big_size *= sizeof(struct MachO::dylib_table_of_contents);
3837 big_size += dyst.tocoff;
3838 if (big_size > object_size)
3839 outs() << " (past end of file)\n";
3842 outs() << " modtaboff " << dyst.modtaboff;
3843 if (dyst.modtaboff > object_size)
3844 outs() << " (past end of file)\n";
3847 outs() << " nmodtab " << dyst.nmodtab;
3850 modtabend = dyst.nmodtab;
3851 modtabend *= sizeof(struct MachO::dylib_module_64);
3852 modtabend += dyst.modtaboff;
3854 modtabend = dyst.nmodtab;
3855 modtabend *= sizeof(struct MachO::dylib_module);
3856 modtabend += dyst.modtaboff;
3858 if (modtabend > object_size)
3859 outs() << " (past end of file)\n";
3862 outs() << " extrefsymoff " << dyst.extrefsymoff;
3863 if (dyst.extrefsymoff > object_size)
3864 outs() << " (past end of file)\n";
3867 outs() << " nextrefsyms " << dyst.nextrefsyms;
3868 big_size = dyst.nextrefsyms;
3869 big_size *= sizeof(struct MachO::dylib_reference);
3870 big_size += dyst.extrefsymoff;
3871 if (big_size > object_size)
3872 outs() << " (past end of file)\n";
3875 outs() << " indirectsymoff " << dyst.indirectsymoff;
3876 if (dyst.indirectsymoff > object_size)
3877 outs() << " (past end of file)\n";
3880 outs() << " nindirectsyms " << dyst.nindirectsyms;
3881 big_size = dyst.nindirectsyms;
3882 big_size *= sizeof(uint32_t);
3883 big_size += dyst.indirectsymoff;
3884 if (big_size > object_size)
3885 outs() << " (past end of file)\n";
3888 outs() << " extreloff " << dyst.extreloff;
3889 if (dyst.extreloff > object_size)
3890 outs() << " (past end of file)\n";
3893 outs() << " nextrel " << dyst.nextrel;
3894 big_size = dyst.nextrel;
3895 big_size *= sizeof(struct MachO::relocation_info);
3896 big_size += dyst.extreloff;
3897 if (big_size > object_size)
3898 outs() << " (past end of file)\n";
3901 outs() << " locreloff " << dyst.locreloff;
3902 if (dyst.locreloff > object_size)
3903 outs() << " (past end of file)\n";
3906 outs() << " nlocrel " << dyst.nlocrel;
3907 big_size = dyst.nlocrel;
3908 big_size *= sizeof(struct MachO::relocation_info);
3909 big_size += dyst.locreloff;
3910 if (big_size > object_size)
3911 outs() << " (past end of file)\n";
3916 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
3917 uint32_t object_size) {
3918 if (dc.cmd == MachO::LC_DYLD_INFO)
3919 outs() << " cmd LC_DYLD_INFO\n";
3921 outs() << " cmd LC_DYLD_INFO_ONLY\n";
3922 outs() << " cmdsize " << dc.cmdsize;
3923 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
3924 outs() << " Incorrect size\n";
3927 outs() << " rebase_off " << dc.rebase_off;
3928 if (dc.rebase_off > object_size)
3929 outs() << " (past end of file)\n";
3932 outs() << " rebase_size " << dc.rebase_size;
3934 big_size = dc.rebase_off;
3935 big_size += dc.rebase_size;
3936 if (big_size > object_size)
3937 outs() << " (past end of file)\n";
3940 outs() << " bind_off " << dc.bind_off;
3941 if (dc.bind_off > object_size)
3942 outs() << " (past end of file)\n";
3945 outs() << " bind_size " << dc.bind_size;
3946 big_size = dc.bind_off;
3947 big_size += dc.bind_size;
3948 if (big_size > object_size)
3949 outs() << " (past end of file)\n";
3952 outs() << " weak_bind_off " << dc.weak_bind_off;
3953 if (dc.weak_bind_off > object_size)
3954 outs() << " (past end of file)\n";
3957 outs() << " weak_bind_size " << dc.weak_bind_size;
3958 big_size = dc.weak_bind_off;
3959 big_size += dc.weak_bind_size;
3960 if (big_size > object_size)
3961 outs() << " (past end of file)\n";
3964 outs() << " lazy_bind_off " << dc.lazy_bind_off;
3965 if (dc.lazy_bind_off > object_size)
3966 outs() << " (past end of file)\n";
3969 outs() << " lazy_bind_size " << dc.lazy_bind_size;
3970 big_size = dc.lazy_bind_off;
3971 big_size += dc.lazy_bind_size;
3972 if (big_size > object_size)
3973 outs() << " (past end of file)\n";
3976 outs() << " export_off " << dc.export_off;
3977 if (dc.export_off > object_size)
3978 outs() << " (past end of file)\n";
3981 outs() << " export_size " << dc.export_size;
3982 big_size = dc.export_off;
3983 big_size += dc.export_size;
3984 if (big_size > object_size)
3985 outs() << " (past end of file)\n";
3990 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
3992 if (dyld.cmd == MachO::LC_ID_DYLINKER)
3993 outs() << " cmd LC_ID_DYLINKER\n";
3994 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
3995 outs() << " cmd LC_LOAD_DYLINKER\n";
3996 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
3997 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
3999 outs() << " cmd ?(" << dyld.cmd << ")\n";
4000 outs() << " cmdsize " << dyld.cmdsize;
4001 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
4002 outs() << " Incorrect size\n";
4005 if (dyld.name >= dyld.cmdsize)
4006 outs() << " name ?(bad offset " << dyld.name << ")\n";
4008 const char *P = (const char *)(Ptr) + dyld.name;
4009 outs() << " name " << P << " (offset " << dyld.name << ")\n";
4013 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
4014 outs() << " cmd LC_UUID\n";
4015 outs() << " cmdsize " << uuid.cmdsize;
4016 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
4017 outs() << " Incorrect size\n";
4021 outs() << format("%02" PRIX32, uuid.uuid[0]);
4022 outs() << format("%02" PRIX32, uuid.uuid[1]);
4023 outs() << format("%02" PRIX32, uuid.uuid[2]);
4024 outs() << format("%02" PRIX32, uuid.uuid[3]);
4026 outs() << format("%02" PRIX32, uuid.uuid[4]);
4027 outs() << format("%02" PRIX32, uuid.uuid[5]);
4029 outs() << format("%02" PRIX32, uuid.uuid[6]);
4030 outs() << format("%02" PRIX32, uuid.uuid[7]);
4032 outs() << format("%02" PRIX32, uuid.uuid[8]);
4033 outs() << format("%02" PRIX32, uuid.uuid[9]);
4035 outs() << format("%02" PRIX32, uuid.uuid[10]);
4036 outs() << format("%02" PRIX32, uuid.uuid[11]);
4037 outs() << format("%02" PRIX32, uuid.uuid[12]);
4038 outs() << format("%02" PRIX32, uuid.uuid[13]);
4039 outs() << format("%02" PRIX32, uuid.uuid[14]);
4040 outs() << format("%02" PRIX32, uuid.uuid[15]);
4044 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
4045 outs() << " cmd LC_RPATH\n";
4046 outs() << " cmdsize " << rpath.cmdsize;
4047 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
4048 outs() << " Incorrect size\n";
4051 if (rpath.path >= rpath.cmdsize)
4052 outs() << " path ?(bad offset " << rpath.path << ")\n";
4054 const char *P = (const char *)(Ptr) + rpath.path;
4055 outs() << " path " << P << " (offset " << rpath.path << ")\n";
4059 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
4060 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
4061 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
4062 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
4063 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
4065 outs() << " cmd " << vd.cmd << " (?)\n";
4066 outs() << " cmdsize " << vd.cmdsize;
4067 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
4068 outs() << " Incorrect size\n";
4071 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
4072 << ((vd.version >> 8) & 0xff);
4073 if ((vd.version & 0xff) != 0)
4074 outs() << "." << (vd.version & 0xff);
4077 outs() << " sdk n/a";
4079 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
4080 << ((vd.sdk >> 8) & 0xff);
4082 if ((vd.sdk & 0xff) != 0)
4083 outs() << "." << (vd.sdk & 0xff);
4087 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
4088 outs() << " cmd LC_SOURCE_VERSION\n";
4089 outs() << " cmdsize " << sd.cmdsize;
4090 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
4091 outs() << " Incorrect size\n";
4094 uint64_t a = (sd.version >> 40) & 0xffffff;
4095 uint64_t b = (sd.version >> 30) & 0x3ff;
4096 uint64_t c = (sd.version >> 20) & 0x3ff;
4097 uint64_t d = (sd.version >> 10) & 0x3ff;
4098 uint64_t e = sd.version & 0x3ff;
4099 outs() << " version " << a << "." << b;
4101 outs() << "." << c << "." << d << "." << e;
4103 outs() << "." << c << "." << d;
4109 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
4110 outs() << " cmd LC_MAIN\n";
4111 outs() << " cmdsize " << ep.cmdsize;
4112 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
4113 outs() << " Incorrect size\n";
4116 outs() << " entryoff " << ep.entryoff << "\n";
4117 outs() << " stacksize " << ep.stacksize << "\n";
4120 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
4121 uint32_t object_size) {
4122 outs() << " cmd LC_ENCRYPTION_INFO\n";
4123 outs() << " cmdsize " << ec.cmdsize;
4124 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
4125 outs() << " Incorrect size\n";
4128 outs() << " cryptoff " << ec.cryptoff;
4129 if (ec.cryptoff > object_size)
4130 outs() << " (past end of file)\n";
4133 outs() << " cryptsize " << ec.cryptsize;
4134 if (ec.cryptsize > object_size)
4135 outs() << " (past end of file)\n";
4138 outs() << " cryptid " << ec.cryptid << "\n";
4141 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
4142 uint32_t object_size) {
4143 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
4144 outs() << " cmdsize " << ec.cmdsize;
4145 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
4146 outs() << " Incorrect size\n";
4149 outs() << " cryptoff " << ec.cryptoff;
4150 if (ec.cryptoff > object_size)
4151 outs() << " (past end of file)\n";
4154 outs() << " cryptsize " << ec.cryptsize;
4155 if (ec.cryptsize > object_size)
4156 outs() << " (past end of file)\n";
4159 outs() << " cryptid " << ec.cryptid << "\n";
4160 outs() << " pad " << ec.pad << "\n";
4163 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
4165 outs() << " cmd LC_LINKER_OPTION\n";
4166 outs() << " cmdsize " << lo.cmdsize;
4167 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
4168 outs() << " Incorrect size\n";
4171 outs() << " count " << lo.count << "\n";
4172 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
4173 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
4176 while (*string == '\0' && left > 0) {
4182 outs() << " string #" << i << " " << format("%.*s\n", left, string);
4183 uint32_t NullPos = StringRef(string, left).find('\0');
4184 uint32_t len = std::min(NullPos, left) + 1;
4190 outs() << " count " << lo.count << " does not match number of strings "
4194 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
4196 outs() << " cmd LC_SUB_FRAMEWORK\n";
4197 outs() << " cmdsize " << sub.cmdsize;
4198 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
4199 outs() << " Incorrect size\n";
4202 if (sub.umbrella < sub.cmdsize) {
4203 const char *P = Ptr + sub.umbrella;
4204 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
4206 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
4210 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
4212 outs() << " cmd LC_SUB_UMBRELLA\n";
4213 outs() << " cmdsize " << sub.cmdsize;
4214 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
4215 outs() << " Incorrect size\n";
4218 if (sub.sub_umbrella < sub.cmdsize) {
4219 const char *P = Ptr + sub.sub_umbrella;
4220 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
4222 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
4226 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
4228 outs() << " cmd LC_SUB_LIBRARY\n";
4229 outs() << " cmdsize " << sub.cmdsize;
4230 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
4231 outs() << " Incorrect size\n";
4234 if (sub.sub_library < sub.cmdsize) {
4235 const char *P = Ptr + sub.sub_library;
4236 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
4238 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
4242 static void PrintSubClientCommand(MachO::sub_client_command sub,
4244 outs() << " cmd LC_SUB_CLIENT\n";
4245 outs() << " cmdsize " << sub.cmdsize;
4246 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
4247 outs() << " Incorrect size\n";
4250 if (sub.client < sub.cmdsize) {
4251 const char *P = Ptr + sub.client;
4252 outs() << " client " << P << " (offset " << sub.client << ")\n";
4254 outs() << " client ?(bad offset " << sub.client << ")\n";
4258 static void PrintRoutinesCommand(MachO::routines_command r) {
4259 outs() << " cmd LC_ROUTINES\n";
4260 outs() << " cmdsize " << r.cmdsize;
4261 if (r.cmdsize != sizeof(struct MachO::routines_command))
4262 outs() << " Incorrect size\n";
4265 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
4266 outs() << " init_module " << r.init_module << "\n";
4267 outs() << " reserved1 " << r.reserved1 << "\n";
4268 outs() << " reserved2 " << r.reserved2 << "\n";
4269 outs() << " reserved3 " << r.reserved3 << "\n";
4270 outs() << " reserved4 " << r.reserved4 << "\n";
4271 outs() << " reserved5 " << r.reserved5 << "\n";
4272 outs() << " reserved6 " << r.reserved6 << "\n";
4275 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
4276 outs() << " cmd LC_ROUTINES_64\n";
4277 outs() << " cmdsize " << r.cmdsize;
4278 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
4279 outs() << " Incorrect size\n";
4282 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
4283 outs() << " init_module " << r.init_module << "\n";
4284 outs() << " reserved1 " << r.reserved1 << "\n";
4285 outs() << " reserved2 " << r.reserved2 << "\n";
4286 outs() << " reserved3 " << r.reserved3 << "\n";
4287 outs() << " reserved4 " << r.reserved4 << "\n";
4288 outs() << " reserved5 " << r.reserved5 << "\n";
4289 outs() << " reserved6 " << r.reserved6 << "\n";
4292 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4293 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
4294 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4295 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4296 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
4297 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4298 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4299 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
4300 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4301 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4302 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
4303 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4304 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4305 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
4306 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4307 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4308 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
4309 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4310 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
4311 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
4312 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4313 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
4316 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
4318 outs() << "\t mmst_reg ";
4319 for (f = 0; f < 10; f++)
4320 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
4322 outs() << "\t mmst_rsrv ";
4323 for (f = 0; f < 6; f++)
4324 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
4328 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
4330 outs() << "\t xmm_reg ";
4331 for (f = 0; f < 16; f++)
4332 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
4336 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
4337 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
4338 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
4339 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
4340 outs() << " denorm " << fpu.fpu_fcw.denorm;
4341 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
4342 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
4343 outs() << " undfl " << fpu.fpu_fcw.undfl;
4344 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
4345 outs() << "\t\t pc ";
4346 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
4347 outs() << "FP_PREC_24B ";
4348 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
4349 outs() << "FP_PREC_53B ";
4350 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
4351 outs() << "FP_PREC_64B ";
4353 outs() << fpu.fpu_fcw.pc << " ";
4355 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
4356 outs() << "FP_RND_NEAR ";
4357 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
4358 outs() << "FP_RND_DOWN ";
4359 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
4360 outs() << "FP_RND_UP ";
4361 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
4362 outs() << "FP_CHOP ";
4364 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
4365 outs() << " denorm " << fpu.fpu_fsw.denorm;
4366 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
4367 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
4368 outs() << " undfl " << fpu.fpu_fsw.undfl;
4369 outs() << " precis " << fpu.fpu_fsw.precis;
4370 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
4371 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
4372 outs() << " c0 " << fpu.fpu_fsw.c0;
4373 outs() << " c1 " << fpu.fpu_fsw.c1;
4374 outs() << " c2 " << fpu.fpu_fsw.c2;
4375 outs() << " tos " << fpu.fpu_fsw.tos;
4376 outs() << " c3 " << fpu.fpu_fsw.c3;
4377 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
4378 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
4379 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
4380 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
4381 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
4382 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
4383 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
4384 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
4385 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
4386 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
4387 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
4388 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
4390 outs() << "\t fpu_stmm0:\n";
4391 Print_mmst_reg(fpu.fpu_stmm0);
4392 outs() << "\t fpu_stmm1:\n";
4393 Print_mmst_reg(fpu.fpu_stmm1);
4394 outs() << "\t fpu_stmm2:\n";
4395 Print_mmst_reg(fpu.fpu_stmm2);
4396 outs() << "\t fpu_stmm3:\n";
4397 Print_mmst_reg(fpu.fpu_stmm3);
4398 outs() << "\t fpu_stmm4:\n";
4399 Print_mmst_reg(fpu.fpu_stmm4);
4400 outs() << "\t fpu_stmm5:\n";
4401 Print_mmst_reg(fpu.fpu_stmm5);
4402 outs() << "\t fpu_stmm6:\n";
4403 Print_mmst_reg(fpu.fpu_stmm6);
4404 outs() << "\t fpu_stmm7:\n";
4405 Print_mmst_reg(fpu.fpu_stmm7);
4406 outs() << "\t fpu_xmm0:\n";
4407 Print_xmm_reg(fpu.fpu_xmm0);
4408 outs() << "\t fpu_xmm1:\n";
4409 Print_xmm_reg(fpu.fpu_xmm1);
4410 outs() << "\t fpu_xmm2:\n";
4411 Print_xmm_reg(fpu.fpu_xmm2);
4412 outs() << "\t fpu_xmm3:\n";
4413 Print_xmm_reg(fpu.fpu_xmm3);
4414 outs() << "\t fpu_xmm4:\n";
4415 Print_xmm_reg(fpu.fpu_xmm4);
4416 outs() << "\t fpu_xmm5:\n";
4417 Print_xmm_reg(fpu.fpu_xmm5);
4418 outs() << "\t fpu_xmm6:\n";
4419 Print_xmm_reg(fpu.fpu_xmm6);
4420 outs() << "\t fpu_xmm7:\n";
4421 Print_xmm_reg(fpu.fpu_xmm7);
4422 outs() << "\t fpu_xmm8:\n";
4423 Print_xmm_reg(fpu.fpu_xmm8);
4424 outs() << "\t fpu_xmm9:\n";
4425 Print_xmm_reg(fpu.fpu_xmm9);
4426 outs() << "\t fpu_xmm10:\n";
4427 Print_xmm_reg(fpu.fpu_xmm10);
4428 outs() << "\t fpu_xmm11:\n";
4429 Print_xmm_reg(fpu.fpu_xmm11);
4430 outs() << "\t fpu_xmm12:\n";
4431 Print_xmm_reg(fpu.fpu_xmm12);
4432 outs() << "\t fpu_xmm13:\n";
4433 Print_xmm_reg(fpu.fpu_xmm13);
4434 outs() << "\t fpu_xmm14:\n";
4435 Print_xmm_reg(fpu.fpu_xmm14);
4436 outs() << "\t fpu_xmm15:\n";
4437 Print_xmm_reg(fpu.fpu_xmm15);
4438 outs() << "\t fpu_rsrv4:\n";
4439 for (uint32_t f = 0; f < 6; f++) {
4441 for (uint32_t g = 0; g < 16; g++)
4442 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
4445 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
4449 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
4450 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
4451 outs() << " err " << format("0x%08" PRIx32, exc64.err);
4452 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
4455 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
4456 bool isLittleEndian, uint32_t cputype) {
4457 if (t.cmd == MachO::LC_THREAD)
4458 outs() << " cmd LC_THREAD\n";
4459 else if (t.cmd == MachO::LC_UNIXTHREAD)
4460 outs() << " cmd LC_UNIXTHREAD\n";
4462 outs() << " cmd " << t.cmd << " (unknown)\n";
4463 outs() << " cmdsize " << t.cmdsize;
4464 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
4465 outs() << " Incorrect size\n";
4469 const char *begin = Ptr + sizeof(struct MachO::thread_command);
4470 const char *end = Ptr + t.cmdsize;
4471 uint32_t flavor, count, left;
4472 if (cputype == MachO::CPU_TYPE_X86_64) {
4473 while (begin < end) {
4474 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4475 memcpy((char *)&flavor, begin, sizeof(uint32_t));
4476 begin += sizeof(uint32_t);
4481 if (isLittleEndian != sys::IsLittleEndianHost)
4482 sys::swapByteOrder(flavor);
4483 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4484 memcpy((char *)&count, begin, sizeof(uint32_t));
4485 begin += sizeof(uint32_t);
4490 if (isLittleEndian != sys::IsLittleEndianHost)
4491 sys::swapByteOrder(count);
4492 if (flavor == MachO::x86_THREAD_STATE64) {
4493 outs() << " flavor x86_THREAD_STATE64\n";
4494 if (count == MachO::x86_THREAD_STATE64_COUNT)
4495 outs() << " count x86_THREAD_STATE64_COUNT\n";
4497 outs() << " count " << count
4498 << " (not x86_THREAD_STATE64_COUNT)\n";
4499 MachO::x86_thread_state64_t cpu64;
4501 if (left >= sizeof(MachO::x86_thread_state64_t)) {
4502 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
4503 begin += sizeof(MachO::x86_thread_state64_t);
4505 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
4506 memcpy(&cpu64, begin, left);
4509 if (isLittleEndian != sys::IsLittleEndianHost)
4511 Print_x86_thread_state64_t(cpu64);
4512 } else if (flavor == MachO::x86_THREAD_STATE) {
4513 outs() << " flavor x86_THREAD_STATE\n";
4514 if (count == MachO::x86_THREAD_STATE_COUNT)
4515 outs() << " count x86_THREAD_STATE_COUNT\n";
4517 outs() << " count " << count
4518 << " (not x86_THREAD_STATE_COUNT)\n";
4519 struct MachO::x86_thread_state_t ts;
4521 if (left >= sizeof(MachO::x86_thread_state_t)) {
4522 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
4523 begin += sizeof(MachO::x86_thread_state_t);
4525 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
4526 memcpy(&ts, begin, left);
4529 if (isLittleEndian != sys::IsLittleEndianHost)
4531 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
4532 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
4533 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
4534 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
4536 outs() << "tsh.count " << ts.tsh.count
4537 << " (not x86_THREAD_STATE64_COUNT\n";
4538 Print_x86_thread_state64_t(ts.uts.ts64);
4540 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
4541 << ts.tsh.count << "\n";
4543 } else if (flavor == MachO::x86_FLOAT_STATE) {
4544 outs() << " flavor x86_FLOAT_STATE\n";
4545 if (count == MachO::x86_FLOAT_STATE_COUNT)
4546 outs() << " count x86_FLOAT_STATE_COUNT\n";
4548 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
4549 struct MachO::x86_float_state_t fs;
4551 if (left >= sizeof(MachO::x86_float_state_t)) {
4552 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
4553 begin += sizeof(MachO::x86_float_state_t);
4555 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
4556 memcpy(&fs, begin, left);
4559 if (isLittleEndian != sys::IsLittleEndianHost)
4561 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
4562 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
4563 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
4564 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
4566 outs() << "fsh.count " << fs.fsh.count
4567 << " (not x86_FLOAT_STATE64_COUNT\n";
4568 Print_x86_float_state_t(fs.ufs.fs64);
4570 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
4571 << fs.fsh.count << "\n";
4573 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
4574 outs() << " flavor x86_EXCEPTION_STATE\n";
4575 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
4576 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
4578 outs() << " count " << count
4579 << " (not x86_EXCEPTION_STATE_COUNT)\n";
4580 struct MachO::x86_exception_state_t es;
4582 if (left >= sizeof(MachO::x86_exception_state_t)) {
4583 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
4584 begin += sizeof(MachO::x86_exception_state_t);
4586 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
4587 memcpy(&es, begin, left);
4590 if (isLittleEndian != sys::IsLittleEndianHost)
4592 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
4593 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
4594 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
4595 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
4597 outs() << "\t esh.count " << es.esh.count
4598 << " (not x86_EXCEPTION_STATE64_COUNT\n";
4599 Print_x86_exception_state_t(es.ues.es64);
4601 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
4602 << es.esh.count << "\n";
4605 outs() << " flavor " << flavor << " (unknown)\n";
4606 outs() << " count " << count << "\n";
4607 outs() << " state (unknown)\n";
4608 begin += count * sizeof(uint32_t);
4612 while (begin < end) {
4613 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4614 memcpy((char *)&flavor, begin, sizeof(uint32_t));
4615 begin += sizeof(uint32_t);
4620 if (isLittleEndian != sys::IsLittleEndianHost)
4621 sys::swapByteOrder(flavor);
4622 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4623 memcpy((char *)&count, begin, sizeof(uint32_t));
4624 begin += sizeof(uint32_t);
4629 if (isLittleEndian != sys::IsLittleEndianHost)
4630 sys::swapByteOrder(count);
4631 outs() << " flavor " << flavor << "\n";
4632 outs() << " count " << count << "\n";
4633 outs() << " state (Unknown cputype/cpusubtype)\n";
4634 begin += count * sizeof(uint32_t);
4639 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
4640 if (dl.cmd == MachO::LC_ID_DYLIB)
4641 outs() << " cmd LC_ID_DYLIB\n";
4642 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
4643 outs() << " cmd LC_LOAD_DYLIB\n";
4644 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
4645 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
4646 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
4647 outs() << " cmd LC_REEXPORT_DYLIB\n";
4648 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
4649 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
4650 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
4651 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
4653 outs() << " cmd " << dl.cmd << " (unknown)\n";
4654 outs() << " cmdsize " << dl.cmdsize;
4655 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
4656 outs() << " Incorrect size\n";
4659 if (dl.dylib.name < dl.cmdsize) {
4660 const char *P = (const char *)(Ptr) + dl.dylib.name;
4661 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
4663 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
4665 outs() << " time stamp " << dl.dylib.timestamp << " ";
4666 time_t t = dl.dylib.timestamp;
4667 outs() << ctime(&t);
4668 outs() << " current version ";
4669 if (dl.dylib.current_version == 0xffffffff)
4672 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
4673 << ((dl.dylib.current_version >> 8) & 0xff) << "."
4674 << (dl.dylib.current_version & 0xff) << "\n";
4675 outs() << "compatibility version ";
4676 if (dl.dylib.compatibility_version == 0xffffffff)
4679 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
4680 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
4681 << (dl.dylib.compatibility_version & 0xff) << "\n";
4684 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
4685 uint32_t object_size) {
4686 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
4687 outs() << " cmd LC_FUNCTION_STARTS\n";
4688 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
4689 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
4690 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
4691 outs() << " cmd LC_FUNCTION_STARTS\n";
4692 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
4693 outs() << " cmd LC_DATA_IN_CODE\n";
4694 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
4695 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
4696 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
4697 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
4699 outs() << " cmd " << ld.cmd << " (?)\n";
4700 outs() << " cmdsize " << ld.cmdsize;
4701 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
4702 outs() << " Incorrect size\n";
4705 outs() << " dataoff " << ld.dataoff;
4706 if (ld.dataoff > object_size)
4707 outs() << " (past end of file)\n";
4710 outs() << " datasize " << ld.datasize;
4711 uint64_t big_size = ld.dataoff;
4712 big_size += ld.datasize;
4713 if (big_size > object_size)
4714 outs() << " (past end of file)\n";
4719 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
4720 uint32_t filetype, uint32_t cputype,
4724 StringRef Buf = Obj->getData();
4725 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
4726 for (unsigned i = 0;; ++i) {
4727 outs() << "Load command " << i << "\n";
4728 if (Command.C.cmd == MachO::LC_SEGMENT) {
4729 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
4730 const char *sg_segname = SLC.segname;
4731 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
4732 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
4733 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
4735 for (unsigned j = 0; j < SLC.nsects; j++) {
4736 MachO::section S = Obj->getSection(Command, j);
4737 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
4738 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
4739 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
4741 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
4742 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
4743 const char *sg_segname = SLC_64.segname;
4744 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
4745 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
4746 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
4747 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
4748 for (unsigned j = 0; j < SLC_64.nsects; j++) {
4749 MachO::section_64 S_64 = Obj->getSection64(Command, j);
4750 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
4751 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
4752 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
4753 sg_segname, filetype, Buf.size(), verbose);
4755 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
4756 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
4757 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
4758 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
4759 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
4760 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
4761 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
4763 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
4764 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
4765 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
4766 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
4767 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
4768 Command.C.cmd == MachO::LC_ID_DYLINKER ||
4769 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
4770 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
4771 PrintDyldLoadCommand(Dyld, Command.Ptr);
4772 } else if (Command.C.cmd == MachO::LC_UUID) {
4773 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
4774 PrintUuidLoadCommand(Uuid);
4775 } else if (Command.C.cmd == MachO::LC_RPATH) {
4776 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
4777 PrintRpathLoadCommand(Rpath, Command.Ptr);
4778 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
4779 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
4780 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
4781 PrintVersionMinLoadCommand(Vd);
4782 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
4783 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
4784 PrintSourceVersionCommand(Sd);
4785 } else if (Command.C.cmd == MachO::LC_MAIN) {
4786 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
4787 PrintEntryPointCommand(Ep);
4788 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
4789 MachO::encryption_info_command Ei =
4790 Obj->getEncryptionInfoCommand(Command);
4791 PrintEncryptionInfoCommand(Ei, Buf.size());
4792 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
4793 MachO::encryption_info_command_64 Ei =
4794 Obj->getEncryptionInfoCommand64(Command);
4795 PrintEncryptionInfoCommand64(Ei, Buf.size());
4796 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
4797 MachO::linker_option_command Lo =
4798 Obj->getLinkerOptionLoadCommand(Command);
4799 PrintLinkerOptionCommand(Lo, Command.Ptr);
4800 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
4801 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
4802 PrintSubFrameworkCommand(Sf, Command.Ptr);
4803 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
4804 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
4805 PrintSubUmbrellaCommand(Sf, Command.Ptr);
4806 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
4807 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
4808 PrintSubLibraryCommand(Sl, Command.Ptr);
4809 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
4810 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
4811 PrintSubClientCommand(Sc, Command.Ptr);
4812 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
4813 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
4814 PrintRoutinesCommand(Rc);
4815 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
4816 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
4817 PrintRoutinesCommand64(Rc);
4818 } else if (Command.C.cmd == MachO::LC_THREAD ||
4819 Command.C.cmd == MachO::LC_UNIXTHREAD) {
4820 MachO::thread_command Tc = Obj->getThreadCommand(Command);
4821 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
4822 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
4823 Command.C.cmd == MachO::LC_ID_DYLIB ||
4824 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
4825 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
4826 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
4827 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
4828 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
4829 PrintDylibCommand(Dl, Command.Ptr);
4830 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
4831 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
4832 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
4833 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
4834 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
4835 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
4836 MachO::linkedit_data_command Ld =
4837 Obj->getLinkeditDataLoadCommand(Command);
4838 PrintLinkEditDataCommand(Ld, Buf.size());
4840 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
4842 outs() << " cmdsize " << Command.C.cmdsize << "\n";
4843 // TODO: get and print the raw bytes of the load command.
4845 // TODO: print all the other kinds of load commands.
4849 Command = Obj->getNextLoadCommandInfo(Command);
4853 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
4854 uint32_t &filetype, uint32_t &cputype,
4856 if (Obj->is64Bit()) {
4857 MachO::mach_header_64 H_64;
4858 H_64 = Obj->getHeader64();
4859 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
4860 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
4862 filetype = H_64.filetype;
4863 cputype = H_64.cputype;
4865 MachO::mach_header H;
4866 H = Obj->getHeader();
4867 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
4868 H.sizeofcmds, H.flags, verbose);
4870 filetype = H.filetype;
4871 cputype = H.cputype;
4875 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
4876 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
4878 uint32_t filetype = 0;
4879 uint32_t cputype = 0;
4880 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
4881 PrintLoadCommands(file, ncmds, filetype, cputype, true);
4884 //===----------------------------------------------------------------------===//
4885 // export trie dumping
4886 //===----------------------------------------------------------------------===//
4888 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
4889 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
4890 uint64_t Flags = Entry.flags();
4891 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
4892 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
4893 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
4894 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
4895 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
4896 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
4897 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
4899 outs() << "[re-export] ";
4901 outs() << format("0x%08llX ",
4902 Entry.address()); // FIXME:add in base address
4903 outs() << Entry.name();
4904 if (WeakDef || ThreadLocal || Resolver || Abs) {
4905 bool NeedsComma = false;
4908 outs() << "weak_def";
4914 outs() << "per-thread";
4920 outs() << "absolute";
4926 outs() << format("resolver=0x%08llX", Entry.other());
4932 StringRef DylibName = "unknown";
4933 int Ordinal = Entry.other() - 1;
4934 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
4935 if (Entry.otherName().empty())
4936 outs() << " (from " << DylibName << ")";
4938 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
4944 //===----------------------------------------------------------------------===//
4945 // rebase table dumping
4946 //===----------------------------------------------------------------------===//
4951 SegInfo(const object::MachOObjectFile *Obj);
4953 StringRef segmentName(uint32_t SegIndex);
4954 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
4955 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
4958 struct SectionInfo {
4961 StringRef SectionName;
4962 StringRef SegmentName;
4963 uint64_t OffsetInSegment;
4964 uint64_t SegmentStartAddress;
4965 uint32_t SegmentIndex;
4967 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
4968 SmallVector<SectionInfo, 32> Sections;
4972 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
4973 // Build table of sections so segIndex/offset pairs can be translated.
4974 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
4975 StringRef CurSegName;
4976 uint64_t CurSegAddress;
4977 for (const SectionRef &Section : Obj->sections()) {
4979 if (error(Section.getName(Info.SectionName)))
4981 Info.Address = Section.getAddress();
4982 Info.Size = Section.getSize();
4984 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
4985 if (!Info.SegmentName.equals(CurSegName)) {
4987 CurSegName = Info.SegmentName;
4988 CurSegAddress = Info.Address;
4990 Info.SegmentIndex = CurSegIndex - 1;
4991 Info.OffsetInSegment = Info.Address - CurSegAddress;
4992 Info.SegmentStartAddress = CurSegAddress;
4993 Sections.push_back(Info);
4997 StringRef SegInfo::segmentName(uint32_t SegIndex) {
4998 for (const SectionInfo &SI : Sections) {
4999 if (SI.SegmentIndex == SegIndex)
5000 return SI.SegmentName;
5002 llvm_unreachable("invalid segIndex");
5005 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
5006 uint64_t OffsetInSeg) {
5007 for (const SectionInfo &SI : Sections) {
5008 if (SI.SegmentIndex != SegIndex)
5010 if (SI.OffsetInSegment > OffsetInSeg)
5012 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
5016 llvm_unreachable("segIndex and offset not in any section");
5019 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
5020 return findSection(SegIndex, OffsetInSeg).SectionName;
5023 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
5024 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
5025 return SI.SegmentStartAddress + OffsetInSeg;
5028 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
5029 // Build table of sections so names can used in final output.
5030 SegInfo sectionTable(Obj);
5032 outs() << "segment section address type\n";
5033 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
5034 uint32_t SegIndex = Entry.segmentIndex();
5035 uint64_t OffsetInSeg = Entry.segmentOffset();
5036 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5037 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5038 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5040 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
5041 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
5042 SegmentName.str().c_str(), SectionName.str().c_str(),
5043 Address, Entry.typeName().str().c_str());
5047 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
5048 StringRef DylibName;
5050 case MachO::BIND_SPECIAL_DYLIB_SELF:
5051 return "this-image";
5052 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
5053 return "main-executable";
5054 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
5055 return "flat-namespace";
5058 std::error_code EC =
5059 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
5061 return "<<bad library ordinal>>";
5065 return "<<unknown special ordinal>>";
5068 //===----------------------------------------------------------------------===//
5069 // bind table dumping
5070 //===----------------------------------------------------------------------===//
5072 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
5073 // Build table of sections so names can used in final output.
5074 SegInfo sectionTable(Obj);
5076 outs() << "segment section address type "
5077 "addend dylib symbol\n";
5078 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
5079 uint32_t SegIndex = Entry.segmentIndex();
5080 uint64_t OffsetInSeg = Entry.segmentOffset();
5081 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5082 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5083 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5085 // Table lines look like:
5086 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
5088 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
5089 Attr = " (weak_import)";
5090 outs() << left_justify(SegmentName, 8) << " "
5091 << left_justify(SectionName, 18) << " "
5092 << format_hex(Address, 10, true) << " "
5093 << left_justify(Entry.typeName(), 8) << " "
5094 << format_decimal(Entry.addend(), 8) << " "
5095 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5096 << Entry.symbolName() << Attr << "\n";
5100 //===----------------------------------------------------------------------===//
5101 // lazy bind table dumping
5102 //===----------------------------------------------------------------------===//
5104 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
5105 // Build table of sections so names can used in final output.
5106 SegInfo sectionTable(Obj);
5108 outs() << "segment section address "
5110 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
5111 uint32_t SegIndex = Entry.segmentIndex();
5112 uint64_t OffsetInSeg = Entry.segmentOffset();
5113 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5114 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5115 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5117 // Table lines look like:
5118 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
5119 outs() << left_justify(SegmentName, 8) << " "
5120 << left_justify(SectionName, 18) << " "
5121 << format_hex(Address, 10, true) << " "
5122 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5123 << Entry.symbolName() << "\n";
5127 //===----------------------------------------------------------------------===//
5128 // weak bind table dumping
5129 //===----------------------------------------------------------------------===//
5131 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
5132 // Build table of sections so names can used in final output.
5133 SegInfo sectionTable(Obj);
5135 outs() << "segment section address "
5136 "type addend symbol\n";
5137 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
5138 // Strong symbols don't have a location to update.
5139 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
5140 outs() << " strong "
5141 << Entry.symbolName() << "\n";
5144 uint32_t SegIndex = Entry.segmentIndex();
5145 uint64_t OffsetInSeg = Entry.segmentOffset();
5146 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5147 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5148 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5150 // Table lines look like:
5151 // __DATA __data 0x00001000 pointer 0 _foo
5152 outs() << left_justify(SegmentName, 8) << " "
5153 << left_justify(SectionName, 18) << " "
5154 << format_hex(Address, 10, true) << " "
5155 << left_justify(Entry.typeName(), 8) << " "
5156 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
5161 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
5162 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
5163 // information for that address. If the address is found its binding symbol
5164 // name is returned. If not nullptr is returned.
5165 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
5166 struct DisassembleInfo *info) {
5167 if (info->bindtable == nullptr) {
5168 info->bindtable = new (BindTable);
5169 SegInfo sectionTable(info->O);
5170 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
5171 uint32_t SegIndex = Entry.segmentIndex();
5172 uint64_t OffsetInSeg = Entry.segmentOffset();
5173 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5174 const char *SymbolName = nullptr;
5175 StringRef name = Entry.symbolName();
5177 SymbolName = name.data();
5178 info->bindtable->push_back(std::make_pair(Address, SymbolName));
5181 for (bind_table_iterator BI = info->bindtable->begin(),
5182 BE = info->bindtable->end();
5184 uint64_t Address = BI->first;
5185 if (ReferenceValue == Address) {
5186 const char *SymbolName = BI->second;