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/LEB128.h"
40 #include "llvm/Support/MachO.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/Support/raw_ostream.h"
47 #include <system_error>
54 using namespace object;
58 cl::desc("Print line information from debug info if available"));
60 static cl::opt<std::string> DSYMFile("dsym",
61 cl::desc("Use .dSYM file for debug info"));
63 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
64 cl::desc("Print full leading address"));
67 PrintImmHex("print-imm-hex",
68 cl::desc("Use hex format for immediate values"));
70 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
71 cl::desc("Print Mach-O universal headers "
72 "(requires -macho)"));
75 llvm::ArchiveHeaders("archive-headers",
76 cl::desc("Print archive headers for Mach-O archives "
77 "(requires -macho)"));
80 llvm::IndirectSymbols("indirect-symbols",
81 cl::desc("Print indirect symbol table for Mach-O "
82 "objects (requires -macho)"));
85 llvm::DataInCode("data-in-code",
86 cl::desc("Print the data in code table for Mach-O objects "
87 "(requires -macho)"));
90 llvm::LinkOptHints("link-opt-hints",
91 cl::desc("Print the linker optimization hints for "
92 "Mach-O objects (requires -macho)"));
94 static cl::list<std::string>
95 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
99 static std::string ThumbTripleName;
101 static const Target *GetTarget(const MachOObjectFile *MachOObj,
102 const char **McpuDefault,
103 const Target **ThumbTarget) {
104 // Figure out the target triple.
105 if (TripleName.empty()) {
106 llvm::Triple TT("unknown-unknown-unknown");
107 llvm::Triple ThumbTriple = Triple();
108 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
109 TripleName = TT.str();
110 ThumbTripleName = ThumbTriple.str();
113 // Get the target specific parser.
115 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
116 if (TheTarget && ThumbTripleName.empty())
119 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
123 errs() << "llvm-objdump: error: unable to get target for '";
125 errs() << TripleName;
127 errs() << ThumbTripleName;
128 errs() << "', see --version and --triple.\n";
132 struct SymbolSorter {
133 bool operator()(const SymbolRef &A, const SymbolRef &B) {
134 SymbolRef::Type AType, BType;
138 uint64_t AAddr, BAddr;
139 if (AType != SymbolRef::ST_Function)
143 if (BType != SymbolRef::ST_Function)
147 return AAddr < BAddr;
151 // Types for the storted data in code table that is built before disassembly
152 // and the predicate function to sort them.
153 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
154 typedef std::vector<DiceTableEntry> DiceTable;
155 typedef DiceTable::iterator dice_table_iterator;
157 // This is used to search for a data in code table entry for the PC being
158 // disassembled. The j parameter has the PC in j.first. A single data in code
159 // table entry can cover many bytes for each of its Kind's. So if the offset,
160 // aka the i.first value, of the data in code table entry plus its Length
161 // covers the PC being searched for this will return true. If not it will
163 static bool compareDiceTableEntries(const DiceTableEntry &i,
164 const DiceTableEntry &j) {
166 i.second.getLength(Length);
168 return j.first >= i.first && j.first < i.first + Length;
171 static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
172 unsigned short Kind) {
173 uint32_t Value, Size = 1;
177 case MachO::DICE_KIND_DATA:
180 DumpBytes(StringRef(bytes, 4));
181 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
182 outs() << "\t.long " << Value;
184 } else if (Length >= 2) {
186 DumpBytes(StringRef(bytes, 2));
187 Value = bytes[1] << 8 | bytes[0];
188 outs() << "\t.short " << Value;
192 DumpBytes(StringRef(bytes, 2));
194 outs() << "\t.byte " << Value;
197 if (Kind == MachO::DICE_KIND_DATA)
198 outs() << "\t@ KIND_DATA\n";
200 outs() << "\t@ data in code kind = " << Kind << "\n";
202 case MachO::DICE_KIND_JUMP_TABLE8:
204 DumpBytes(StringRef(bytes, 1));
206 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
209 case MachO::DICE_KIND_JUMP_TABLE16:
211 DumpBytes(StringRef(bytes, 2));
212 Value = bytes[1] << 8 | bytes[0];
213 outs() << "\t.short " << format("%5u", Value & 0xffff)
214 << "\t@ KIND_JUMP_TABLE16\n";
217 case MachO::DICE_KIND_JUMP_TABLE32:
218 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
220 DumpBytes(StringRef(bytes, 4));
221 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
222 outs() << "\t.long " << Value;
223 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
224 outs() << "\t@ KIND_JUMP_TABLE32\n";
226 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
233 static void getSectionsAndSymbols(const MachO::mach_header Header,
234 MachOObjectFile *MachOObj,
235 std::vector<SectionRef> &Sections,
236 std::vector<SymbolRef> &Symbols,
237 SmallVectorImpl<uint64_t> &FoundFns,
238 uint64_t &BaseSegmentAddress) {
239 for (const SymbolRef &Symbol : MachOObj->symbols()) {
241 Symbol.getName(SymName);
242 if (!SymName.startswith("ltmp"))
243 Symbols.push_back(Symbol);
246 for (const SectionRef &Section : MachOObj->sections()) {
248 Section.getName(SectName);
249 Sections.push_back(Section);
252 MachOObjectFile::LoadCommandInfo Command =
253 MachOObj->getFirstLoadCommandInfo();
254 bool BaseSegmentAddressSet = false;
255 for (unsigned i = 0;; ++i) {
256 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
257 // We found a function starts segment, parse the addresses for later
259 MachO::linkedit_data_command LLC =
260 MachOObj->getLinkeditDataLoadCommand(Command);
262 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
263 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
264 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
265 StringRef SegName = SLC.segname;
266 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
267 BaseSegmentAddressSet = true;
268 BaseSegmentAddress = SLC.vmaddr;
272 if (i == Header.ncmds - 1)
275 Command = MachOObj->getNextLoadCommandInfo(Command);
279 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
280 uint32_t n, uint32_t count,
281 uint32_t stride, uint64_t addr) {
282 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
283 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
284 if (n > nindirectsyms)
285 outs() << " (entries start past the end of the indirect symbol "
286 "table) (reserved1 field greater than the table size)";
287 else if (n + count > nindirectsyms)
288 outs() << " (entries extends past the end of the indirect symbol "
291 uint32_t cputype = O->getHeader().cputype;
292 if (cputype & MachO::CPU_ARCH_ABI64)
293 outs() << "address index";
295 outs() << "address index";
300 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
301 if (cputype & MachO::CPU_ARCH_ABI64)
302 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
304 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
305 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
306 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
307 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
311 if (indirect_symbol ==
312 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
313 outs() << "LOCAL ABSOLUTE\n";
316 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
317 outs() << "ABSOLUTE\n";
320 outs() << format("%5u ", indirect_symbol);
321 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
322 if (indirect_symbol < Symtab.nsyms) {
323 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
324 SymbolRef Symbol = *Sym;
326 Symbol.getName(SymName);
335 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
336 uint32_t LoadCommandCount = O->getHeader().ncmds;
337 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
338 for (unsigned I = 0;; ++I) {
339 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
340 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
341 for (unsigned J = 0; J < Seg.nsects; ++J) {
342 MachO::section_64 Sec = O->getSection64(Load, J);
343 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
344 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
345 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
346 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
347 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
348 section_type == MachO::S_SYMBOL_STUBS) {
350 if (section_type == MachO::S_SYMBOL_STUBS)
351 stride = Sec.reserved2;
355 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
356 << Sec.sectname << ") "
357 << "(size of stubs in reserved2 field is zero)\n";
360 uint32_t count = Sec.size / stride;
361 outs() << "Indirect symbols for (" << Sec.segname << ","
362 << Sec.sectname << ") " << count << " entries";
363 uint32_t n = Sec.reserved1;
364 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
367 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
368 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
369 for (unsigned J = 0; J < Seg.nsects; ++J) {
370 MachO::section Sec = O->getSection(Load, J);
371 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
372 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
373 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
374 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
375 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
376 section_type == MachO::S_SYMBOL_STUBS) {
378 if (section_type == MachO::S_SYMBOL_STUBS)
379 stride = Sec.reserved2;
383 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
384 << Sec.sectname << ") "
385 << "(size of stubs in reserved2 field is zero)\n";
388 uint32_t count = Sec.size / stride;
389 outs() << "Indirect symbols for (" << Sec.segname << ","
390 << Sec.sectname << ") " << count << " entries";
391 uint32_t n = Sec.reserved1;
392 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
396 if (I == LoadCommandCount - 1)
399 Load = O->getNextLoadCommandInfo(Load);
403 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
404 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
405 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
406 outs() << "Data in code table (" << nentries << " entries)\n";
407 outs() << "offset length kind\n";
408 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
411 DI->getOffset(Offset);
412 outs() << format("0x%08" PRIx32, Offset) << " ";
414 DI->getLength(Length);
415 outs() << format("%6u", Length) << " ";
420 case MachO::DICE_KIND_DATA:
423 case MachO::DICE_KIND_JUMP_TABLE8:
424 outs() << "JUMP_TABLE8";
426 case MachO::DICE_KIND_JUMP_TABLE16:
427 outs() << "JUMP_TABLE16";
429 case MachO::DICE_KIND_JUMP_TABLE32:
430 outs() << "JUMP_TABLE32";
432 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
433 outs() << "ABS_JUMP_TABLE32";
436 outs() << format("0x%04" PRIx32, Kind);
440 outs() << format("0x%04" PRIx32, Kind);
445 static void PrintLinkOptHints(MachOObjectFile *O) {
446 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
447 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
448 uint32_t nloh = LohLC.datasize;
449 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
450 for (uint32_t i = 0; i < nloh;) {
452 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
454 outs() << " identifier " << identifier << " ";
457 switch (identifier) {
459 outs() << "AdrpAdrp\n";
462 outs() << "AdrpLdr\n";
465 outs() << "AdrpAddLdr\n";
468 outs() << "AdrpLdrGotLdr\n";
471 outs() << "AdrpAddStr\n";
474 outs() << "AdrpLdrGotStr\n";
477 outs() << "AdrpAdd\n";
480 outs() << "AdrpLdrGot\n";
483 outs() << "Unknown identifier value\n";
486 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
488 outs() << " narguments " << narguments << "\n";
492 for (uint32_t j = 0; j < narguments; j++) {
493 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
495 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
502 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
503 // and if it is and there is a list of architecture flags is specified then
504 // check to make sure this Mach-O file is one of those architectures or all
505 // architectures were specified. If not then an error is generated and this
506 // routine returns false. Else it returns true.
507 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
508 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
509 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
510 bool ArchFound = false;
511 MachO::mach_header H;
512 MachO::mach_header_64 H_64;
514 if (MachO->is64Bit()) {
515 H_64 = MachO->MachOObjectFile::getHeader64();
516 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
518 H = MachO->MachOObjectFile::getHeader();
519 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
522 for (i = 0; i < ArchFlags.size(); ++i) {
523 if (ArchFlags[i] == T.getArchName())
528 errs() << "llvm-objdump: file: " + Filename + " does not contain "
529 << "architecture: " + ArchFlags[i] + "\n";
536 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF);
538 // ProcessMachO() is passed a single opened Mach-O file, which may be an
539 // archive member and or in a slice of a universal file. It prints the
540 // the file name and header info and then processes it according to the
541 // command line options.
542 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
543 StringRef ArchiveMemberName = StringRef(),
544 StringRef ArchitectureName = StringRef()) {
545 // If we are doing some processing here on the Mach-O file print the header
546 // info. And don't print it otherwise like in the case of printing the
547 // UniversalHeaders or ArchiveHeaders.
548 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
549 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints) {
551 if (!ArchiveMemberName.empty())
552 outs() << '(' << ArchiveMemberName << ')';
553 if (!ArchitectureName.empty())
554 outs() << " (architecture " << ArchitectureName << ")";
559 DisassembleMachO(Filename, MachOOF);
561 PrintIndirectSymbols(MachOOF, true);
563 PrintDataInCodeTable(MachOOF, true);
565 PrintLinkOptHints(MachOOF);
567 PrintRelocations(MachOOF);
569 PrintSectionHeaders(MachOOF);
571 PrintSectionContents(MachOOF);
573 PrintSymbolTable(MachOOF);
575 printMachOUnwindInfo(MachOOF);
577 printMachOFileHeader(MachOOF);
579 printExportsTrie(MachOOF);
581 printRebaseTable(MachOOF);
583 printBindTable(MachOOF);
585 printLazyBindTable(MachOOF);
587 printWeakBindTable(MachOOF);
590 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
591 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
592 outs() << " cputype (" << cputype << ")\n";
593 outs() << " cpusubtype (" << cpusubtype << ")\n";
596 // printCPUType() helps print_fat_headers by printing the cputype and
597 // pusubtype (symbolically for the one's it knows about).
598 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
600 case MachO::CPU_TYPE_I386:
601 switch (cpusubtype) {
602 case MachO::CPU_SUBTYPE_I386_ALL:
603 outs() << " cputype CPU_TYPE_I386\n";
604 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
607 printUnknownCPUType(cputype, cpusubtype);
611 case MachO::CPU_TYPE_X86_64:
612 switch (cpusubtype) {
613 case MachO::CPU_SUBTYPE_X86_64_ALL:
614 outs() << " cputype CPU_TYPE_X86_64\n";
615 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
617 case MachO::CPU_SUBTYPE_X86_64_H:
618 outs() << " cputype CPU_TYPE_X86_64\n";
619 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
622 printUnknownCPUType(cputype, cpusubtype);
626 case MachO::CPU_TYPE_ARM:
627 switch (cpusubtype) {
628 case MachO::CPU_SUBTYPE_ARM_ALL:
629 outs() << " cputype CPU_TYPE_ARM\n";
630 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
632 case MachO::CPU_SUBTYPE_ARM_V4T:
633 outs() << " cputype CPU_TYPE_ARM\n";
634 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
636 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
637 outs() << " cputype CPU_TYPE_ARM\n";
638 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
640 case MachO::CPU_SUBTYPE_ARM_XSCALE:
641 outs() << " cputype CPU_TYPE_ARM\n";
642 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
644 case MachO::CPU_SUBTYPE_ARM_V6:
645 outs() << " cputype CPU_TYPE_ARM\n";
646 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
648 case MachO::CPU_SUBTYPE_ARM_V6M:
649 outs() << " cputype CPU_TYPE_ARM\n";
650 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
652 case MachO::CPU_SUBTYPE_ARM_V7:
653 outs() << " cputype CPU_TYPE_ARM\n";
654 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
656 case MachO::CPU_SUBTYPE_ARM_V7EM:
657 outs() << " cputype CPU_TYPE_ARM\n";
658 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
660 case MachO::CPU_SUBTYPE_ARM_V7K:
661 outs() << " cputype CPU_TYPE_ARM\n";
662 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
664 case MachO::CPU_SUBTYPE_ARM_V7M:
665 outs() << " cputype CPU_TYPE_ARM\n";
666 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
668 case MachO::CPU_SUBTYPE_ARM_V7S:
669 outs() << " cputype CPU_TYPE_ARM\n";
670 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
673 printUnknownCPUType(cputype, cpusubtype);
677 case MachO::CPU_TYPE_ARM64:
678 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
679 case MachO::CPU_SUBTYPE_ARM64_ALL:
680 outs() << " cputype CPU_TYPE_ARM64\n";
681 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
684 printUnknownCPUType(cputype, cpusubtype);
689 printUnknownCPUType(cputype, cpusubtype);
694 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
696 outs() << "Fat headers\n";
698 outs() << "fat_magic FAT_MAGIC\n";
700 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
702 uint32_t nfat_arch = UB->getNumberOfObjects();
703 StringRef Buf = UB->getData();
704 uint64_t size = Buf.size();
705 uint64_t big_size = sizeof(struct MachO::fat_header) +
706 nfat_arch * sizeof(struct MachO::fat_arch);
707 outs() << "nfat_arch " << UB->getNumberOfObjects();
709 outs() << " (malformed, contains zero architecture types)\n";
710 else if (big_size > size)
711 outs() << " (malformed, architectures past end of file)\n";
715 for (uint32_t i = 0; i < nfat_arch; ++i) {
716 MachOUniversalBinary::ObjectForArch OFA(UB, i);
717 uint32_t cputype = OFA.getCPUType();
718 uint32_t cpusubtype = OFA.getCPUSubType();
719 outs() << "architecture ";
720 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
721 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
722 uint32_t other_cputype = other_OFA.getCPUType();
723 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
724 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
725 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
726 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
727 outs() << "(illegal duplicate architecture) ";
732 outs() << OFA.getArchTypeName() << "\n";
733 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
736 outs() << " cputype " << cputype << "\n";
737 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
741 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
742 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
744 outs() << " capabilities "
745 << format("0x%" PRIx32,
746 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
747 outs() << " offset " << OFA.getOffset();
748 if (OFA.getOffset() > size)
749 outs() << " (past end of file)";
750 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
751 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
753 outs() << " size " << OFA.getSize();
754 big_size = OFA.getOffset() + OFA.getSize();
756 outs() << " (past end of file)";
758 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
763 static void printArchiveChild(Archive::Child &C, bool verbose,
766 outs() << C.getChildOffset() << "\t";
767 sys::fs::perms Mode = C.getAccessMode();
769 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
770 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
772 if (Mode & sys::fs::owner_read)
776 if (Mode & sys::fs::owner_write)
780 if (Mode & sys::fs::owner_exe)
784 if (Mode & sys::fs::group_read)
788 if (Mode & sys::fs::group_write)
792 if (Mode & sys::fs::group_exe)
796 if (Mode & sys::fs::others_read)
800 if (Mode & sys::fs::others_write)
804 if (Mode & sys::fs::others_exe)
809 outs() << format("0%o ", Mode);
812 unsigned UID = C.getUID();
813 outs() << format("%3d/", UID);
814 unsigned GID = C.getGID();
815 outs() << format("%-3d ", GID);
816 uint64_t Size = C.getRawSize();
817 outs() << format("%5" PRId64, Size) << " ";
819 StringRef RawLastModified = C.getRawLastModified();
822 if (RawLastModified.getAsInteger(10, Seconds))
823 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
825 // Since cime(3) returns a 26 character string of the form:
826 // "Sun Sep 16 01:03:52 1973\n\0"
827 // just print 24 characters.
829 outs() << format("%.24s ", ctime(&t));
832 outs() << RawLastModified << " ";
836 ErrorOr<StringRef> NameOrErr = C.getName();
837 if (NameOrErr.getError()) {
838 StringRef RawName = C.getRawName();
839 outs() << RawName << "\n";
841 StringRef Name = NameOrErr.get();
842 outs() << Name << "\n";
845 StringRef RawName = C.getRawName();
846 outs() << RawName << "\n";
850 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
851 if (A->hasSymbolTable()) {
852 Archive::child_iterator S = A->getSymbolTableChild();
853 Archive::Child C = *S;
854 printArchiveChild(C, verbose, print_offset);
856 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
858 Archive::Child C = *I;
859 printArchiveChild(C, verbose, print_offset);
863 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
864 // -arch flags selecting just those slices as specified by them and also parses
865 // archive files. Then for each individual Mach-O file ProcessMachO() is
866 // called to process the file based on the command line options.
867 void llvm::ParseInputMachO(StringRef Filename) {
868 // Check for -arch all and verifiy the -arch flags are valid.
869 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
870 if (ArchFlags[i] == "all") {
873 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
874 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
875 "'for the -arch option\n";
881 // Attempt to open the binary.
882 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
883 if (std::error_code EC = BinaryOrErr.getError()) {
884 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
887 Binary &Bin = *BinaryOrErr.get().getBinary();
889 if (Archive *A = dyn_cast<Archive>(&Bin)) {
890 outs() << "Archive : " << Filename << "\n";
892 printArchiveHeaders(A, true, false);
893 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
895 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
896 if (ChildOrErr.getError())
898 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
899 if (!checkMachOAndArchFlags(O, Filename))
901 ProcessMachO(Filename, O, O->getFileName());
906 if (UniversalHeaders) {
907 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
908 printMachOUniversalHeaders(UB, true);
910 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
911 // If we have a list of architecture flags specified dump only those.
912 if (!ArchAll && ArchFlags.size() != 0) {
913 // Look for a slice in the universal binary that matches each ArchFlag.
915 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
917 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
918 E = UB->end_objects();
920 if (ArchFlags[i] == I->getArchTypeName()) {
922 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
923 I->getAsObjectFile();
924 std::string ArchitectureName = "";
925 if (ArchFlags.size() > 1)
926 ArchitectureName = I->getArchTypeName();
928 ObjectFile &O = *ObjOrErr.get();
929 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
930 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
931 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
933 std::unique_ptr<Archive> &A = *AOrErr;
934 outs() << "Archive : " << Filename;
935 if (!ArchitectureName.empty())
936 outs() << " (architecture " << ArchitectureName << ")";
939 printArchiveHeaders(A.get(), true, false);
940 for (Archive::child_iterator AI = A->child_begin(),
943 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
944 if (ChildOrErr.getError())
946 if (MachOObjectFile *O =
947 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
948 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
954 errs() << "llvm-objdump: file: " + Filename + " does not contain "
955 << "architecture: " + ArchFlags[i] + "\n";
961 // No architecture flags were specified so if this contains a slice that
962 // matches the host architecture dump only that.
964 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
965 E = UB->end_objects();
967 if (MachOObjectFile::getHostArch().getArchName() ==
968 I->getArchTypeName()) {
969 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
970 std::string ArchiveName;
973 ObjectFile &O = *ObjOrErr.get();
974 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
975 ProcessMachO(Filename, MachOOF);
976 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
978 std::unique_ptr<Archive> &A = *AOrErr;
979 outs() << "Archive : " << Filename << "\n";
981 printArchiveHeaders(A.get(), true, false);
982 for (Archive::child_iterator AI = A->child_begin(),
985 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
986 if (ChildOrErr.getError())
988 if (MachOObjectFile *O =
989 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
990 ProcessMachO(Filename, O, O->getFileName());
997 // Either all architectures have been specified or none have been specified
998 // and this does not contain the host architecture so dump all the slices.
999 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1000 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1001 E = UB->end_objects();
1003 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1004 std::string ArchitectureName = "";
1005 if (moreThanOneArch)
1006 ArchitectureName = I->getArchTypeName();
1008 ObjectFile &Obj = *ObjOrErr.get();
1009 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1010 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1011 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1012 std::unique_ptr<Archive> &A = *AOrErr;
1013 outs() << "Archive : " << Filename;
1014 if (!ArchitectureName.empty())
1015 outs() << " (architecture " << ArchitectureName << ")";
1018 printArchiveHeaders(A.get(), true, false);
1019 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1021 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1022 if (ChildOrErr.getError())
1024 if (MachOObjectFile *O =
1025 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1026 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1027 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1035 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1036 if (!checkMachOAndArchFlags(O, Filename))
1038 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1039 ProcessMachO(Filename, MachOOF);
1041 errs() << "llvm-objdump: '" << Filename << "': "
1042 << "Object is not a Mach-O file type.\n";
1044 errs() << "llvm-objdump: '" << Filename << "': "
1045 << "Unrecognized file type.\n";
1048 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1049 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1050 typedef std::vector<BindInfoEntry> BindTable;
1051 typedef BindTable::iterator bind_table_iterator;
1053 // The block of info used by the Symbolizer call backs.
1054 struct DisassembleInfo {
1058 SymbolAddressMap *AddrMap;
1059 std::vector<SectionRef> *Sections;
1060 const char *class_name;
1061 const char *selector_name;
1063 char *demangled_name;
1066 BindTable *bindtable;
1069 // GuessSymbolName is passed the address of what might be a symbol and a
1070 // pointer to the DisassembleInfo struct. It returns the name of a symbol
1071 // with that address or nullptr if no symbol is found with that address.
1072 static const char *GuessSymbolName(uint64_t value,
1073 struct DisassembleInfo *info) {
1074 const char *SymbolName = nullptr;
1075 // A DenseMap can't lookup up some values.
1076 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1077 StringRef name = info->AddrMap->lookup(value);
1079 SymbolName = name.data();
1084 // SymbolizerGetOpInfo() is the operand information call back function.
1085 // This is called to get the symbolic information for operand(s) of an
1086 // instruction when it is being done. This routine does this from
1087 // the relocation information, symbol table, etc. That block of information
1088 // is a pointer to the struct DisassembleInfo that was passed when the
1089 // disassembler context was created and passed to back to here when
1090 // called back by the disassembler for instruction operands that could have
1091 // relocation information. The address of the instruction containing operand is
1092 // at the Pc parameter. The immediate value the operand has is passed in
1093 // op_info->Value and is at Offset past the start of the instruction and has a
1094 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1095 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1096 // names and addends of the symbolic expression to add for the operand. The
1097 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1098 // information is returned then this function returns 1 else it returns 0.
1099 int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1100 uint64_t Size, int TagType, void *TagBuf) {
1101 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1102 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1103 uint64_t value = op_info->Value;
1105 // Make sure all fields returned are zero if we don't set them.
1106 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1107 op_info->Value = value;
1109 // If the TagType is not the value 1 which it code knows about or if no
1110 // verbose symbolic information is wanted then just return 0, indicating no
1111 // information is being returned.
1112 if (TagType != 1 || info->verbose == false)
1115 unsigned int Arch = info->O->getArch();
1116 if (Arch == Triple::x86) {
1117 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1119 // First search the section's relocation entries (if any) for an entry
1120 // for this section offset.
1121 uint32_t sect_addr = info->S.getAddress();
1122 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1123 bool reloc_found = false;
1125 MachO::any_relocation_info RE;
1126 bool isExtern = false;
1128 bool r_scattered = false;
1129 uint32_t r_value, pair_r_value, r_type;
1130 for (const RelocationRef &Reloc : info->S.relocations()) {
1131 uint64_t RelocOffset;
1132 Reloc.getOffset(RelocOffset);
1133 if (RelocOffset == sect_offset) {
1134 Rel = Reloc.getRawDataRefImpl();
1135 RE = info->O->getRelocation(Rel);
1136 r_type = info->O->getAnyRelocationType(RE);
1137 r_scattered = info->O->isRelocationScattered(RE);
1139 r_value = info->O->getScatteredRelocationValue(RE);
1140 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1141 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1142 DataRefImpl RelNext = Rel;
1143 info->O->moveRelocationNext(RelNext);
1144 MachO::any_relocation_info RENext;
1145 RENext = info->O->getRelocation(RelNext);
1146 if (info->O->isRelocationScattered(RENext))
1147 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1152 isExtern = info->O->getPlainRelocationExternal(RE);
1154 symbol_iterator RelocSym = Reloc.getSymbol();
1162 if (reloc_found && isExtern) {
1164 Symbol.getName(SymName);
1165 const char *name = SymName.data();
1166 op_info->AddSymbol.Present = 1;
1167 op_info->AddSymbol.Name = name;
1168 // For i386 extern relocation entries the value in the instruction is
1169 // the offset from the symbol, and value is already set in op_info->Value.
1172 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1173 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1174 const char *add = GuessSymbolName(r_value, info);
1175 const char *sub = GuessSymbolName(pair_r_value, info);
1176 uint32_t offset = value - (r_value - pair_r_value);
1177 op_info->AddSymbol.Present = 1;
1179 op_info->AddSymbol.Name = add;
1181 op_info->AddSymbol.Value = r_value;
1182 op_info->SubtractSymbol.Present = 1;
1184 op_info->SubtractSymbol.Name = sub;
1186 op_info->SubtractSymbol.Value = pair_r_value;
1187 op_info->Value = offset;
1191 // Second search the external relocation entries of a fully linked image
1192 // (if any) for an entry that matches this segment offset.
1193 // uint32_t seg_offset = (Pc + Offset);
1195 } else if (Arch == Triple::x86_64) {
1196 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1198 // First search the section's relocation entries (if any) for an entry
1199 // for this section offset.
1200 uint64_t sect_addr = info->S.getAddress();
1201 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1202 bool reloc_found = false;
1204 MachO::any_relocation_info RE;
1205 bool isExtern = false;
1207 for (const RelocationRef &Reloc : info->S.relocations()) {
1208 uint64_t RelocOffset;
1209 Reloc.getOffset(RelocOffset);
1210 if (RelocOffset == sect_offset) {
1211 Rel = Reloc.getRawDataRefImpl();
1212 RE = info->O->getRelocation(Rel);
1213 // NOTE: Scattered relocations don't exist on x86_64.
1214 isExtern = info->O->getPlainRelocationExternal(RE);
1216 symbol_iterator RelocSym = Reloc.getSymbol();
1223 if (reloc_found && isExtern) {
1224 // The Value passed in will be adjusted by the Pc if the instruction
1225 // adds the Pc. But for x86_64 external relocation entries the Value
1226 // is the offset from the external symbol.
1227 if (info->O->getAnyRelocationPCRel(RE))
1228 op_info->Value -= Pc + Offset + Size;
1230 Symbol.getName(SymName);
1231 const char *name = SymName.data();
1232 unsigned Type = info->O->getAnyRelocationType(RE);
1233 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1234 DataRefImpl RelNext = Rel;
1235 info->O->moveRelocationNext(RelNext);
1236 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1237 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1238 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1239 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1240 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1241 op_info->SubtractSymbol.Present = 1;
1242 op_info->SubtractSymbol.Name = name;
1243 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1244 Symbol = *RelocSymNext;
1245 StringRef SymNameNext;
1246 Symbol.getName(SymNameNext);
1247 name = SymNameNext.data();
1250 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1251 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1252 op_info->AddSymbol.Present = 1;
1253 op_info->AddSymbol.Name = name;
1257 // Second search the external relocation entries of a fully linked image
1258 // (if any) for an entry that matches this segment offset.
1259 // uint64_t seg_offset = (Pc + Offset);
1261 } else if (Arch == Triple::arm) {
1262 if (Offset != 0 || (Size != 4 && Size != 2))
1264 // First search the section's relocation entries (if any) for an entry
1265 // for this section offset.
1266 uint32_t sect_addr = info->S.getAddress();
1267 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1268 bool reloc_found = false;
1270 MachO::any_relocation_info RE;
1271 bool isExtern = false;
1273 bool r_scattered = false;
1274 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1275 for (const RelocationRef &Reloc : info->S.relocations()) {
1276 uint64_t RelocOffset;
1277 Reloc.getOffset(RelocOffset);
1278 if (RelocOffset == sect_offset) {
1279 Rel = Reloc.getRawDataRefImpl();
1280 RE = info->O->getRelocation(Rel);
1281 r_length = info->O->getAnyRelocationLength(RE);
1282 r_scattered = info->O->isRelocationScattered(RE);
1284 r_value = info->O->getScatteredRelocationValue(RE);
1285 r_type = info->O->getScatteredRelocationType(RE);
1287 r_type = info->O->getAnyRelocationType(RE);
1288 isExtern = info->O->getPlainRelocationExternal(RE);
1290 symbol_iterator RelocSym = Reloc.getSymbol();
1294 if (r_type == MachO::ARM_RELOC_HALF ||
1295 r_type == MachO::ARM_RELOC_SECTDIFF ||
1296 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1297 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1298 DataRefImpl RelNext = Rel;
1299 info->O->moveRelocationNext(RelNext);
1300 MachO::any_relocation_info RENext;
1301 RENext = info->O->getRelocation(RelNext);
1302 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1303 if (info->O->isRelocationScattered(RENext))
1304 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1310 if (reloc_found && isExtern) {
1312 Symbol.getName(SymName);
1313 const char *name = SymName.data();
1314 op_info->AddSymbol.Present = 1;
1315 op_info->AddSymbol.Name = name;
1318 case MachO::ARM_RELOC_HALF:
1319 if ((r_length & 0x1) == 1) {
1320 op_info->Value = value << 16 | other_half;
1321 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1323 op_info->Value = other_half << 16 | value;
1324 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1332 case MachO::ARM_RELOC_HALF:
1333 if ((r_length & 0x1) == 1) {
1334 op_info->Value = value << 16 | other_half;
1335 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1337 op_info->Value = other_half << 16 | value;
1338 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1347 // If we have a branch that is not an external relocation entry then
1348 // return 0 so the code in tryAddingSymbolicOperand() can use the
1349 // SymbolLookUp call back with the branch target address to look up the
1350 // symbol and possiblity add an annotation for a symbol stub.
1351 if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1352 r_type == MachO::ARM_THUMB_RELOC_BR22))
1355 uint32_t offset = 0;
1357 if (r_type == MachO::ARM_RELOC_HALF ||
1358 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1359 if ((r_length & 0x1) == 1)
1360 value = value << 16 | other_half;
1362 value = other_half << 16 | value;
1364 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1365 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1366 offset = value - r_value;
1371 if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1372 if ((r_length & 0x1) == 1)
1373 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1375 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1376 const char *add = GuessSymbolName(r_value, info);
1377 const char *sub = GuessSymbolName(pair_r_value, info);
1378 int32_t offset = value - (r_value - pair_r_value);
1379 op_info->AddSymbol.Present = 1;
1381 op_info->AddSymbol.Name = add;
1383 op_info->AddSymbol.Value = r_value;
1384 op_info->SubtractSymbol.Present = 1;
1386 op_info->SubtractSymbol.Name = sub;
1388 op_info->SubtractSymbol.Value = pair_r_value;
1389 op_info->Value = offset;
1393 if (reloc_found == false)
1396 op_info->AddSymbol.Present = 1;
1397 op_info->Value = offset;
1399 if (r_type == MachO::ARM_RELOC_HALF) {
1400 if ((r_length & 0x1) == 1)
1401 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1403 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1406 const char *add = GuessSymbolName(value, info);
1407 if (add != nullptr) {
1408 op_info->AddSymbol.Name = add;
1411 op_info->AddSymbol.Value = value;
1413 } else if (Arch == Triple::aarch64) {
1414 if (Offset != 0 || Size != 4)
1416 // First search the section's relocation entries (if any) for an entry
1417 // for this section offset.
1418 uint64_t sect_addr = info->S.getAddress();
1419 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1420 bool reloc_found = false;
1422 MachO::any_relocation_info RE;
1423 bool isExtern = false;
1425 uint32_t r_type = 0;
1426 for (const RelocationRef &Reloc : info->S.relocations()) {
1427 uint64_t RelocOffset;
1428 Reloc.getOffset(RelocOffset);
1429 if (RelocOffset == sect_offset) {
1430 Rel = Reloc.getRawDataRefImpl();
1431 RE = info->O->getRelocation(Rel);
1432 r_type = info->O->getAnyRelocationType(RE);
1433 if (r_type == MachO::ARM64_RELOC_ADDEND) {
1434 DataRefImpl RelNext = Rel;
1435 info->O->moveRelocationNext(RelNext);
1436 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1438 value = info->O->getPlainRelocationSymbolNum(RENext);
1439 op_info->Value = value;
1442 // NOTE: Scattered relocations don't exist on arm64.
1443 isExtern = info->O->getPlainRelocationExternal(RE);
1445 symbol_iterator RelocSym = Reloc.getSymbol();
1452 if (reloc_found && isExtern) {
1454 Symbol.getName(SymName);
1455 const char *name = SymName.data();
1456 op_info->AddSymbol.Present = 1;
1457 op_info->AddSymbol.Name = name;
1460 case MachO::ARM64_RELOC_PAGE21:
1462 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
1464 case MachO::ARM64_RELOC_PAGEOFF12:
1466 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
1468 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
1470 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
1472 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
1474 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
1476 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
1477 /* @tvlppage is not implemented in llvm-mc */
1478 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
1480 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
1481 /* @tvlppageoff is not implemented in llvm-mc */
1482 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
1485 case MachO::ARM64_RELOC_BRANCH26:
1486 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
1497 // GuessCstringPointer is passed the address of what might be a pointer to a
1498 // literal string in a cstring section. If that address is in a cstring section
1499 // it returns a pointer to that string. Else it returns nullptr.
1500 const char *GuessCstringPointer(uint64_t ReferenceValue,
1501 struct DisassembleInfo *info) {
1502 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1503 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1504 for (unsigned I = 0;; ++I) {
1505 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1506 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1507 for (unsigned J = 0; J < Seg.nsects; ++J) {
1508 MachO::section_64 Sec = info->O->getSection64(Load, J);
1509 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1510 if (section_type == MachO::S_CSTRING_LITERALS &&
1511 ReferenceValue >= Sec.addr &&
1512 ReferenceValue < Sec.addr + Sec.size) {
1513 uint64_t sect_offset = ReferenceValue - Sec.addr;
1514 uint64_t object_offset = Sec.offset + sect_offset;
1515 StringRef MachOContents = info->O->getData();
1516 uint64_t object_size = MachOContents.size();
1517 const char *object_addr = (const char *)MachOContents.data();
1518 if (object_offset < object_size) {
1519 const char *name = object_addr + object_offset;
1526 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1527 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
1528 for (unsigned J = 0; J < Seg.nsects; ++J) {
1529 MachO::section Sec = info->O->getSection(Load, J);
1530 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1531 if (section_type == MachO::S_CSTRING_LITERALS &&
1532 ReferenceValue >= Sec.addr &&
1533 ReferenceValue < Sec.addr + Sec.size) {
1534 uint64_t sect_offset = ReferenceValue - Sec.addr;
1535 uint64_t object_offset = Sec.offset + sect_offset;
1536 StringRef MachOContents = info->O->getData();
1537 uint64_t object_size = MachOContents.size();
1538 const char *object_addr = (const char *)MachOContents.data();
1539 if (object_offset < object_size) {
1540 const char *name = object_addr + object_offset;
1548 if (I == LoadCommandCount - 1)
1551 Load = info->O->getNextLoadCommandInfo(Load);
1556 // GuessIndirectSymbol returns the name of the indirect symbol for the
1557 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
1558 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
1559 // symbol name being referenced by the stub or pointer.
1560 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
1561 struct DisassembleInfo *info) {
1562 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1563 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1564 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
1565 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
1566 for (unsigned I = 0;; ++I) {
1567 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1568 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1569 for (unsigned J = 0; J < Seg.nsects; ++J) {
1570 MachO::section_64 Sec = info->O->getSection64(Load, J);
1571 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1572 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1573 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1574 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1575 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
1576 section_type == MachO::S_SYMBOL_STUBS) &&
1577 ReferenceValue >= Sec.addr &&
1578 ReferenceValue < Sec.addr + Sec.size) {
1580 if (section_type == MachO::S_SYMBOL_STUBS)
1581 stride = Sec.reserved2;
1586 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
1587 if (index < Dysymtab.nindirectsyms) {
1588 uint32_t indirect_symbol =
1589 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
1590 if (indirect_symbol < Symtab.nsyms) {
1591 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1592 SymbolRef Symbol = *Sym;
1594 Symbol.getName(SymName);
1595 const char *name = SymName.data();
1601 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1602 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
1603 for (unsigned J = 0; J < Seg.nsects; ++J) {
1604 MachO::section Sec = info->O->getSection(Load, J);
1605 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1606 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1607 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1608 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1609 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
1610 section_type == MachO::S_SYMBOL_STUBS) &&
1611 ReferenceValue >= Sec.addr &&
1612 ReferenceValue < Sec.addr + Sec.size) {
1614 if (section_type == MachO::S_SYMBOL_STUBS)
1615 stride = Sec.reserved2;
1620 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
1621 if (index < Dysymtab.nindirectsyms) {
1622 uint32_t indirect_symbol =
1623 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
1624 if (indirect_symbol < Symtab.nsyms) {
1625 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1626 SymbolRef Symbol = *Sym;
1628 Symbol.getName(SymName);
1629 const char *name = SymName.data();
1636 if (I == LoadCommandCount - 1)
1639 Load = info->O->getNextLoadCommandInfo(Load);
1644 // method_reference() is called passing it the ReferenceName that might be
1645 // a reference it to an Objective-C method call. If so then it allocates and
1646 // assembles a method call string with the values last seen and saved in
1647 // the DisassembleInfo's class_name and selector_name fields. This is saved
1648 // into the method field of the info and any previous string is free'ed.
1649 // Then the class_name field in the info is set to nullptr. The method call
1650 // string is set into ReferenceName and ReferenceType is set to
1651 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
1652 // then both ReferenceType and ReferenceName are left unchanged.
1653 static void method_reference(struct DisassembleInfo *info,
1654 uint64_t *ReferenceType,
1655 const char **ReferenceName) {
1656 unsigned int Arch = info->O->getArch();
1657 if (*ReferenceName != nullptr) {
1658 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
1659 if (info->selector_name != nullptr) {
1660 if (info->method != nullptr)
1662 if (info->class_name != nullptr) {
1663 info->method = (char *)malloc(5 + strlen(info->class_name) +
1664 strlen(info->selector_name));
1665 if (info->method != nullptr) {
1666 strcpy(info->method, "+[");
1667 strcat(info->method, info->class_name);
1668 strcat(info->method, " ");
1669 strcat(info->method, info->selector_name);
1670 strcat(info->method, "]");
1671 *ReferenceName = info->method;
1672 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1675 info->method = (char *)malloc(9 + strlen(info->selector_name));
1676 if (info->method != nullptr) {
1677 if (Arch == Triple::x86_64)
1678 strcpy(info->method, "-[%rdi ");
1679 else if (Arch == Triple::aarch64)
1680 strcpy(info->method, "-[x0 ");
1682 strcpy(info->method, "-[r? ");
1683 strcat(info->method, info->selector_name);
1684 strcat(info->method, "]");
1685 *ReferenceName = info->method;
1686 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1689 info->class_name = nullptr;
1691 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
1692 if (info->selector_name != nullptr) {
1693 if (info->method != nullptr)
1695 info->method = (char *)malloc(17 + strlen(info->selector_name));
1696 if (info->method != nullptr) {
1697 if (Arch == Triple::x86_64)
1698 strcpy(info->method, "-[[%rdi super] ");
1699 else if (Arch == Triple::aarch64)
1700 strcpy(info->method, "-[[x0 super] ");
1702 strcpy(info->method, "-[[r? super] ");
1703 strcat(info->method, info->selector_name);
1704 strcat(info->method, "]");
1705 *ReferenceName = info->method;
1706 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1708 info->class_name = nullptr;
1714 // GuessPointerPointer() is passed the address of what might be a pointer to
1715 // a reference to an Objective-C class, selector, message ref or cfstring.
1716 // If so the value of the pointer is returned and one of the booleans are set
1717 // to true. If not zero is returned and all the booleans are set to false.
1718 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
1719 struct DisassembleInfo *info,
1720 bool &classref, bool &selref, bool &msgref,
1726 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1727 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1728 for (unsigned I = 0;; ++I) {
1729 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1730 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1731 for (unsigned J = 0; J < Seg.nsects; ++J) {
1732 MachO::section_64 Sec = info->O->getSection64(Load, J);
1733 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
1734 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
1735 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
1736 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
1737 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
1738 ReferenceValue >= Sec.addr &&
1739 ReferenceValue < Sec.addr + Sec.size) {
1740 uint64_t sect_offset = ReferenceValue - Sec.addr;
1741 uint64_t object_offset = Sec.offset + sect_offset;
1742 StringRef MachOContents = info->O->getData();
1743 uint64_t object_size = MachOContents.size();
1744 const char *object_addr = (const char *)MachOContents.data();
1745 if (object_offset < object_size) {
1746 uint64_t pointer_value;
1747 memcpy(&pointer_value, object_addr + object_offset,
1749 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1750 sys::swapByteOrder(pointer_value);
1751 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
1753 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
1754 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
1756 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
1757 ReferenceValue + 8 < Sec.addr + Sec.size) {
1759 memcpy(&pointer_value, object_addr + object_offset + 8,
1761 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1762 sys::swapByteOrder(pointer_value);
1763 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
1765 return pointer_value;
1772 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
1773 if (I == LoadCommandCount - 1)
1776 Load = info->O->getNextLoadCommandInfo(Load);
1781 // get_pointer_64 returns a pointer to the bytes in the object file at the
1782 // Address from a section in the Mach-O file. And indirectly returns the
1783 // offset into the section, number of bytes left in the section past the offset
1784 // and which section is was being referenced. If the Address is not in a
1785 // section nullptr is returned.
1786 const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left,
1787 SectionRef &S, DisassembleInfo *info) {
1791 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
1792 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
1793 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
1794 if (Address >= SectAddress && Address < SectAddress + SectSize) {
1795 S = (*(info->Sections))[SectIdx];
1796 offset = Address - SectAddress;
1797 left = SectSize - offset;
1798 StringRef SectContents;
1799 ((*(info->Sections))[SectIdx]).getContents(SectContents);
1800 return SectContents.data() + offset;
1806 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
1807 // the symbol indirectly through n_value. Based on the relocation information
1808 // for the specified section offset in the specified section reference.
1809 const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
1810 DisassembleInfo *info, uint64_t &n_value) {
1812 if (info->verbose == false)
1815 // See if there is an external relocation entry at the sect_offset.
1816 bool reloc_found = false;
1818 MachO::any_relocation_info RE;
1819 bool isExtern = false;
1821 for (const RelocationRef &Reloc : S.relocations()) {
1822 uint64_t RelocOffset;
1823 Reloc.getOffset(RelocOffset);
1824 if (RelocOffset == sect_offset) {
1825 Rel = Reloc.getRawDataRefImpl();
1826 RE = info->O->getRelocation(Rel);
1827 if (info->O->isRelocationScattered(RE))
1829 isExtern = info->O->getPlainRelocationExternal(RE);
1831 symbol_iterator RelocSym = Reloc.getSymbol();
1838 // If there is an external relocation entry for a symbol in this section
1839 // at this section_offset then use that symbol's value for the n_value
1840 // and return its name.
1841 const char *SymbolName = nullptr;
1842 if (reloc_found && isExtern) {
1843 Symbol.getAddress(n_value);
1845 Symbol.getName(name);
1846 if (!name.empty()) {
1847 SymbolName = name.data();
1852 // TODO: For fully linked images, look through the external relocation
1853 // entries off the dynamic symtab command. For these the r_offset is from the
1854 // start of the first writeable segment in the Mach-O file. So the offset
1855 // to this section from that segment is passed to this routine by the caller,
1856 // as the database_offset. Which is the difference of the section's starting
1857 // address and the first writable segment.
1859 // NOTE: need add passing the database_offset to this routine.
1861 // TODO: We did not find an external relocation entry so look up the
1862 // ReferenceValue as an address of a symbol and if found return that symbol's
1865 // NOTE: need add passing the ReferenceValue to this routine. Then that code
1866 // would simply be this:
1867 // SymbolName = GuessSymbolName(ReferenceValue, info);
1872 // These are structs in the Objective-C meta data and read to produce the
1873 // comments for disassembly. While these are part of the ABI they are no
1874 // public defintions. So the are here not in include/llvm/Support/MachO.h .
1876 // The cfstring object in a 64-bit Mach-O file.
1877 struct cfstring64_t {
1878 uint64_t isa; // class64_t * (64-bit pointer)
1879 uint64_t flags; // flag bits
1880 uint64_t characters; // char * (64-bit pointer)
1881 uint64_t length; // number of non-NULL characters in above
1884 // The class object in a 64-bit Mach-O file.
1886 uint64_t isa; // class64_t * (64-bit pointer)
1887 uint64_t superclass; // class64_t * (64-bit pointer)
1888 uint64_t cache; // Cache (64-bit pointer)
1889 uint64_t vtable; // IMP * (64-bit pointer)
1890 uint64_t data; // class_ro64_t * (64-bit pointer)
1893 struct class_ro64_t {
1895 uint32_t instanceStart;
1896 uint32_t instanceSize;
1898 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
1899 uint64_t name; // const char * (64-bit pointer)
1900 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
1901 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
1902 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
1903 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
1904 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
1907 inline void swapStruct(struct cfstring64_t &cfs) {
1908 sys::swapByteOrder(cfs.isa);
1909 sys::swapByteOrder(cfs.flags);
1910 sys::swapByteOrder(cfs.characters);
1911 sys::swapByteOrder(cfs.length);
1914 inline void swapStruct(struct class64_t &c) {
1915 sys::swapByteOrder(c.isa);
1916 sys::swapByteOrder(c.superclass);
1917 sys::swapByteOrder(c.cache);
1918 sys::swapByteOrder(c.vtable);
1919 sys::swapByteOrder(c.data);
1922 inline void swapStruct(struct class_ro64_t &cro) {
1923 sys::swapByteOrder(cro.flags);
1924 sys::swapByteOrder(cro.instanceStart);
1925 sys::swapByteOrder(cro.instanceSize);
1926 sys::swapByteOrder(cro.reserved);
1927 sys::swapByteOrder(cro.ivarLayout);
1928 sys::swapByteOrder(cro.name);
1929 sys::swapByteOrder(cro.baseMethods);
1930 sys::swapByteOrder(cro.baseProtocols);
1931 sys::swapByteOrder(cro.ivars);
1932 sys::swapByteOrder(cro.weakIvarLayout);
1933 sys::swapByteOrder(cro.baseProperties);
1936 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
1937 struct DisassembleInfo *info);
1939 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
1940 // to an Objective-C class and returns the class name. It is also passed the
1941 // address of the pointer, so when the pointer is zero as it can be in an .o
1942 // file, that is used to look for an external relocation entry with a symbol
1944 const char *get_objc2_64bit_class_name(uint64_t pointer_value,
1945 uint64_t ReferenceValue,
1946 struct DisassembleInfo *info) {
1948 uint32_t offset, left;
1951 // The pointer_value can be 0 in an object file and have a relocation
1952 // entry for the class symbol at the ReferenceValue (the address of the
1954 if (pointer_value == 0) {
1955 r = get_pointer_64(ReferenceValue, offset, left, S, info);
1956 if (r == nullptr || left < sizeof(uint64_t))
1959 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1960 if (symbol_name == nullptr)
1962 const char *class_name = strrchr(symbol_name, '$');
1963 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
1964 return class_name + 2;
1969 // The case were the pointer_value is non-zero and points to a class defined
1970 // in this Mach-O file.
1971 r = get_pointer_64(pointer_value, offset, left, S, info);
1972 if (r == nullptr || left < sizeof(struct class64_t))
1975 memcpy(&c, r, sizeof(struct class64_t));
1976 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1980 r = get_pointer_64(c.data, offset, left, S, info);
1981 if (r == nullptr || left < sizeof(struct class_ro64_t))
1983 struct class_ro64_t cro;
1984 memcpy(&cro, r, sizeof(struct class_ro64_t));
1985 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1989 const char *name = get_pointer_64(cro.name, offset, left, S, info);
1993 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
1994 // pointer to a cfstring and returns its name or nullptr.
1995 const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
1996 struct DisassembleInfo *info) {
1997 const char *r, *name;
1998 uint32_t offset, left;
2000 struct cfstring64_t cfs;
2001 uint64_t cfs_characters;
2003 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2004 if (r == nullptr || left < sizeof(struct cfstring64_t))
2006 memcpy(&cfs, r, sizeof(struct cfstring64_t));
2007 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2009 if (cfs.characters == 0) {
2011 const char *symbol_name = get_symbol_64(
2012 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
2013 if (symbol_name == nullptr)
2015 cfs_characters = n_value;
2017 cfs_characters = cfs.characters;
2018 name = get_pointer_64(cfs_characters, offset, left, S, info);
2023 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
2024 // of a pointer to an Objective-C selector reference when the pointer value is
2025 // zero as in a .o file and is likely to have a external relocation entry with
2026 // who's symbol's n_value is the real pointer to the selector name. If that is
2027 // the case the real pointer to the selector name is returned else 0 is
2029 uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
2030 struct DisassembleInfo *info) {
2031 uint32_t offset, left;
2034 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
2035 if (r == nullptr || left < sizeof(uint64_t))
2038 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2039 if (symbol_name == nullptr)
2044 // GuessLiteralPointer returns a string which for the item in the Mach-O file
2045 // for the address passed in as ReferenceValue for printing as a comment with
2046 // the instruction and also returns the corresponding type of that item
2047 // indirectly through ReferenceType.
2049 // If ReferenceValue is an address of literal cstring then a pointer to the
2050 // cstring is returned and ReferenceType is set to
2051 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
2053 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
2054 // Class ref that name is returned and the ReferenceType is set accordingly.
2056 // Lastly, literals which are Symbol address in a literal pool are looked for
2057 // and if found the symbol name is returned and ReferenceType is set to
2058 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
2060 // If there is no item in the Mach-O file for the address passed in as
2061 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
2062 const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC,
2063 uint64_t *ReferenceType,
2064 struct DisassembleInfo *info) {
2065 // First see if there is an external relocation entry at the ReferencePC.
2066 uint64_t sect_addr = info->S.getAddress();
2067 uint64_t sect_offset = ReferencePC - sect_addr;
2068 bool reloc_found = false;
2070 MachO::any_relocation_info RE;
2071 bool isExtern = false;
2073 for (const RelocationRef &Reloc : info->S.relocations()) {
2074 uint64_t RelocOffset;
2075 Reloc.getOffset(RelocOffset);
2076 if (RelocOffset == sect_offset) {
2077 Rel = Reloc.getRawDataRefImpl();
2078 RE = info->O->getRelocation(Rel);
2079 if (info->O->isRelocationScattered(RE))
2081 isExtern = info->O->getPlainRelocationExternal(RE);
2083 symbol_iterator RelocSym = Reloc.getSymbol();
2090 // If there is an external relocation entry for a symbol in a section
2091 // then used that symbol's value for the value of the reference.
2092 if (reloc_found && isExtern) {
2093 if (info->O->getAnyRelocationPCRel(RE)) {
2094 unsigned Type = info->O->getAnyRelocationType(RE);
2095 if (Type == MachO::X86_64_RELOC_SIGNED) {
2096 Symbol.getAddress(ReferenceValue);
2101 // Look for literals such as Objective-C CFStrings refs, Selector refs,
2102 // Message refs and Class refs.
2103 bool classref, selref, msgref, cfstring;
2104 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
2105 selref, msgref, cfstring);
2106 if (classref == true && pointer_value == 0) {
2107 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
2108 // And the pointer_value in that section is typically zero as it will be
2109 // set by dyld as part of the "bind information".
2110 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
2111 if (name != nullptr) {
2112 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2113 const char *class_name = strrchr(name, '$');
2114 if (class_name != nullptr && class_name[1] == '_' &&
2115 class_name[2] != '\0') {
2116 info->class_name = class_name + 2;
2122 if (classref == true) {
2123 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2125 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
2126 if (name != nullptr)
2127 info->class_name = name;
2129 name = "bad class ref";
2133 if (cfstring == true) {
2134 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
2135 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
2139 if (selref == true && pointer_value == 0)
2140 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
2142 if (pointer_value != 0)
2143 ReferenceValue = pointer_value;
2145 const char *name = GuessCstringPointer(ReferenceValue, info);
2147 if (pointer_value != 0 && selref == true) {
2148 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
2149 info->selector_name = name;
2150 } else if (pointer_value != 0 && msgref == true) {
2151 info->class_name = nullptr;
2152 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
2153 info->selector_name = name;
2155 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
2159 // Lastly look for an indirect symbol with this ReferenceValue which is in
2160 // a literal pool. If found return that symbol name.
2161 name = GuessIndirectSymbol(ReferenceValue, info);
2163 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
2170 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
2171 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
2172 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
2173 // is created and returns the symbol name that matches the ReferenceValue or
2174 // nullptr if none. The ReferenceType is passed in for the IN type of
2175 // reference the instruction is making from the values in defined in the header
2176 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
2177 // Out type and the ReferenceName will also be set which is added as a comment
2178 // to the disassembled instruction.
2181 // If the symbol name is a C++ mangled name then the demangled name is
2182 // returned through ReferenceName and ReferenceType is set to
2183 // LLVMDisassembler_ReferenceType_DeMangled_Name .
2186 // When this is called to get a symbol name for a branch target then the
2187 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
2188 // SymbolValue will be looked for in the indirect symbol table to determine if
2189 // it is an address for a symbol stub. If so then the symbol name for that
2190 // stub is returned indirectly through ReferenceName and then ReferenceType is
2191 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
2193 // When this is called with an value loaded via a PC relative load then
2194 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
2195 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
2196 // or an Objective-C meta data reference. If so the output ReferenceType is
2197 // set to correspond to that as well as setting the ReferenceName.
2198 const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue,
2199 uint64_t *ReferenceType,
2200 uint64_t ReferencePC,
2201 const char **ReferenceName) {
2202 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2203 // If no verbose symbolic information is wanted then just return nullptr.
2204 if (info->verbose == false) {
2205 *ReferenceName = nullptr;
2206 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2210 const char *SymbolName = GuessSymbolName(ReferenceValue, info);
2212 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
2213 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
2214 if (*ReferenceName != nullptr) {
2215 method_reference(info, ReferenceType, ReferenceName);
2216 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
2217 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
2220 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2221 if (info->demangled_name != nullptr)
2222 free(info->demangled_name);
2224 info->demangled_name =
2225 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2226 if (info->demangled_name != nullptr) {
2227 *ReferenceName = info->demangled_name;
2228 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2230 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2233 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2234 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
2236 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2238 method_reference(info, ReferenceType, ReferenceName);
2240 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2241 // If this is arm64 and the reference is an adrp instruction save the
2242 // instruction, passed in ReferenceValue and the address of the instruction
2243 // for use later if we see and add immediate instruction.
2244 } else if (info->O->getArch() == Triple::aarch64 &&
2245 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
2246 info->adrp_inst = ReferenceValue;
2247 info->adrp_addr = ReferencePC;
2248 SymbolName = nullptr;
2249 *ReferenceName = nullptr;
2250 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2251 // If this is arm64 and reference is an add immediate instruction and we
2253 // seen an adrp instruction just before it and the adrp's Xd register
2255 // this add's Xn register reconstruct the value being referenced and look to
2256 // see if it is a literal pointer. Note the add immediate instruction is
2257 // passed in ReferenceValue.
2258 } else if (info->O->getArch() == Triple::aarch64 &&
2259 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
2260 ReferencePC - 4 == info->adrp_addr &&
2261 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2262 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2263 uint32_t addxri_inst;
2264 uint64_t adrp_imm, addxri_imm;
2267 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2268 if (info->adrp_inst & 0x0200000)
2269 adrp_imm |= 0xfffffffffc000000LL;
2271 addxri_inst = ReferenceValue;
2272 addxri_imm = (addxri_inst >> 10) & 0xfff;
2273 if (((addxri_inst >> 22) & 0x3) == 1)
2276 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2277 (adrp_imm << 12) + addxri_imm;
2280 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2281 if (*ReferenceName == nullptr)
2282 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2283 // If this is arm64 and the reference is a load register instruction and we
2284 // have seen an adrp instruction just before it and the adrp's Xd register
2285 // matches this add's Xn register reconstruct the value being referenced and
2286 // look to see if it is a literal pointer. Note the load register
2287 // instruction is passed in ReferenceValue.
2288 } else if (info->O->getArch() == Triple::aarch64 &&
2289 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
2290 ReferencePC - 4 == info->adrp_addr &&
2291 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2292 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2293 uint32_t ldrxui_inst;
2294 uint64_t adrp_imm, ldrxui_imm;
2297 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2298 if (info->adrp_inst & 0x0200000)
2299 adrp_imm |= 0xfffffffffc000000LL;
2301 ldrxui_inst = ReferenceValue;
2302 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
2304 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2305 (adrp_imm << 12) + (ldrxui_imm << 3);
2308 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2309 if (*ReferenceName == nullptr)
2310 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2312 // If this arm64 and is an load register (PC-relative) instruction the
2313 // ReferenceValue is the PC plus the immediate value.
2314 else if (info->O->getArch() == Triple::aarch64 &&
2315 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
2316 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
2318 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2319 if (*ReferenceName == nullptr)
2320 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2323 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2324 if (info->demangled_name != nullptr)
2325 free(info->demangled_name);
2327 info->demangled_name =
2328 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2329 if (info->demangled_name != nullptr) {
2330 *ReferenceName = info->demangled_name;
2331 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2336 *ReferenceName = nullptr;
2337 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2343 /// \brief Emits the comments that are stored in the CommentStream.
2344 /// Each comment in the CommentStream must end with a newline.
2345 static void emitComments(raw_svector_ostream &CommentStream,
2346 SmallString<128> &CommentsToEmit,
2347 formatted_raw_ostream &FormattedOS,
2348 const MCAsmInfo &MAI) {
2349 // Flush the stream before taking its content.
2350 CommentStream.flush();
2351 StringRef Comments = CommentsToEmit.str();
2352 // Get the default information for printing a comment.
2353 const char *CommentBegin = MAI.getCommentString();
2354 unsigned CommentColumn = MAI.getCommentColumn();
2355 bool IsFirst = true;
2356 while (!Comments.empty()) {
2358 FormattedOS << '\n';
2359 // Emit a line of comments.
2360 FormattedOS.PadToColumn(CommentColumn);
2361 size_t Position = Comments.find('\n');
2362 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
2363 // Move after the newline character.
2364 Comments = Comments.substr(Position + 1);
2367 FormattedOS.flush();
2369 // Tell the comment stream that the vector changed underneath it.
2370 CommentsToEmit.clear();
2371 CommentStream.resync();
2374 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF) {
2375 const char *McpuDefault = nullptr;
2376 const Target *ThumbTarget = nullptr;
2377 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
2379 // GetTarget prints out stuff.
2382 if (MCPU.empty() && McpuDefault)
2385 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
2386 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
2388 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
2390 // Package up features to be passed to target/subtarget
2391 std::string FeaturesStr;
2392 if (MAttrs.size()) {
2393 SubtargetFeatures Features;
2394 for (unsigned i = 0; i != MAttrs.size(); ++i)
2395 Features.AddFeature(MAttrs[i]);
2396 FeaturesStr = Features.getString();
2399 // Set up disassembler.
2400 std::unique_ptr<const MCRegisterInfo> MRI(
2401 TheTarget->createMCRegInfo(TripleName));
2402 std::unique_ptr<const MCAsmInfo> AsmInfo(
2403 TheTarget->createMCAsmInfo(*MRI, TripleName));
2404 std::unique_ptr<const MCSubtargetInfo> STI(
2405 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
2406 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
2407 std::unique_ptr<MCDisassembler> DisAsm(
2408 TheTarget->createMCDisassembler(*STI, Ctx));
2409 std::unique_ptr<MCSymbolizer> Symbolizer;
2410 struct DisassembleInfo SymbolizerInfo;
2411 std::unique_ptr<MCRelocationInfo> RelInfo(
2412 TheTarget->createMCRelocationInfo(TripleName, Ctx));
2414 Symbolizer.reset(TheTarget->createMCSymbolizer(
2415 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2416 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
2417 DisAsm->setSymbolizer(std::move(Symbolizer));
2419 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
2420 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
2421 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
2422 // Set the display preference for hex vs. decimal immediates.
2423 IP->setPrintImmHex(PrintImmHex);
2424 // Comment stream and backing vector.
2425 SmallString<128> CommentsToEmit;
2426 raw_svector_ostream CommentStream(CommentsToEmit);
2427 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
2428 // if it is done then arm64 comments for string literals don't get printed
2429 // and some constant get printed instead and not setting it causes intel
2430 // (32-bit and 64-bit) comments printed with different spacing before the
2431 // comment causing different diffs with the 'C' disassembler library API.
2432 // IP->setCommentStream(CommentStream);
2434 if (!AsmInfo || !STI || !DisAsm || !IP) {
2435 errs() << "error: couldn't initialize disassembler for target "
2436 << TripleName << '\n';
2440 // Set up thumb disassembler.
2441 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
2442 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
2443 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
2444 std::unique_ptr<MCDisassembler> ThumbDisAsm;
2445 std::unique_ptr<MCInstPrinter> ThumbIP;
2446 std::unique_ptr<MCContext> ThumbCtx;
2447 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
2448 struct DisassembleInfo ThumbSymbolizerInfo;
2449 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
2451 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
2453 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
2455 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
2456 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
2457 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
2458 MCContext *PtrThumbCtx = ThumbCtx.get();
2460 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
2462 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
2463 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2464 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
2465 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
2467 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
2468 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
2469 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
2471 // Set the display preference for hex vs. decimal immediates.
2472 ThumbIP->setPrintImmHex(PrintImmHex);
2475 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
2476 errs() << "error: couldn't initialize disassembler for target "
2477 << ThumbTripleName << '\n';
2481 MachO::mach_header Header = MachOOF->getHeader();
2483 // FIXME: Using the -cfg command line option, this code used to be able to
2484 // annotate relocations with the referenced symbol's name, and if this was
2485 // inside a __[cf]string section, the data it points to. This is now replaced
2486 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
2487 std::vector<SectionRef> Sections;
2488 std::vector<SymbolRef> Symbols;
2489 SmallVector<uint64_t, 8> FoundFns;
2490 uint64_t BaseSegmentAddress;
2492 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
2493 BaseSegmentAddress);
2495 // Sort the symbols by address, just in case they didn't come in that way.
2496 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
2498 // Build a data in code table that is sorted on by the address of each entry.
2499 uint64_t BaseAddress = 0;
2500 if (Header.filetype == MachO::MH_OBJECT)
2501 BaseAddress = Sections[0].getAddress();
2503 BaseAddress = BaseSegmentAddress;
2505 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
2508 DI->getOffset(Offset);
2509 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
2511 array_pod_sort(Dices.begin(), Dices.end());
2514 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
2516 raw_ostream &DebugOut = nulls();
2519 std::unique_ptr<DIContext> diContext;
2520 ObjectFile *DbgObj = MachOOF;
2521 // Try to find debug info and set up the DIContext for it.
2523 // A separate DSym file path was specified, parse it as a macho file,
2524 // get the sections and supply it to the section name parsing machinery.
2525 if (!DSYMFile.empty()) {
2526 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
2527 MemoryBuffer::getFileOrSTDIN(DSYMFile);
2528 if (std::error_code EC = BufOrErr.getError()) {
2529 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
2533 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
2538 // Setup the DIContext
2539 diContext.reset(DIContext::getDWARFContext(*DbgObj));
2542 // TODO: For now this only disassembles the (__TEXT,__text) section (see the
2543 // checks in the code below at the top of this loop). It should allow a
2544 // darwin otool(1) like -s option to disassemble any named segment & section
2545 // that is marked as containing instructions with the attributes
2546 // S_ATTR_PURE_INSTRUCTIONS or S_ATTR_SOME_INSTRUCTIONS in the flags field of
2547 // the section structure.
2548 outs() << "(__TEXT,__text) section\n";
2550 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
2552 bool SectIsText = Sections[SectIdx].isText();
2553 if (SectIsText == false)
2557 if (Sections[SectIdx].getName(SectName) || SectName != "__text")
2558 continue; // Skip non-text sections
2560 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
2562 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
2563 if (SegmentName != "__TEXT")
2567 Sections[SectIdx].getContents(BytesStr);
2568 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
2570 uint64_t SectAddress = Sections[SectIdx].getAddress();
2572 bool symbolTableWorked = false;
2574 // Parse relocations.
2575 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
2576 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
2577 uint64_t RelocOffset;
2578 Reloc.getOffset(RelocOffset);
2579 uint64_t SectionAddress = Sections[SectIdx].getAddress();
2580 RelocOffset -= SectionAddress;
2582 symbol_iterator RelocSym = Reloc.getSymbol();
2584 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
2586 array_pod_sort(Relocs.begin(), Relocs.end());
2588 // Create a map of symbol addresses to symbol names for use by
2589 // the SymbolizerSymbolLookUp() routine.
2590 SymbolAddressMap AddrMap;
2591 for (const SymbolRef &Symbol : MachOOF->symbols()) {
2594 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
2595 ST == SymbolRef::ST_Other) {
2597 Symbol.getAddress(Address);
2599 Symbol.getName(SymName);
2600 AddrMap[Address] = SymName;
2603 // Set up the block of info used by the Symbolizer call backs.
2604 SymbolizerInfo.verbose = true;
2605 SymbolizerInfo.O = MachOOF;
2606 SymbolizerInfo.S = Sections[SectIdx];
2607 SymbolizerInfo.AddrMap = &AddrMap;
2608 SymbolizerInfo.Sections = &Sections;
2609 SymbolizerInfo.class_name = nullptr;
2610 SymbolizerInfo.selector_name = nullptr;
2611 SymbolizerInfo.method = nullptr;
2612 SymbolizerInfo.demangled_name = nullptr;
2613 SymbolizerInfo.bindtable = nullptr;
2614 SymbolizerInfo.adrp_addr = 0;
2615 SymbolizerInfo.adrp_inst = 0;
2616 // Same for the ThumbSymbolizer
2617 ThumbSymbolizerInfo.verbose = true;
2618 ThumbSymbolizerInfo.O = MachOOF;
2619 ThumbSymbolizerInfo.S = Sections[SectIdx];
2620 ThumbSymbolizerInfo.AddrMap = &AddrMap;
2621 ThumbSymbolizerInfo.Sections = &Sections;
2622 ThumbSymbolizerInfo.class_name = nullptr;
2623 ThumbSymbolizerInfo.selector_name = nullptr;
2624 ThumbSymbolizerInfo.method = nullptr;
2625 ThumbSymbolizerInfo.demangled_name = nullptr;
2626 ThumbSymbolizerInfo.bindtable = nullptr;
2627 ThumbSymbolizerInfo.adrp_addr = 0;
2628 ThumbSymbolizerInfo.adrp_inst = 0;
2630 // Disassemble symbol by symbol.
2631 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
2633 Symbols[SymIdx].getName(SymName);
2636 Symbols[SymIdx].getType(ST);
2637 if (ST != SymbolRef::ST_Function)
2640 // Make sure the symbol is defined in this section.
2641 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
2645 // Start at the address of the symbol relative to the section's address.
2647 uint64_t SectionAddress = Sections[SectIdx].getAddress();
2648 Symbols[SymIdx].getAddress(Start);
2649 Start -= SectionAddress;
2651 // Stop disassembling either at the beginning of the next symbol or at
2652 // the end of the section.
2653 bool containsNextSym = false;
2654 uint64_t NextSym = 0;
2655 uint64_t NextSymIdx = SymIdx + 1;
2656 while (Symbols.size() > NextSymIdx) {
2657 SymbolRef::Type NextSymType;
2658 Symbols[NextSymIdx].getType(NextSymType);
2659 if (NextSymType == SymbolRef::ST_Function) {
2661 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
2662 Symbols[NextSymIdx].getAddress(NextSym);
2663 NextSym -= SectionAddress;
2669 uint64_t SectSize = Sections[SectIdx].getSize();
2670 uint64_t End = containsNextSym ? NextSym : SectSize;
2673 symbolTableWorked = true;
2675 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
2677 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
2679 outs() << SymName << ":\n";
2680 DILineInfo lastLine;
2681 for (uint64_t Index = Start; Index < End; Index += Size) {
2684 uint64_t PC = SectAddress + Index;
2685 if (FullLeadingAddr) {
2686 if (MachOOF->is64Bit())
2687 outs() << format("%016" PRIx64, PC);
2689 outs() << format("%08" PRIx64, PC);
2691 outs() << format("%8" PRIx64 ":", PC);
2696 // Check the data in code table here to see if this is data not an
2697 // instruction to be disassembled.
2699 Dice.push_back(std::make_pair(PC, DiceRef()));
2700 dice_table_iterator DTI =
2701 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
2702 compareDiceTableEntries);
2703 if (DTI != Dices.end()) {
2705 DTI->second.getLength(Length);
2707 DTI->second.getKind(Kind);
2708 Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
2711 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
2712 (PC == (DTI->first + Length - 1)) && (Length & 1))
2717 SmallVector<char, 64> AnnotationsBytes;
2718 raw_svector_ostream Annotations(AnnotationsBytes);
2722 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
2723 PC, DebugOut, Annotations);
2725 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
2726 DebugOut, Annotations);
2728 if (!NoShowRawInsn) {
2729 DumpBytes(StringRef(
2730 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
2732 formatted_raw_ostream FormattedOS(outs());
2733 Annotations.flush();
2734 StringRef AnnotationsStr = Annotations.str();
2736 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
2738 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
2739 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
2741 // Print debug info.
2743 DILineInfo dli = diContext->getLineInfoForAddress(PC);
2744 // Print valid line info if it changed.
2745 if (dli != lastLine && dli.Line != 0)
2746 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
2752 unsigned int Arch = MachOOF->getArch();
2753 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
2754 outs() << format("\t.byte 0x%02x #bad opcode\n",
2755 *(Bytes.data() + Index) & 0xff);
2756 Size = 1; // skip exactly one illegible byte and move on.
2757 } else if (Arch == Triple::aarch64) {
2758 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
2759 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
2760 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
2761 (*(Bytes.data() + Index + 3) & 0xff) << 24;
2762 outs() << format("\t.long\t0x%08x\n", opcode);
2765 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2767 Size = 1; // skip illegible bytes
2772 if (!symbolTableWorked) {
2773 // Reading the symbol table didn't work, disassemble the whole section.
2774 uint64_t SectAddress = Sections[SectIdx].getAddress();
2775 uint64_t SectSize = Sections[SectIdx].getSize();
2777 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
2780 uint64_t PC = SectAddress + Index;
2781 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
2782 DebugOut, nulls())) {
2783 if (FullLeadingAddr) {
2784 if (MachOOF->is64Bit())
2785 outs() << format("%016" PRIx64, PC);
2787 outs() << format("%08" PRIx64, PC);
2789 outs() << format("%8" PRIx64 ":", PC);
2791 if (!NoShowRawInsn) {
2794 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
2797 IP->printInst(&Inst, outs(), "");
2800 unsigned int Arch = MachOOF->getArch();
2801 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
2802 outs() << format("\t.byte 0x%02x #bad opcode\n",
2803 *(Bytes.data() + Index) & 0xff);
2804 InstSize = 1; // skip exactly one illegible byte and move on.
2806 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2808 InstSize = 1; // skip illegible bytes
2813 // The TripleName's need to be reset if we are called again for a different
2816 ThumbTripleName = "";
2818 if (SymbolizerInfo.method != nullptr)
2819 free(SymbolizerInfo.method);
2820 if (SymbolizerInfo.demangled_name != nullptr)
2821 free(SymbolizerInfo.demangled_name);
2822 if (SymbolizerInfo.bindtable != nullptr)
2823 delete SymbolizerInfo.bindtable;
2824 if (ThumbSymbolizerInfo.method != nullptr)
2825 free(ThumbSymbolizerInfo.method);
2826 if (ThumbSymbolizerInfo.demangled_name != nullptr)
2827 free(ThumbSymbolizerInfo.demangled_name);
2828 if (ThumbSymbolizerInfo.bindtable != nullptr)
2829 delete ThumbSymbolizerInfo.bindtable;
2833 //===----------------------------------------------------------------------===//
2834 // __compact_unwind section dumping
2835 //===----------------------------------------------------------------------===//
2839 template <typename T> static uint64_t readNext(const char *&Buf) {
2840 using llvm::support::little;
2841 using llvm::support::unaligned;
2843 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
2848 struct CompactUnwindEntry {
2849 uint32_t OffsetInSection;
2851 uint64_t FunctionAddr;
2853 uint32_t CompactEncoding;
2854 uint64_t PersonalityAddr;
2857 RelocationRef FunctionReloc;
2858 RelocationRef PersonalityReloc;
2859 RelocationRef LSDAReloc;
2861 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
2862 : OffsetInSection(Offset) {
2864 read<uint64_t>(Contents.data() + Offset);
2866 read<uint32_t>(Contents.data() + Offset);
2870 template <typename UIntPtr> void read(const char *Buf) {
2871 FunctionAddr = readNext<UIntPtr>(Buf);
2872 Length = readNext<uint32_t>(Buf);
2873 CompactEncoding = readNext<uint32_t>(Buf);
2874 PersonalityAddr = readNext<UIntPtr>(Buf);
2875 LSDAAddr = readNext<UIntPtr>(Buf);
2880 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
2881 /// and data being relocated, determine the best base Name and Addend to use for
2882 /// display purposes.
2884 /// 1. An Extern relocation will directly reference a symbol (and the data is
2885 /// then already an addend), so use that.
2886 /// 2. Otherwise the data is an offset in the object file's layout; try to find
2887 // a symbol before it in the same section, and use the offset from there.
2888 /// 3. Finally, if all that fails, fall back to an offset from the start of the
2889 /// referenced section.
2890 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
2891 std::map<uint64_t, SymbolRef> &Symbols,
2892 const RelocationRef &Reloc, uint64_t Addr,
2893 StringRef &Name, uint64_t &Addend) {
2894 if (Reloc.getSymbol() != Obj->symbol_end()) {
2895 Reloc.getSymbol()->getName(Name);
2900 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
2901 SectionRef RelocSection = Obj->getRelocationSection(RE);
2903 uint64_t SectionAddr = RelocSection.getAddress();
2905 auto Sym = Symbols.upper_bound(Addr);
2906 if (Sym == Symbols.begin()) {
2907 // The first symbol in the object is after this reference, the best we can
2908 // do is section-relative notation.
2909 RelocSection.getName(Name);
2910 Addend = Addr - SectionAddr;
2914 // Go back one so that SymbolAddress <= Addr.
2917 section_iterator SymSection = Obj->section_end();
2918 Sym->second.getSection(SymSection);
2919 if (RelocSection == *SymSection) {
2920 // There's a valid symbol in the same section before this reference.
2921 Sym->second.getName(Name);
2922 Addend = Addr - Sym->first;
2926 // There is a symbol before this reference, but it's in a different
2927 // section. Probably not helpful to mention it, so use the section name.
2928 RelocSection.getName(Name);
2929 Addend = Addr - SectionAddr;
2932 static void printUnwindRelocDest(const MachOObjectFile *Obj,
2933 std::map<uint64_t, SymbolRef> &Symbols,
2934 const RelocationRef &Reloc, uint64_t Addr) {
2938 if (!Reloc.getObjectFile())
2941 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
2945 outs() << " + " << format("0x%" PRIx64, Addend);
2949 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
2950 std::map<uint64_t, SymbolRef> &Symbols,
2951 const SectionRef &CompactUnwind) {
2953 assert(Obj->isLittleEndian() &&
2954 "There should not be a big-endian .o with __compact_unwind");
2956 bool Is64 = Obj->is64Bit();
2957 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
2958 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
2961 CompactUnwind.getContents(Contents);
2963 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
2965 // First populate the initial raw offsets, encodings and so on from the entry.
2966 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
2967 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
2968 CompactUnwinds.push_back(Entry);
2971 // Next we need to look at the relocations to find out what objects are
2972 // actually being referred to.
2973 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
2974 uint64_t RelocAddress;
2975 Reloc.getOffset(RelocAddress);
2977 uint32_t EntryIdx = RelocAddress / EntrySize;
2978 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
2979 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
2981 if (OffsetInEntry == 0)
2982 Entry.FunctionReloc = Reloc;
2983 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
2984 Entry.PersonalityReloc = Reloc;
2985 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
2986 Entry.LSDAReloc = Reloc;
2988 llvm_unreachable("Unexpected relocation in __compact_unwind section");
2991 // Finally, we're ready to print the data we've gathered.
2992 outs() << "Contents of __compact_unwind section:\n";
2993 for (auto &Entry : CompactUnwinds) {
2994 outs() << " Entry at offset "
2995 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
2997 // 1. Start of the region this entry applies to.
2998 outs() << " start: " << format("0x%" PRIx64,
2999 Entry.FunctionAddr) << ' ';
3000 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
3003 // 2. Length of the region this entry applies to.
3004 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
3006 // 3. The 32-bit compact encoding.
3007 outs() << " compact encoding: "
3008 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
3010 // 4. The personality function, if present.
3011 if (Entry.PersonalityReloc.getObjectFile()) {
3012 outs() << " personality function: "
3013 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
3014 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
3015 Entry.PersonalityAddr);
3019 // 5. This entry's language-specific data area.
3020 if (Entry.LSDAReloc.getObjectFile()) {
3021 outs() << " LSDA: " << format("0x%" PRIx64,
3022 Entry.LSDAAddr) << ' ';
3023 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
3029 //===----------------------------------------------------------------------===//
3030 // __unwind_info section dumping
3031 //===----------------------------------------------------------------------===//
3033 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
3034 const char *Pos = PageStart;
3035 uint32_t Kind = readNext<uint32_t>(Pos);
3037 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
3039 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3040 uint16_t NumEntries = readNext<uint16_t>(Pos);
3042 Pos = PageStart + EntriesStart;
3043 for (unsigned i = 0; i < NumEntries; ++i) {
3044 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3045 uint32_t Encoding = readNext<uint32_t>(Pos);
3047 outs() << " [" << i << "]: "
3048 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3050 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
3054 static void printCompressedSecondLevelUnwindPage(
3055 const char *PageStart, uint32_t FunctionBase,
3056 const SmallVectorImpl<uint32_t> &CommonEncodings) {
3057 const char *Pos = PageStart;
3058 uint32_t Kind = readNext<uint32_t>(Pos);
3060 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
3062 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3063 uint16_t NumEntries = readNext<uint16_t>(Pos);
3065 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
3066 readNext<uint16_t>(Pos);
3067 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
3068 PageStart + EncodingsStart);
3070 Pos = PageStart + EntriesStart;
3071 for (unsigned i = 0; i < NumEntries; ++i) {
3072 uint32_t Entry = readNext<uint32_t>(Pos);
3073 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
3074 uint32_t EncodingIdx = Entry >> 24;
3077 if (EncodingIdx < CommonEncodings.size())
3078 Encoding = CommonEncodings[EncodingIdx];
3080 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
3082 outs() << " [" << i << "]: "
3083 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3085 << "encoding[" << EncodingIdx
3086 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
3090 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
3091 std::map<uint64_t, SymbolRef> &Symbols,
3092 const SectionRef &UnwindInfo) {
3094 assert(Obj->isLittleEndian() &&
3095 "There should not be a big-endian .o with __unwind_info");
3097 outs() << "Contents of __unwind_info section:\n";
3100 UnwindInfo.getContents(Contents);
3101 const char *Pos = Contents.data();
3103 //===----------------------------------
3105 //===----------------------------------
3107 uint32_t Version = readNext<uint32_t>(Pos);
3108 outs() << " Version: "
3109 << format("0x%" PRIx32, Version) << '\n';
3110 assert(Version == 1 && "only understand version 1");
3112 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
3113 outs() << " Common encodings array section offset: "
3114 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
3115 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
3116 outs() << " Number of common encodings in array: "
3117 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
3119 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
3120 outs() << " Personality function array section offset: "
3121 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
3122 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
3123 outs() << " Number of personality functions in array: "
3124 << format("0x%" PRIx32, NumPersonalities) << '\n';
3126 uint32_t IndicesStart = readNext<uint32_t>(Pos);
3127 outs() << " Index array section offset: "
3128 << format("0x%" PRIx32, IndicesStart) << '\n';
3129 uint32_t NumIndices = readNext<uint32_t>(Pos);
3130 outs() << " Number of indices in array: "
3131 << format("0x%" PRIx32, NumIndices) << '\n';
3133 //===----------------------------------
3134 // A shared list of common encodings
3135 //===----------------------------------
3137 // These occupy indices in the range [0, N] whenever an encoding is referenced
3138 // from a compressed 2nd level index table. In practice the linker only
3139 // creates ~128 of these, so that indices are available to embed encodings in
3140 // the 2nd level index.
3142 SmallVector<uint32_t, 64> CommonEncodings;
3143 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
3144 Pos = Contents.data() + CommonEncodingsStart;
3145 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
3146 uint32_t Encoding = readNext<uint32_t>(Pos);
3147 CommonEncodings.push_back(Encoding);
3149 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
3153 //===----------------------------------
3154 // Personality functions used in this executable
3155 //===----------------------------------
3157 // There should be only a handful of these (one per source language,
3158 // roughly). Particularly since they only get 2 bits in the compact encoding.
3160 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
3161 Pos = Contents.data() + PersonalitiesStart;
3162 for (unsigned i = 0; i < NumPersonalities; ++i) {
3163 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
3164 outs() << " personality[" << i + 1
3165 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
3168 //===----------------------------------
3169 // The level 1 index entries
3170 //===----------------------------------
3172 // These specify an approximate place to start searching for the more detailed
3173 // information, sorted by PC.
3176 uint32_t FunctionOffset;
3177 uint32_t SecondLevelPageStart;
3181 SmallVector<IndexEntry, 4> IndexEntries;
3183 outs() << " Top level indices: (count = " << NumIndices << ")\n";
3184 Pos = Contents.data() + IndicesStart;
3185 for (unsigned i = 0; i < NumIndices; ++i) {
3188 Entry.FunctionOffset = readNext<uint32_t>(Pos);
3189 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
3190 Entry.LSDAStart = readNext<uint32_t>(Pos);
3191 IndexEntries.push_back(Entry);
3193 outs() << " [" << i << "]: "
3194 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
3196 << "2nd level page offset="
3197 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
3198 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
3201 //===----------------------------------
3202 // Next come the LSDA tables
3203 //===----------------------------------
3205 // The LSDA layout is rather implicit: it's a contiguous array of entries from
3206 // the first top-level index's LSDAOffset to the last (sentinel).
3208 outs() << " LSDA descriptors:\n";
3209 Pos = Contents.data() + IndexEntries[0].LSDAStart;
3210 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
3211 (2 * sizeof(uint32_t));
3212 for (int i = 0; i < NumLSDAs; ++i) {
3213 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3214 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
3215 outs() << " [" << i << "]: "
3216 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3218 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
3221 //===----------------------------------
3222 // Finally, the 2nd level indices
3223 //===----------------------------------
3225 // Generally these are 4K in size, and have 2 possible forms:
3226 // + Regular stores up to 511 entries with disparate encodings
3227 // + Compressed stores up to 1021 entries if few enough compact encoding
3229 outs() << " Second level indices:\n";
3230 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
3231 // The final sentinel top-level index has no associated 2nd level page
3232 if (IndexEntries[i].SecondLevelPageStart == 0)
3235 outs() << " Second level index[" << i << "]: "
3236 << "offset in section="
3237 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
3239 << "base function offset="
3240 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
3242 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
3243 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
3245 printRegularSecondLevelUnwindPage(Pos);
3247 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
3250 llvm_unreachable("Do not know how to print this kind of 2nd level page");
3254 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
3255 std::map<uint64_t, SymbolRef> Symbols;
3256 for (const SymbolRef &SymRef : Obj->symbols()) {
3257 // Discard any undefined or absolute symbols. They're not going to take part
3258 // in the convenience lookup for unwind info and just take up resources.
3259 section_iterator Section = Obj->section_end();
3260 SymRef.getSection(Section);
3261 if (Section == Obj->section_end())
3265 SymRef.getAddress(Addr);
3266 Symbols.insert(std::make_pair(Addr, SymRef));
3269 for (const SectionRef &Section : Obj->sections()) {
3271 Section.getName(SectName);
3272 if (SectName == "__compact_unwind")
3273 printMachOCompactUnwindSection(Obj, Symbols, Section);
3274 else if (SectName == "__unwind_info")
3275 printMachOUnwindInfoSection(Obj, Symbols, Section);
3276 else if (SectName == "__eh_frame")
3277 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
3281 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
3282 uint32_t cpusubtype, uint32_t filetype,
3283 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
3285 outs() << "Mach header\n";
3286 outs() << " magic cputype cpusubtype caps filetype ncmds "
3287 "sizeofcmds flags\n";
3289 if (magic == MachO::MH_MAGIC)
3290 outs() << " MH_MAGIC";
3291 else if (magic == MachO::MH_MAGIC_64)
3292 outs() << "MH_MAGIC_64";
3294 outs() << format(" 0x%08" PRIx32, magic);
3296 case MachO::CPU_TYPE_I386:
3298 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3299 case MachO::CPU_SUBTYPE_I386_ALL:
3303 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3307 case MachO::CPU_TYPE_X86_64:
3308 outs() << " X86_64";
3309 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3310 case MachO::CPU_SUBTYPE_X86_64_ALL:
3313 case MachO::CPU_SUBTYPE_X86_64_H:
3314 outs() << " Haswell";
3317 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3321 case MachO::CPU_TYPE_ARM:
3323 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3324 case MachO::CPU_SUBTYPE_ARM_ALL:
3327 case MachO::CPU_SUBTYPE_ARM_V4T:
3330 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
3333 case MachO::CPU_SUBTYPE_ARM_XSCALE:
3334 outs() << " XSCALE";
3336 case MachO::CPU_SUBTYPE_ARM_V6:
3339 case MachO::CPU_SUBTYPE_ARM_V6M:
3342 case MachO::CPU_SUBTYPE_ARM_V7:
3345 case MachO::CPU_SUBTYPE_ARM_V7EM:
3348 case MachO::CPU_SUBTYPE_ARM_V7K:
3351 case MachO::CPU_SUBTYPE_ARM_V7M:
3354 case MachO::CPU_SUBTYPE_ARM_V7S:
3358 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3362 case MachO::CPU_TYPE_ARM64:
3364 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3365 case MachO::CPU_SUBTYPE_ARM64_ALL:
3369 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3373 case MachO::CPU_TYPE_POWERPC:
3375 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3376 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3380 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3384 case MachO::CPU_TYPE_POWERPC64:
3386 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3387 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3391 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3396 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
3399 outs() << format(" 0x%02" PRIx32,
3400 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3403 case MachO::MH_OBJECT:
3404 outs() << " OBJECT";
3406 case MachO::MH_EXECUTE:
3407 outs() << " EXECUTE";
3409 case MachO::MH_FVMLIB:
3410 outs() << " FVMLIB";
3412 case MachO::MH_CORE:
3415 case MachO::MH_PRELOAD:
3416 outs() << " PRELOAD";
3418 case MachO::MH_DYLIB:
3421 case MachO::MH_DYLIB_STUB:
3422 outs() << " DYLIB_STUB";
3424 case MachO::MH_DYLINKER:
3425 outs() << " DYLINKER";
3427 case MachO::MH_BUNDLE:
3428 outs() << " BUNDLE";
3430 case MachO::MH_DSYM:
3433 case MachO::MH_KEXT_BUNDLE:
3434 outs() << " KEXTBUNDLE";
3437 outs() << format(" %10u", filetype);
3440 outs() << format(" %5u", ncmds);
3441 outs() << format(" %10u", sizeofcmds);
3443 if (f & MachO::MH_NOUNDEFS) {
3444 outs() << " NOUNDEFS";
3445 f &= ~MachO::MH_NOUNDEFS;
3447 if (f & MachO::MH_INCRLINK) {
3448 outs() << " INCRLINK";
3449 f &= ~MachO::MH_INCRLINK;
3451 if (f & MachO::MH_DYLDLINK) {
3452 outs() << " DYLDLINK";
3453 f &= ~MachO::MH_DYLDLINK;
3455 if (f & MachO::MH_BINDATLOAD) {
3456 outs() << " BINDATLOAD";
3457 f &= ~MachO::MH_BINDATLOAD;
3459 if (f & MachO::MH_PREBOUND) {
3460 outs() << " PREBOUND";
3461 f &= ~MachO::MH_PREBOUND;
3463 if (f & MachO::MH_SPLIT_SEGS) {
3464 outs() << " SPLIT_SEGS";
3465 f &= ~MachO::MH_SPLIT_SEGS;
3467 if (f & MachO::MH_LAZY_INIT) {
3468 outs() << " LAZY_INIT";
3469 f &= ~MachO::MH_LAZY_INIT;
3471 if (f & MachO::MH_TWOLEVEL) {
3472 outs() << " TWOLEVEL";
3473 f &= ~MachO::MH_TWOLEVEL;
3475 if (f & MachO::MH_FORCE_FLAT) {
3476 outs() << " FORCE_FLAT";
3477 f &= ~MachO::MH_FORCE_FLAT;
3479 if (f & MachO::MH_NOMULTIDEFS) {
3480 outs() << " NOMULTIDEFS";
3481 f &= ~MachO::MH_NOMULTIDEFS;
3483 if (f & MachO::MH_NOFIXPREBINDING) {
3484 outs() << " NOFIXPREBINDING";
3485 f &= ~MachO::MH_NOFIXPREBINDING;
3487 if (f & MachO::MH_PREBINDABLE) {
3488 outs() << " PREBINDABLE";
3489 f &= ~MachO::MH_PREBINDABLE;
3491 if (f & MachO::MH_ALLMODSBOUND) {
3492 outs() << " ALLMODSBOUND";
3493 f &= ~MachO::MH_ALLMODSBOUND;
3495 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
3496 outs() << " SUBSECTIONS_VIA_SYMBOLS";
3497 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
3499 if (f & MachO::MH_CANONICAL) {
3500 outs() << " CANONICAL";
3501 f &= ~MachO::MH_CANONICAL;
3503 if (f & MachO::MH_WEAK_DEFINES) {
3504 outs() << " WEAK_DEFINES";
3505 f &= ~MachO::MH_WEAK_DEFINES;
3507 if (f & MachO::MH_BINDS_TO_WEAK) {
3508 outs() << " BINDS_TO_WEAK";
3509 f &= ~MachO::MH_BINDS_TO_WEAK;
3511 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
3512 outs() << " ALLOW_STACK_EXECUTION";
3513 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
3515 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
3516 outs() << " DEAD_STRIPPABLE_DYLIB";
3517 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
3519 if (f & MachO::MH_PIE) {
3521 f &= ~MachO::MH_PIE;
3523 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
3524 outs() << " NO_REEXPORTED_DYLIBS";
3525 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
3527 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
3528 outs() << " MH_HAS_TLV_DESCRIPTORS";
3529 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
3531 if (f & MachO::MH_NO_HEAP_EXECUTION) {
3532 outs() << " MH_NO_HEAP_EXECUTION";
3533 f &= ~MachO::MH_NO_HEAP_EXECUTION;
3535 if (f & MachO::MH_APP_EXTENSION_SAFE) {
3536 outs() << " APP_EXTENSION_SAFE";
3537 f &= ~MachO::MH_APP_EXTENSION_SAFE;
3539 if (f != 0 || flags == 0)
3540 outs() << format(" 0x%08" PRIx32, f);
3542 outs() << format(" 0x%08" PRIx32, magic);
3543 outs() << format(" %7d", cputype);
3544 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3545 outs() << format(" 0x%02" PRIx32,
3546 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3547 outs() << format(" %10u", filetype);
3548 outs() << format(" %5u", ncmds);
3549 outs() << format(" %10u", sizeofcmds);
3550 outs() << format(" 0x%08" PRIx32, flags);
3555 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
3556 StringRef SegName, uint64_t vmaddr,
3557 uint64_t vmsize, uint64_t fileoff,
3558 uint64_t filesize, uint32_t maxprot,
3559 uint32_t initprot, uint32_t nsects,
3560 uint32_t flags, uint32_t object_size,
3562 uint64_t expected_cmdsize;
3563 if (cmd == MachO::LC_SEGMENT) {
3564 outs() << " cmd LC_SEGMENT\n";
3565 expected_cmdsize = nsects;
3566 expected_cmdsize *= sizeof(struct MachO::section);
3567 expected_cmdsize += sizeof(struct MachO::segment_command);
3569 outs() << " cmd LC_SEGMENT_64\n";
3570 expected_cmdsize = nsects;
3571 expected_cmdsize *= sizeof(struct MachO::section_64);
3572 expected_cmdsize += sizeof(struct MachO::segment_command_64);
3574 outs() << " cmdsize " << cmdsize;
3575 if (cmdsize != expected_cmdsize)
3576 outs() << " Inconsistent size\n";
3579 outs() << " segname " << SegName << "\n";
3580 if (cmd == MachO::LC_SEGMENT_64) {
3581 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
3582 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
3584 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
3585 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
3587 outs() << " fileoff " << fileoff;
3588 if (fileoff > object_size)
3589 outs() << " (past end of file)\n";
3592 outs() << " filesize " << filesize;
3593 if (fileoff + filesize > object_size)
3594 outs() << " (past end of file)\n";
3599 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3600 MachO::VM_PROT_EXECUTE)) != 0)
3601 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
3603 if (maxprot & MachO::VM_PROT_READ)
3604 outs() << " maxprot r";
3606 outs() << " maxprot -";
3607 if (maxprot & MachO::VM_PROT_WRITE)
3611 if (maxprot & MachO::VM_PROT_EXECUTE)
3617 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3618 MachO::VM_PROT_EXECUTE)) != 0)
3619 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
3621 if (initprot & MachO::VM_PROT_READ)
3622 outs() << " initprot r";
3624 outs() << " initprot -";
3625 if (initprot & MachO::VM_PROT_WRITE)
3629 if (initprot & MachO::VM_PROT_EXECUTE)
3635 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
3636 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
3638 outs() << " nsects " << nsects << "\n";
3642 outs() << " (none)\n";
3644 if (flags & MachO::SG_HIGHVM) {
3645 outs() << " HIGHVM";
3646 flags &= ~MachO::SG_HIGHVM;
3648 if (flags & MachO::SG_FVMLIB) {
3649 outs() << " FVMLIB";
3650 flags &= ~MachO::SG_FVMLIB;
3652 if (flags & MachO::SG_NORELOC) {
3653 outs() << " NORELOC";
3654 flags &= ~MachO::SG_NORELOC;
3656 if (flags & MachO::SG_PROTECTED_VERSION_1) {
3657 outs() << " PROTECTED_VERSION_1";
3658 flags &= ~MachO::SG_PROTECTED_VERSION_1;
3661 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
3666 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
3670 static void PrintSection(const char *sectname, const char *segname,
3671 uint64_t addr, uint64_t size, uint32_t offset,
3672 uint32_t align, uint32_t reloff, uint32_t nreloc,
3673 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
3674 uint32_t cmd, const char *sg_segname,
3675 uint32_t filetype, uint32_t object_size,
3677 outs() << "Section\n";
3678 outs() << " sectname " << format("%.16s\n", sectname);
3679 outs() << " segname " << format("%.16s", segname);
3680 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
3681 outs() << " (does not match segment)\n";
3684 if (cmd == MachO::LC_SEGMENT_64) {
3685 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
3686 outs() << " size " << format("0x%016" PRIx64, size);
3688 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
3689 outs() << " size " << format("0x%08" PRIx64, size);
3691 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
3692 outs() << " (past end of file)\n";
3695 outs() << " offset " << offset;
3696 if (offset > object_size)
3697 outs() << " (past end of file)\n";
3700 uint32_t align_shifted = 1 << align;
3701 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
3702 outs() << " reloff " << reloff;
3703 if (reloff > object_size)
3704 outs() << " (past end of file)\n";
3707 outs() << " nreloc " << nreloc;
3708 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
3709 outs() << " (past end of file)\n";
3712 uint32_t section_type = flags & MachO::SECTION_TYPE;
3715 if (section_type == MachO::S_REGULAR)
3716 outs() << " S_REGULAR\n";
3717 else if (section_type == MachO::S_ZEROFILL)
3718 outs() << " S_ZEROFILL\n";
3719 else if (section_type == MachO::S_CSTRING_LITERALS)
3720 outs() << " S_CSTRING_LITERALS\n";
3721 else if (section_type == MachO::S_4BYTE_LITERALS)
3722 outs() << " S_4BYTE_LITERALS\n";
3723 else if (section_type == MachO::S_8BYTE_LITERALS)
3724 outs() << " S_8BYTE_LITERALS\n";
3725 else if (section_type == MachO::S_16BYTE_LITERALS)
3726 outs() << " S_16BYTE_LITERALS\n";
3727 else if (section_type == MachO::S_LITERAL_POINTERS)
3728 outs() << " S_LITERAL_POINTERS\n";
3729 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
3730 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
3731 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
3732 outs() << " S_LAZY_SYMBOL_POINTERS\n";
3733 else if (section_type == MachO::S_SYMBOL_STUBS)
3734 outs() << " S_SYMBOL_STUBS\n";
3735 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
3736 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
3737 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
3738 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
3739 else if (section_type == MachO::S_COALESCED)
3740 outs() << " S_COALESCED\n";
3741 else if (section_type == MachO::S_INTERPOSING)
3742 outs() << " S_INTERPOSING\n";
3743 else if (section_type == MachO::S_DTRACE_DOF)
3744 outs() << " S_DTRACE_DOF\n";
3745 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
3746 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
3747 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
3748 outs() << " S_THREAD_LOCAL_REGULAR\n";
3749 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
3750 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
3751 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
3752 outs() << " S_THREAD_LOCAL_VARIABLES\n";
3753 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
3754 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
3755 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
3756 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
3758 outs() << format("0x%08" PRIx32, section_type) << "\n";
3759 outs() << "attributes";
3760 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
3761 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
3762 outs() << " PURE_INSTRUCTIONS";
3763 if (section_attributes & MachO::S_ATTR_NO_TOC)
3764 outs() << " NO_TOC";
3765 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
3766 outs() << " STRIP_STATIC_SYMS";
3767 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
3768 outs() << " NO_DEAD_STRIP";
3769 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
3770 outs() << " LIVE_SUPPORT";
3771 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
3772 outs() << " SELF_MODIFYING_CODE";
3773 if (section_attributes & MachO::S_ATTR_DEBUG)
3775 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
3776 outs() << " SOME_INSTRUCTIONS";
3777 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
3778 outs() << " EXT_RELOC";
3779 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
3780 outs() << " LOC_RELOC";
3781 if (section_attributes == 0)
3782 outs() << " (none)";
3785 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
3786 outs() << " reserved1 " << reserved1;
3787 if (section_type == MachO::S_SYMBOL_STUBS ||
3788 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3789 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3790 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3791 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
3792 outs() << " (index into indirect symbol table)\n";
3795 outs() << " reserved2 " << reserved2;
3796 if (section_type == MachO::S_SYMBOL_STUBS)
3797 outs() << " (size of stubs)\n";
3802 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
3803 uint32_t object_size) {
3804 outs() << " cmd LC_SYMTAB\n";
3805 outs() << " cmdsize " << st.cmdsize;
3806 if (st.cmdsize != sizeof(struct MachO::symtab_command))
3807 outs() << " Incorrect size\n";
3810 outs() << " symoff " << st.symoff;
3811 if (st.symoff > object_size)
3812 outs() << " (past end of file)\n";
3815 outs() << " nsyms " << st.nsyms;
3818 big_size = st.nsyms;
3819 big_size *= sizeof(struct MachO::nlist_64);
3820 big_size += st.symoff;
3821 if (big_size > object_size)
3822 outs() << " (past end of file)\n";
3826 big_size = st.nsyms;
3827 big_size *= sizeof(struct MachO::nlist);
3828 big_size += st.symoff;
3829 if (big_size > object_size)
3830 outs() << " (past end of file)\n";
3834 outs() << " stroff " << st.stroff;
3835 if (st.stroff > object_size)
3836 outs() << " (past end of file)\n";
3839 outs() << " strsize " << st.strsize;
3840 big_size = st.stroff;
3841 big_size += st.strsize;
3842 if (big_size > object_size)
3843 outs() << " (past end of file)\n";
3848 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
3849 uint32_t nsyms, uint32_t object_size,
3851 outs() << " cmd LC_DYSYMTAB\n";
3852 outs() << " cmdsize " << dyst.cmdsize;
3853 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
3854 outs() << " Incorrect size\n";
3857 outs() << " ilocalsym " << dyst.ilocalsym;
3858 if (dyst.ilocalsym > nsyms)
3859 outs() << " (greater than the number of symbols)\n";
3862 outs() << " nlocalsym " << dyst.nlocalsym;
3864 big_size = dyst.ilocalsym;
3865 big_size += dyst.nlocalsym;
3866 if (big_size > nsyms)
3867 outs() << " (past the end of the symbol table)\n";
3870 outs() << " iextdefsym " << dyst.iextdefsym;
3871 if (dyst.iextdefsym > nsyms)
3872 outs() << " (greater than the number of symbols)\n";
3875 outs() << " nextdefsym " << dyst.nextdefsym;
3876 big_size = dyst.iextdefsym;
3877 big_size += dyst.nextdefsym;
3878 if (big_size > nsyms)
3879 outs() << " (past the end of the symbol table)\n";
3882 outs() << " iundefsym " << dyst.iundefsym;
3883 if (dyst.iundefsym > nsyms)
3884 outs() << " (greater than the number of symbols)\n";
3887 outs() << " nundefsym " << dyst.nundefsym;
3888 big_size = dyst.iundefsym;
3889 big_size += dyst.nundefsym;
3890 if (big_size > nsyms)
3891 outs() << " (past the end of the symbol table)\n";
3894 outs() << " tocoff " << dyst.tocoff;
3895 if (dyst.tocoff > object_size)
3896 outs() << " (past end of file)\n";
3899 outs() << " ntoc " << dyst.ntoc;
3900 big_size = dyst.ntoc;
3901 big_size *= sizeof(struct MachO::dylib_table_of_contents);
3902 big_size += dyst.tocoff;
3903 if (big_size > object_size)
3904 outs() << " (past end of file)\n";
3907 outs() << " modtaboff " << dyst.modtaboff;
3908 if (dyst.modtaboff > object_size)
3909 outs() << " (past end of file)\n";
3912 outs() << " nmodtab " << dyst.nmodtab;
3915 modtabend = dyst.nmodtab;
3916 modtabend *= sizeof(struct MachO::dylib_module_64);
3917 modtabend += dyst.modtaboff;
3919 modtabend = dyst.nmodtab;
3920 modtabend *= sizeof(struct MachO::dylib_module);
3921 modtabend += dyst.modtaboff;
3923 if (modtabend > object_size)
3924 outs() << " (past end of file)\n";
3927 outs() << " extrefsymoff " << dyst.extrefsymoff;
3928 if (dyst.extrefsymoff > object_size)
3929 outs() << " (past end of file)\n";
3932 outs() << " nextrefsyms " << dyst.nextrefsyms;
3933 big_size = dyst.nextrefsyms;
3934 big_size *= sizeof(struct MachO::dylib_reference);
3935 big_size += dyst.extrefsymoff;
3936 if (big_size > object_size)
3937 outs() << " (past end of file)\n";
3940 outs() << " indirectsymoff " << dyst.indirectsymoff;
3941 if (dyst.indirectsymoff > object_size)
3942 outs() << " (past end of file)\n";
3945 outs() << " nindirectsyms " << dyst.nindirectsyms;
3946 big_size = dyst.nindirectsyms;
3947 big_size *= sizeof(uint32_t);
3948 big_size += dyst.indirectsymoff;
3949 if (big_size > object_size)
3950 outs() << " (past end of file)\n";
3953 outs() << " extreloff " << dyst.extreloff;
3954 if (dyst.extreloff > object_size)
3955 outs() << " (past end of file)\n";
3958 outs() << " nextrel " << dyst.nextrel;
3959 big_size = dyst.nextrel;
3960 big_size *= sizeof(struct MachO::relocation_info);
3961 big_size += dyst.extreloff;
3962 if (big_size > object_size)
3963 outs() << " (past end of file)\n";
3966 outs() << " locreloff " << dyst.locreloff;
3967 if (dyst.locreloff > object_size)
3968 outs() << " (past end of file)\n";
3971 outs() << " nlocrel " << dyst.nlocrel;
3972 big_size = dyst.nlocrel;
3973 big_size *= sizeof(struct MachO::relocation_info);
3974 big_size += dyst.locreloff;
3975 if (big_size > object_size)
3976 outs() << " (past end of file)\n";
3981 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
3982 uint32_t object_size) {
3983 if (dc.cmd == MachO::LC_DYLD_INFO)
3984 outs() << " cmd LC_DYLD_INFO\n";
3986 outs() << " cmd LC_DYLD_INFO_ONLY\n";
3987 outs() << " cmdsize " << dc.cmdsize;
3988 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
3989 outs() << " Incorrect size\n";
3992 outs() << " rebase_off " << dc.rebase_off;
3993 if (dc.rebase_off > object_size)
3994 outs() << " (past end of file)\n";
3997 outs() << " rebase_size " << dc.rebase_size;
3999 big_size = dc.rebase_off;
4000 big_size += dc.rebase_size;
4001 if (big_size > object_size)
4002 outs() << " (past end of file)\n";
4005 outs() << " bind_off " << dc.bind_off;
4006 if (dc.bind_off > object_size)
4007 outs() << " (past end of file)\n";
4010 outs() << " bind_size " << dc.bind_size;
4011 big_size = dc.bind_off;
4012 big_size += dc.bind_size;
4013 if (big_size > object_size)
4014 outs() << " (past end of file)\n";
4017 outs() << " weak_bind_off " << dc.weak_bind_off;
4018 if (dc.weak_bind_off > object_size)
4019 outs() << " (past end of file)\n";
4022 outs() << " weak_bind_size " << dc.weak_bind_size;
4023 big_size = dc.weak_bind_off;
4024 big_size += dc.weak_bind_size;
4025 if (big_size > object_size)
4026 outs() << " (past end of file)\n";
4029 outs() << " lazy_bind_off " << dc.lazy_bind_off;
4030 if (dc.lazy_bind_off > object_size)
4031 outs() << " (past end of file)\n";
4034 outs() << " lazy_bind_size " << dc.lazy_bind_size;
4035 big_size = dc.lazy_bind_off;
4036 big_size += dc.lazy_bind_size;
4037 if (big_size > object_size)
4038 outs() << " (past end of file)\n";
4041 outs() << " export_off " << dc.export_off;
4042 if (dc.export_off > object_size)
4043 outs() << " (past end of file)\n";
4046 outs() << " export_size " << dc.export_size;
4047 big_size = dc.export_off;
4048 big_size += dc.export_size;
4049 if (big_size > object_size)
4050 outs() << " (past end of file)\n";
4055 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
4057 if (dyld.cmd == MachO::LC_ID_DYLINKER)
4058 outs() << " cmd LC_ID_DYLINKER\n";
4059 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
4060 outs() << " cmd LC_LOAD_DYLINKER\n";
4061 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
4062 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
4064 outs() << " cmd ?(" << dyld.cmd << ")\n";
4065 outs() << " cmdsize " << dyld.cmdsize;
4066 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
4067 outs() << " Incorrect size\n";
4070 if (dyld.name >= dyld.cmdsize)
4071 outs() << " name ?(bad offset " << dyld.name << ")\n";
4073 const char *P = (const char *)(Ptr) + dyld.name;
4074 outs() << " name " << P << " (offset " << dyld.name << ")\n";
4078 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
4079 outs() << " cmd LC_UUID\n";
4080 outs() << " cmdsize " << uuid.cmdsize;
4081 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
4082 outs() << " Incorrect size\n";
4086 outs() << format("%02" PRIX32, uuid.uuid[0]);
4087 outs() << format("%02" PRIX32, uuid.uuid[1]);
4088 outs() << format("%02" PRIX32, uuid.uuid[2]);
4089 outs() << format("%02" PRIX32, uuid.uuid[3]);
4091 outs() << format("%02" PRIX32, uuid.uuid[4]);
4092 outs() << format("%02" PRIX32, uuid.uuid[5]);
4094 outs() << format("%02" PRIX32, uuid.uuid[6]);
4095 outs() << format("%02" PRIX32, uuid.uuid[7]);
4097 outs() << format("%02" PRIX32, uuid.uuid[8]);
4098 outs() << format("%02" PRIX32, uuid.uuid[9]);
4100 outs() << format("%02" PRIX32, uuid.uuid[10]);
4101 outs() << format("%02" PRIX32, uuid.uuid[11]);
4102 outs() << format("%02" PRIX32, uuid.uuid[12]);
4103 outs() << format("%02" PRIX32, uuid.uuid[13]);
4104 outs() << format("%02" PRIX32, uuid.uuid[14]);
4105 outs() << format("%02" PRIX32, uuid.uuid[15]);
4109 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
4110 outs() << " cmd LC_RPATH\n";
4111 outs() << " cmdsize " << rpath.cmdsize;
4112 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
4113 outs() << " Incorrect size\n";
4116 if (rpath.path >= rpath.cmdsize)
4117 outs() << " path ?(bad offset " << rpath.path << ")\n";
4119 const char *P = (const char *)(Ptr) + rpath.path;
4120 outs() << " path " << P << " (offset " << rpath.path << ")\n";
4124 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
4125 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
4126 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
4127 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
4128 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
4130 outs() << " cmd " << vd.cmd << " (?)\n";
4131 outs() << " cmdsize " << vd.cmdsize;
4132 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
4133 outs() << " Incorrect size\n";
4136 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
4137 << ((vd.version >> 8) & 0xff);
4138 if ((vd.version & 0xff) != 0)
4139 outs() << "." << (vd.version & 0xff);
4142 outs() << " sdk n/a";
4144 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
4145 << ((vd.sdk >> 8) & 0xff);
4147 if ((vd.sdk & 0xff) != 0)
4148 outs() << "." << (vd.sdk & 0xff);
4152 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
4153 outs() << " cmd LC_SOURCE_VERSION\n";
4154 outs() << " cmdsize " << sd.cmdsize;
4155 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
4156 outs() << " Incorrect size\n";
4159 uint64_t a = (sd.version >> 40) & 0xffffff;
4160 uint64_t b = (sd.version >> 30) & 0x3ff;
4161 uint64_t c = (sd.version >> 20) & 0x3ff;
4162 uint64_t d = (sd.version >> 10) & 0x3ff;
4163 uint64_t e = sd.version & 0x3ff;
4164 outs() << " version " << a << "." << b;
4166 outs() << "." << c << "." << d << "." << e;
4168 outs() << "." << c << "." << d;
4174 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
4175 outs() << " cmd LC_MAIN\n";
4176 outs() << " cmdsize " << ep.cmdsize;
4177 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
4178 outs() << " Incorrect size\n";
4181 outs() << " entryoff " << ep.entryoff << "\n";
4182 outs() << " stacksize " << ep.stacksize << "\n";
4185 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
4186 uint32_t object_size) {
4187 outs() << " cmd LC_ENCRYPTION_INFO\n";
4188 outs() << " cmdsize " << ec.cmdsize;
4189 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
4190 outs() << " Incorrect size\n";
4193 outs() << " cryptoff " << ec.cryptoff;
4194 if (ec.cryptoff > object_size)
4195 outs() << " (past end of file)\n";
4198 outs() << " cryptsize " << ec.cryptsize;
4199 if (ec.cryptsize > object_size)
4200 outs() << " (past end of file)\n";
4203 outs() << " cryptid " << ec.cryptid << "\n";
4206 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
4207 uint32_t object_size) {
4208 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
4209 outs() << " cmdsize " << ec.cmdsize;
4210 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
4211 outs() << " Incorrect size\n";
4214 outs() << " cryptoff " << ec.cryptoff;
4215 if (ec.cryptoff > object_size)
4216 outs() << " (past end of file)\n";
4219 outs() << " cryptsize " << ec.cryptsize;
4220 if (ec.cryptsize > object_size)
4221 outs() << " (past end of file)\n";
4224 outs() << " cryptid " << ec.cryptid << "\n";
4225 outs() << " pad " << ec.pad << "\n";
4228 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
4230 outs() << " cmd LC_LINKER_OPTION\n";
4231 outs() << " cmdsize " << lo.cmdsize;
4232 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
4233 outs() << " Incorrect size\n";
4236 outs() << " count " << lo.count << "\n";
4237 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
4238 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
4241 while (*string == '\0' && left > 0) {
4247 outs() << " string #" << i << " " << format("%.*s\n", left, string);
4248 uint32_t NullPos = StringRef(string, left).find('\0');
4249 uint32_t len = std::min(NullPos, left) + 1;
4255 outs() << " count " << lo.count << " does not match number of strings "
4259 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
4261 outs() << " cmd LC_SUB_FRAMEWORK\n";
4262 outs() << " cmdsize " << sub.cmdsize;
4263 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
4264 outs() << " Incorrect size\n";
4267 if (sub.umbrella < sub.cmdsize) {
4268 const char *P = Ptr + sub.umbrella;
4269 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
4271 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
4275 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
4277 outs() << " cmd LC_SUB_UMBRELLA\n";
4278 outs() << " cmdsize " << sub.cmdsize;
4279 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
4280 outs() << " Incorrect size\n";
4283 if (sub.sub_umbrella < sub.cmdsize) {
4284 const char *P = Ptr + sub.sub_umbrella;
4285 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
4287 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
4291 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
4293 outs() << " cmd LC_SUB_LIBRARY\n";
4294 outs() << " cmdsize " << sub.cmdsize;
4295 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
4296 outs() << " Incorrect size\n";
4299 if (sub.sub_library < sub.cmdsize) {
4300 const char *P = Ptr + sub.sub_library;
4301 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
4303 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
4307 static void PrintSubClientCommand(MachO::sub_client_command sub,
4309 outs() << " cmd LC_SUB_CLIENT\n";
4310 outs() << " cmdsize " << sub.cmdsize;
4311 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
4312 outs() << " Incorrect size\n";
4315 if (sub.client < sub.cmdsize) {
4316 const char *P = Ptr + sub.client;
4317 outs() << " client " << P << " (offset " << sub.client << ")\n";
4319 outs() << " client ?(bad offset " << sub.client << ")\n";
4323 static void PrintRoutinesCommand(MachO::routines_command r) {
4324 outs() << " cmd LC_ROUTINES\n";
4325 outs() << " cmdsize " << r.cmdsize;
4326 if (r.cmdsize != sizeof(struct MachO::routines_command))
4327 outs() << " Incorrect size\n";
4330 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
4331 outs() << " init_module " << r.init_module << "\n";
4332 outs() << " reserved1 " << r.reserved1 << "\n";
4333 outs() << " reserved2 " << r.reserved2 << "\n";
4334 outs() << " reserved3 " << r.reserved3 << "\n";
4335 outs() << " reserved4 " << r.reserved4 << "\n";
4336 outs() << " reserved5 " << r.reserved5 << "\n";
4337 outs() << " reserved6 " << r.reserved6 << "\n";
4340 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
4341 outs() << " cmd LC_ROUTINES_64\n";
4342 outs() << " cmdsize " << r.cmdsize;
4343 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
4344 outs() << " Incorrect size\n";
4347 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
4348 outs() << " init_module " << r.init_module << "\n";
4349 outs() << " reserved1 " << r.reserved1 << "\n";
4350 outs() << " reserved2 " << r.reserved2 << "\n";
4351 outs() << " reserved3 " << r.reserved3 << "\n";
4352 outs() << " reserved4 " << r.reserved4 << "\n";
4353 outs() << " reserved5 " << r.reserved5 << "\n";
4354 outs() << " reserved6 " << r.reserved6 << "\n";
4357 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4358 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
4359 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4360 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4361 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
4362 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4363 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4364 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
4365 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4366 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4367 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
4368 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4369 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4370 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
4371 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4372 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4373 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
4374 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4375 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
4376 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
4377 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4378 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
4381 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
4383 outs() << "\t mmst_reg ";
4384 for (f = 0; f < 10; f++)
4385 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
4387 outs() << "\t mmst_rsrv ";
4388 for (f = 0; f < 6; f++)
4389 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
4393 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
4395 outs() << "\t xmm_reg ";
4396 for (f = 0; f < 16; f++)
4397 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
4401 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
4402 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
4403 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
4404 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
4405 outs() << " denorm " << fpu.fpu_fcw.denorm;
4406 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
4407 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
4408 outs() << " undfl " << fpu.fpu_fcw.undfl;
4409 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
4410 outs() << "\t\t pc ";
4411 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
4412 outs() << "FP_PREC_24B ";
4413 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
4414 outs() << "FP_PREC_53B ";
4415 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
4416 outs() << "FP_PREC_64B ";
4418 outs() << fpu.fpu_fcw.pc << " ";
4420 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
4421 outs() << "FP_RND_NEAR ";
4422 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
4423 outs() << "FP_RND_DOWN ";
4424 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
4425 outs() << "FP_RND_UP ";
4426 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
4427 outs() << "FP_CHOP ";
4429 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
4430 outs() << " denorm " << fpu.fpu_fsw.denorm;
4431 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
4432 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
4433 outs() << " undfl " << fpu.fpu_fsw.undfl;
4434 outs() << " precis " << fpu.fpu_fsw.precis;
4435 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
4436 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
4437 outs() << " c0 " << fpu.fpu_fsw.c0;
4438 outs() << " c1 " << fpu.fpu_fsw.c1;
4439 outs() << " c2 " << fpu.fpu_fsw.c2;
4440 outs() << " tos " << fpu.fpu_fsw.tos;
4441 outs() << " c3 " << fpu.fpu_fsw.c3;
4442 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
4443 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
4444 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
4445 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
4446 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
4447 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
4448 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
4449 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
4450 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
4451 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
4452 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
4453 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
4455 outs() << "\t fpu_stmm0:\n";
4456 Print_mmst_reg(fpu.fpu_stmm0);
4457 outs() << "\t fpu_stmm1:\n";
4458 Print_mmst_reg(fpu.fpu_stmm1);
4459 outs() << "\t fpu_stmm2:\n";
4460 Print_mmst_reg(fpu.fpu_stmm2);
4461 outs() << "\t fpu_stmm3:\n";
4462 Print_mmst_reg(fpu.fpu_stmm3);
4463 outs() << "\t fpu_stmm4:\n";
4464 Print_mmst_reg(fpu.fpu_stmm4);
4465 outs() << "\t fpu_stmm5:\n";
4466 Print_mmst_reg(fpu.fpu_stmm5);
4467 outs() << "\t fpu_stmm6:\n";
4468 Print_mmst_reg(fpu.fpu_stmm6);
4469 outs() << "\t fpu_stmm7:\n";
4470 Print_mmst_reg(fpu.fpu_stmm7);
4471 outs() << "\t fpu_xmm0:\n";
4472 Print_xmm_reg(fpu.fpu_xmm0);
4473 outs() << "\t fpu_xmm1:\n";
4474 Print_xmm_reg(fpu.fpu_xmm1);
4475 outs() << "\t fpu_xmm2:\n";
4476 Print_xmm_reg(fpu.fpu_xmm2);
4477 outs() << "\t fpu_xmm3:\n";
4478 Print_xmm_reg(fpu.fpu_xmm3);
4479 outs() << "\t fpu_xmm4:\n";
4480 Print_xmm_reg(fpu.fpu_xmm4);
4481 outs() << "\t fpu_xmm5:\n";
4482 Print_xmm_reg(fpu.fpu_xmm5);
4483 outs() << "\t fpu_xmm6:\n";
4484 Print_xmm_reg(fpu.fpu_xmm6);
4485 outs() << "\t fpu_xmm7:\n";
4486 Print_xmm_reg(fpu.fpu_xmm7);
4487 outs() << "\t fpu_xmm8:\n";
4488 Print_xmm_reg(fpu.fpu_xmm8);
4489 outs() << "\t fpu_xmm9:\n";
4490 Print_xmm_reg(fpu.fpu_xmm9);
4491 outs() << "\t fpu_xmm10:\n";
4492 Print_xmm_reg(fpu.fpu_xmm10);
4493 outs() << "\t fpu_xmm11:\n";
4494 Print_xmm_reg(fpu.fpu_xmm11);
4495 outs() << "\t fpu_xmm12:\n";
4496 Print_xmm_reg(fpu.fpu_xmm12);
4497 outs() << "\t fpu_xmm13:\n";
4498 Print_xmm_reg(fpu.fpu_xmm13);
4499 outs() << "\t fpu_xmm14:\n";
4500 Print_xmm_reg(fpu.fpu_xmm14);
4501 outs() << "\t fpu_xmm15:\n";
4502 Print_xmm_reg(fpu.fpu_xmm15);
4503 outs() << "\t fpu_rsrv4:\n";
4504 for (uint32_t f = 0; f < 6; f++) {
4506 for (uint32_t g = 0; g < 16; g++)
4507 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
4510 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
4514 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
4515 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
4516 outs() << " err " << format("0x%08" PRIx32, exc64.err);
4517 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
4520 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
4521 bool isLittleEndian, uint32_t cputype) {
4522 if (t.cmd == MachO::LC_THREAD)
4523 outs() << " cmd LC_THREAD\n";
4524 else if (t.cmd == MachO::LC_UNIXTHREAD)
4525 outs() << " cmd LC_UNIXTHREAD\n";
4527 outs() << " cmd " << t.cmd << " (unknown)\n";
4528 outs() << " cmdsize " << t.cmdsize;
4529 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
4530 outs() << " Incorrect size\n";
4534 const char *begin = Ptr + sizeof(struct MachO::thread_command);
4535 const char *end = Ptr + t.cmdsize;
4536 uint32_t flavor, count, left;
4537 if (cputype == MachO::CPU_TYPE_X86_64) {
4538 while (begin < end) {
4539 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4540 memcpy((char *)&flavor, begin, sizeof(uint32_t));
4541 begin += sizeof(uint32_t);
4546 if (isLittleEndian != sys::IsLittleEndianHost)
4547 sys::swapByteOrder(flavor);
4548 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4549 memcpy((char *)&count, begin, sizeof(uint32_t));
4550 begin += sizeof(uint32_t);
4555 if (isLittleEndian != sys::IsLittleEndianHost)
4556 sys::swapByteOrder(count);
4557 if (flavor == MachO::x86_THREAD_STATE64) {
4558 outs() << " flavor x86_THREAD_STATE64\n";
4559 if (count == MachO::x86_THREAD_STATE64_COUNT)
4560 outs() << " count x86_THREAD_STATE64_COUNT\n";
4562 outs() << " count " << count
4563 << " (not x86_THREAD_STATE64_COUNT)\n";
4564 MachO::x86_thread_state64_t cpu64;
4566 if (left >= sizeof(MachO::x86_thread_state64_t)) {
4567 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
4568 begin += sizeof(MachO::x86_thread_state64_t);
4570 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
4571 memcpy(&cpu64, begin, left);
4574 if (isLittleEndian != sys::IsLittleEndianHost)
4576 Print_x86_thread_state64_t(cpu64);
4577 } else if (flavor == MachO::x86_THREAD_STATE) {
4578 outs() << " flavor x86_THREAD_STATE\n";
4579 if (count == MachO::x86_THREAD_STATE_COUNT)
4580 outs() << " count x86_THREAD_STATE_COUNT\n";
4582 outs() << " count " << count
4583 << " (not x86_THREAD_STATE_COUNT)\n";
4584 struct MachO::x86_thread_state_t ts;
4586 if (left >= sizeof(MachO::x86_thread_state_t)) {
4587 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
4588 begin += sizeof(MachO::x86_thread_state_t);
4590 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
4591 memcpy(&ts, begin, left);
4594 if (isLittleEndian != sys::IsLittleEndianHost)
4596 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
4597 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
4598 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
4599 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
4601 outs() << "tsh.count " << ts.tsh.count
4602 << " (not x86_THREAD_STATE64_COUNT\n";
4603 Print_x86_thread_state64_t(ts.uts.ts64);
4605 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
4606 << ts.tsh.count << "\n";
4608 } else if (flavor == MachO::x86_FLOAT_STATE) {
4609 outs() << " flavor x86_FLOAT_STATE\n";
4610 if (count == MachO::x86_FLOAT_STATE_COUNT)
4611 outs() << " count x86_FLOAT_STATE_COUNT\n";
4613 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
4614 struct MachO::x86_float_state_t fs;
4616 if (left >= sizeof(MachO::x86_float_state_t)) {
4617 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
4618 begin += sizeof(MachO::x86_float_state_t);
4620 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
4621 memcpy(&fs, begin, left);
4624 if (isLittleEndian != sys::IsLittleEndianHost)
4626 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
4627 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
4628 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
4629 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
4631 outs() << "fsh.count " << fs.fsh.count
4632 << " (not x86_FLOAT_STATE64_COUNT\n";
4633 Print_x86_float_state_t(fs.ufs.fs64);
4635 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
4636 << fs.fsh.count << "\n";
4638 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
4639 outs() << " flavor x86_EXCEPTION_STATE\n";
4640 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
4641 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
4643 outs() << " count " << count
4644 << " (not x86_EXCEPTION_STATE_COUNT)\n";
4645 struct MachO::x86_exception_state_t es;
4647 if (left >= sizeof(MachO::x86_exception_state_t)) {
4648 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
4649 begin += sizeof(MachO::x86_exception_state_t);
4651 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
4652 memcpy(&es, begin, left);
4655 if (isLittleEndian != sys::IsLittleEndianHost)
4657 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
4658 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
4659 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
4660 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
4662 outs() << "\t esh.count " << es.esh.count
4663 << " (not x86_EXCEPTION_STATE64_COUNT\n";
4664 Print_x86_exception_state_t(es.ues.es64);
4666 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
4667 << es.esh.count << "\n";
4670 outs() << " flavor " << flavor << " (unknown)\n";
4671 outs() << " count " << count << "\n";
4672 outs() << " state (unknown)\n";
4673 begin += count * sizeof(uint32_t);
4677 while (begin < end) {
4678 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4679 memcpy((char *)&flavor, begin, sizeof(uint32_t));
4680 begin += sizeof(uint32_t);
4685 if (isLittleEndian != sys::IsLittleEndianHost)
4686 sys::swapByteOrder(flavor);
4687 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4688 memcpy((char *)&count, begin, sizeof(uint32_t));
4689 begin += sizeof(uint32_t);
4694 if (isLittleEndian != sys::IsLittleEndianHost)
4695 sys::swapByteOrder(count);
4696 outs() << " flavor " << flavor << "\n";
4697 outs() << " count " << count << "\n";
4698 outs() << " state (Unknown cputype/cpusubtype)\n";
4699 begin += count * sizeof(uint32_t);
4704 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
4705 if (dl.cmd == MachO::LC_ID_DYLIB)
4706 outs() << " cmd LC_ID_DYLIB\n";
4707 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
4708 outs() << " cmd LC_LOAD_DYLIB\n";
4709 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
4710 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
4711 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
4712 outs() << " cmd LC_REEXPORT_DYLIB\n";
4713 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
4714 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
4715 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
4716 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
4718 outs() << " cmd " << dl.cmd << " (unknown)\n";
4719 outs() << " cmdsize " << dl.cmdsize;
4720 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
4721 outs() << " Incorrect size\n";
4724 if (dl.dylib.name < dl.cmdsize) {
4725 const char *P = (const char *)(Ptr) + dl.dylib.name;
4726 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
4728 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
4730 outs() << " time stamp " << dl.dylib.timestamp << " ";
4731 time_t t = dl.dylib.timestamp;
4732 outs() << ctime(&t);
4733 outs() << " current version ";
4734 if (dl.dylib.current_version == 0xffffffff)
4737 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
4738 << ((dl.dylib.current_version >> 8) & 0xff) << "."
4739 << (dl.dylib.current_version & 0xff) << "\n";
4740 outs() << "compatibility version ";
4741 if (dl.dylib.compatibility_version == 0xffffffff)
4744 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
4745 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
4746 << (dl.dylib.compatibility_version & 0xff) << "\n";
4749 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
4750 uint32_t object_size) {
4751 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
4752 outs() << " cmd LC_FUNCTION_STARTS\n";
4753 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
4754 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
4755 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
4756 outs() << " cmd LC_FUNCTION_STARTS\n";
4757 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
4758 outs() << " cmd LC_DATA_IN_CODE\n";
4759 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
4760 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
4761 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
4762 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
4764 outs() << " cmd " << ld.cmd << " (?)\n";
4765 outs() << " cmdsize " << ld.cmdsize;
4766 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
4767 outs() << " Incorrect size\n";
4770 outs() << " dataoff " << ld.dataoff;
4771 if (ld.dataoff > object_size)
4772 outs() << " (past end of file)\n";
4775 outs() << " datasize " << ld.datasize;
4776 uint64_t big_size = ld.dataoff;
4777 big_size += ld.datasize;
4778 if (big_size > object_size)
4779 outs() << " (past end of file)\n";
4784 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
4785 uint32_t filetype, uint32_t cputype,
4789 StringRef Buf = Obj->getData();
4790 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
4791 for (unsigned i = 0;; ++i) {
4792 outs() << "Load command " << i << "\n";
4793 if (Command.C.cmd == MachO::LC_SEGMENT) {
4794 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
4795 const char *sg_segname = SLC.segname;
4796 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
4797 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
4798 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
4800 for (unsigned j = 0; j < SLC.nsects; j++) {
4801 MachO::section S = Obj->getSection(Command, j);
4802 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
4803 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
4804 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
4806 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
4807 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
4808 const char *sg_segname = SLC_64.segname;
4809 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
4810 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
4811 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
4812 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
4813 for (unsigned j = 0; j < SLC_64.nsects; j++) {
4814 MachO::section_64 S_64 = Obj->getSection64(Command, j);
4815 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
4816 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
4817 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
4818 sg_segname, filetype, Buf.size(), verbose);
4820 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
4821 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
4822 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
4823 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
4824 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
4825 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
4826 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
4828 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
4829 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
4830 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
4831 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
4832 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
4833 Command.C.cmd == MachO::LC_ID_DYLINKER ||
4834 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
4835 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
4836 PrintDyldLoadCommand(Dyld, Command.Ptr);
4837 } else if (Command.C.cmd == MachO::LC_UUID) {
4838 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
4839 PrintUuidLoadCommand(Uuid);
4840 } else if (Command.C.cmd == MachO::LC_RPATH) {
4841 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
4842 PrintRpathLoadCommand(Rpath, Command.Ptr);
4843 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
4844 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
4845 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
4846 PrintVersionMinLoadCommand(Vd);
4847 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
4848 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
4849 PrintSourceVersionCommand(Sd);
4850 } else if (Command.C.cmd == MachO::LC_MAIN) {
4851 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
4852 PrintEntryPointCommand(Ep);
4853 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
4854 MachO::encryption_info_command Ei =
4855 Obj->getEncryptionInfoCommand(Command);
4856 PrintEncryptionInfoCommand(Ei, Buf.size());
4857 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
4858 MachO::encryption_info_command_64 Ei =
4859 Obj->getEncryptionInfoCommand64(Command);
4860 PrintEncryptionInfoCommand64(Ei, Buf.size());
4861 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
4862 MachO::linker_option_command Lo =
4863 Obj->getLinkerOptionLoadCommand(Command);
4864 PrintLinkerOptionCommand(Lo, Command.Ptr);
4865 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
4866 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
4867 PrintSubFrameworkCommand(Sf, Command.Ptr);
4868 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
4869 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
4870 PrintSubUmbrellaCommand(Sf, Command.Ptr);
4871 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
4872 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
4873 PrintSubLibraryCommand(Sl, Command.Ptr);
4874 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
4875 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
4876 PrintSubClientCommand(Sc, Command.Ptr);
4877 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
4878 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
4879 PrintRoutinesCommand(Rc);
4880 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
4881 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
4882 PrintRoutinesCommand64(Rc);
4883 } else if (Command.C.cmd == MachO::LC_THREAD ||
4884 Command.C.cmd == MachO::LC_UNIXTHREAD) {
4885 MachO::thread_command Tc = Obj->getThreadCommand(Command);
4886 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
4887 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
4888 Command.C.cmd == MachO::LC_ID_DYLIB ||
4889 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
4890 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
4891 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
4892 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
4893 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
4894 PrintDylibCommand(Dl, Command.Ptr);
4895 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
4896 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
4897 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
4898 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
4899 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
4900 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
4901 MachO::linkedit_data_command Ld =
4902 Obj->getLinkeditDataLoadCommand(Command);
4903 PrintLinkEditDataCommand(Ld, Buf.size());
4905 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
4907 outs() << " cmdsize " << Command.C.cmdsize << "\n";
4908 // TODO: get and print the raw bytes of the load command.
4910 // TODO: print all the other kinds of load commands.
4914 Command = Obj->getNextLoadCommandInfo(Command);
4918 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
4919 uint32_t &filetype, uint32_t &cputype,
4921 if (Obj->is64Bit()) {
4922 MachO::mach_header_64 H_64;
4923 H_64 = Obj->getHeader64();
4924 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
4925 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
4927 filetype = H_64.filetype;
4928 cputype = H_64.cputype;
4930 MachO::mach_header H;
4931 H = Obj->getHeader();
4932 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
4933 H.sizeofcmds, H.flags, verbose);
4935 filetype = H.filetype;
4936 cputype = H.cputype;
4940 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
4941 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
4943 uint32_t filetype = 0;
4944 uint32_t cputype = 0;
4945 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
4946 PrintLoadCommands(file, ncmds, filetype, cputype, true);
4949 //===----------------------------------------------------------------------===//
4950 // export trie dumping
4951 //===----------------------------------------------------------------------===//
4953 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
4954 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
4955 uint64_t Flags = Entry.flags();
4956 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
4957 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
4958 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
4959 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
4960 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
4961 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
4962 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
4964 outs() << "[re-export] ";
4966 outs() << format("0x%08llX ",
4967 Entry.address()); // FIXME:add in base address
4968 outs() << Entry.name();
4969 if (WeakDef || ThreadLocal || Resolver || Abs) {
4970 bool NeedsComma = false;
4973 outs() << "weak_def";
4979 outs() << "per-thread";
4985 outs() << "absolute";
4991 outs() << format("resolver=0x%08llX", Entry.other());
4997 StringRef DylibName = "unknown";
4998 int Ordinal = Entry.other() - 1;
4999 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
5000 if (Entry.otherName().empty())
5001 outs() << " (from " << DylibName << ")";
5003 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
5009 //===----------------------------------------------------------------------===//
5010 // rebase table dumping
5011 //===----------------------------------------------------------------------===//
5016 SegInfo(const object::MachOObjectFile *Obj);
5018 StringRef segmentName(uint32_t SegIndex);
5019 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
5020 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
5023 struct SectionInfo {
5026 StringRef SectionName;
5027 StringRef SegmentName;
5028 uint64_t OffsetInSegment;
5029 uint64_t SegmentStartAddress;
5030 uint32_t SegmentIndex;
5032 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
5033 SmallVector<SectionInfo, 32> Sections;
5037 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
5038 // Build table of sections so segIndex/offset pairs can be translated.
5039 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
5040 StringRef CurSegName;
5041 uint64_t CurSegAddress;
5042 for (const SectionRef &Section : Obj->sections()) {
5044 if (error(Section.getName(Info.SectionName)))
5046 Info.Address = Section.getAddress();
5047 Info.Size = Section.getSize();
5049 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
5050 if (!Info.SegmentName.equals(CurSegName)) {
5052 CurSegName = Info.SegmentName;
5053 CurSegAddress = Info.Address;
5055 Info.SegmentIndex = CurSegIndex - 1;
5056 Info.OffsetInSegment = Info.Address - CurSegAddress;
5057 Info.SegmentStartAddress = CurSegAddress;
5058 Sections.push_back(Info);
5062 StringRef SegInfo::segmentName(uint32_t SegIndex) {
5063 for (const SectionInfo &SI : Sections) {
5064 if (SI.SegmentIndex == SegIndex)
5065 return SI.SegmentName;
5067 llvm_unreachable("invalid segIndex");
5070 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
5071 uint64_t OffsetInSeg) {
5072 for (const SectionInfo &SI : Sections) {
5073 if (SI.SegmentIndex != SegIndex)
5075 if (SI.OffsetInSegment > OffsetInSeg)
5077 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
5081 llvm_unreachable("segIndex and offset not in any section");
5084 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
5085 return findSection(SegIndex, OffsetInSeg).SectionName;
5088 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
5089 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
5090 return SI.SegmentStartAddress + OffsetInSeg;
5093 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
5094 // Build table of sections so names can used in final output.
5095 SegInfo sectionTable(Obj);
5097 outs() << "segment section address type\n";
5098 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
5099 uint32_t SegIndex = Entry.segmentIndex();
5100 uint64_t OffsetInSeg = Entry.segmentOffset();
5101 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5102 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5103 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5105 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
5106 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
5107 SegmentName.str().c_str(), SectionName.str().c_str(),
5108 Address, Entry.typeName().str().c_str());
5112 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
5113 StringRef DylibName;
5115 case MachO::BIND_SPECIAL_DYLIB_SELF:
5116 return "this-image";
5117 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
5118 return "main-executable";
5119 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
5120 return "flat-namespace";
5123 std::error_code EC =
5124 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
5126 return "<<bad library ordinal>>";
5130 return "<<unknown special ordinal>>";
5133 //===----------------------------------------------------------------------===//
5134 // bind table dumping
5135 //===----------------------------------------------------------------------===//
5137 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
5138 // Build table of sections so names can used in final output.
5139 SegInfo sectionTable(Obj);
5141 outs() << "segment section address type "
5142 "addend dylib symbol\n";
5143 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
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 __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
5153 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
5154 Attr = " (weak_import)";
5155 outs() << left_justify(SegmentName, 8) << " "
5156 << left_justify(SectionName, 18) << " "
5157 << format_hex(Address, 10, true) << " "
5158 << left_justify(Entry.typeName(), 8) << " "
5159 << format_decimal(Entry.addend(), 8) << " "
5160 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5161 << Entry.symbolName() << Attr << "\n";
5165 //===----------------------------------------------------------------------===//
5166 // lazy bind table dumping
5167 //===----------------------------------------------------------------------===//
5169 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
5170 // Build table of sections so names can used in final output.
5171 SegInfo sectionTable(Obj);
5173 outs() << "segment section address "
5175 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
5176 uint32_t SegIndex = Entry.segmentIndex();
5177 uint64_t OffsetInSeg = Entry.segmentOffset();
5178 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5179 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5180 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5182 // Table lines look like:
5183 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
5184 outs() << left_justify(SegmentName, 8) << " "
5185 << left_justify(SectionName, 18) << " "
5186 << format_hex(Address, 10, true) << " "
5187 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5188 << Entry.symbolName() << "\n";
5192 //===----------------------------------------------------------------------===//
5193 // weak bind table dumping
5194 //===----------------------------------------------------------------------===//
5196 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
5197 // Build table of sections so names can used in final output.
5198 SegInfo sectionTable(Obj);
5200 outs() << "segment section address "
5201 "type addend symbol\n";
5202 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
5203 // Strong symbols don't have a location to update.
5204 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
5205 outs() << " strong "
5206 << Entry.symbolName() << "\n";
5209 uint32_t SegIndex = Entry.segmentIndex();
5210 uint64_t OffsetInSeg = Entry.segmentOffset();
5211 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5212 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5213 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5215 // Table lines look like:
5216 // __DATA __data 0x00001000 pointer 0 _foo
5217 outs() << left_justify(SegmentName, 8) << " "
5218 << left_justify(SectionName, 18) << " "
5219 << format_hex(Address, 10, true) << " "
5220 << left_justify(Entry.typeName(), 8) << " "
5221 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
5226 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
5227 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
5228 // information for that address. If the address is found its binding symbol
5229 // name is returned. If not nullptr is returned.
5230 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
5231 struct DisassembleInfo *info) {
5232 if (info->bindtable == nullptr) {
5233 info->bindtable = new (BindTable);
5234 SegInfo sectionTable(info->O);
5235 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
5236 uint32_t SegIndex = Entry.segmentIndex();
5237 uint64_t OffsetInSeg = Entry.segmentOffset();
5238 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5239 const char *SymbolName = nullptr;
5240 StringRef name = Entry.symbolName();
5242 SymbolName = name.data();
5243 info->bindtable->push_back(std::make_pair(Address, SymbolName));
5246 for (bind_table_iterator BI = info->bindtable->begin(),
5247 BE = info->bindtable->end();
5249 uint64_t Address = BI->first;
5250 if (ReferenceValue == Address) {
5251 const char *SymbolName = BI->second;