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/DebugInfo/DWARF/DWARFContext.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCDisassembler.h"
25 #include "llvm/MC/MCInst.h"
26 #include "llvm/MC/MCInstPrinter.h"
27 #include "llvm/MC/MCInstrDesc.h"
28 #include "llvm/MC/MCInstrInfo.h"
29 #include "llvm/MC/MCRegisterInfo.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/Object/MachO.h"
32 #include "llvm/Object/MachOUniversal.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Endian.h"
37 #include "llvm/Support/Format.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/GraphWriter.h"
40 #include "llvm/Support/LEB128.h"
41 #include "llvm/Support/MachO.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/raw_ostream.h"
48 #include <system_error>
55 using namespace object;
59 cl::desc("Print line information from debug info if available"));
61 static cl::opt<std::string> DSYMFile("dsym",
62 cl::desc("Use .dSYM file for debug info"));
64 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
65 cl::desc("Print full leading address"));
67 static cl::opt<bool> NoLeadingAddr("no-leading-addr",
68 cl::desc("Print no leading address"));
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 ArchiveMemberOffsets("archive-member-offsets",
81 cl::desc("Print the offset to each archive member for "
82 "Mach-O archives (requires -macho and "
83 "-archive-headers)"));
86 llvm::IndirectSymbols("indirect-symbols",
87 cl::desc("Print indirect symbol table for Mach-O "
88 "objects (requires -macho)"));
91 llvm::DataInCode("data-in-code",
92 cl::desc("Print the data in code table for Mach-O objects "
93 "(requires -macho)"));
96 llvm::LinkOptHints("link-opt-hints",
97 cl::desc("Print the linker optimization hints for "
98 "Mach-O objects (requires -macho)"));
101 llvm::InfoPlist("info-plist",
102 cl::desc("Print the info plist section as strings for "
103 "Mach-O objects (requires -macho)"));
106 llvm::DylibsUsed("dylibs-used",
107 cl::desc("Print the shared libraries used for linked "
108 "Mach-O files (requires -macho)"));
111 llvm::DylibId("dylib-id",
112 cl::desc("Print the shared library's id for the dylib Mach-O "
113 "file (requires -macho)"));
116 llvm::NonVerbose("non-verbose",
117 cl::desc("Print the info for Mach-O objects in "
118 "non-verbose or numeric form (requires -macho)"));
121 llvm::ObjcMetaData("objc-meta-data",
122 cl::desc("Print the Objective-C runtime meta data for "
123 "Mach-O files (requires -macho)"));
125 cl::opt<std::string> llvm::DisSymName(
127 cl::desc("disassemble just this symbol's instructions (requires -macho"));
129 static cl::opt<bool> NoSymbolicOperands(
130 "no-symbolic-operands",
131 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
133 static cl::list<std::string>
134 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
137 bool ArchAll = false;
139 static std::string ThumbTripleName;
141 static const Target *GetTarget(const MachOObjectFile *MachOObj,
142 const char **McpuDefault,
143 const Target **ThumbTarget) {
144 // Figure out the target triple.
145 if (TripleName.empty()) {
146 llvm::Triple TT("unknown-unknown-unknown");
147 llvm::Triple ThumbTriple = Triple();
148 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
149 TripleName = TT.str();
150 ThumbTripleName = ThumbTriple.str();
153 // Get the target specific parser.
155 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
156 if (TheTarget && ThumbTripleName.empty())
159 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
163 errs() << "llvm-objdump: error: unable to get target for '";
165 errs() << TripleName;
167 errs() << ThumbTripleName;
168 errs() << "', see --version and --triple.\n";
172 struct SymbolSorter {
173 bool operator()(const SymbolRef &A, const SymbolRef &B) {
174 uint64_t AAddr = (A.getType() != SymbolRef::ST_Function) ? 0 : A.getValue();
175 uint64_t BAddr = (B.getType() != SymbolRef::ST_Function) ? 0 : B.getValue();
176 return AAddr < BAddr;
180 // Types for the storted data in code table that is built before disassembly
181 // and the predicate function to sort them.
182 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
183 typedef std::vector<DiceTableEntry> DiceTable;
184 typedef DiceTable::iterator dice_table_iterator;
186 // This is used to search for a data in code table entry for the PC being
187 // disassembled. The j parameter has the PC in j.first. A single data in code
188 // table entry can cover many bytes for each of its Kind's. So if the offset,
189 // aka the i.first value, of the data in code table entry plus its Length
190 // covers the PC being searched for this will return true. If not it will
192 static bool compareDiceTableEntries(const DiceTableEntry &i,
193 const DiceTableEntry &j) {
195 i.second.getLength(Length);
197 return j.first >= i.first && j.first < i.first + Length;
200 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
201 unsigned short Kind) {
202 uint32_t Value, Size = 1;
206 case MachO::DICE_KIND_DATA:
209 dumpBytes(makeArrayRef(bytes, 4), outs());
210 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
211 outs() << "\t.long " << Value;
213 } else if (Length >= 2) {
215 dumpBytes(makeArrayRef(bytes, 2), outs());
216 Value = bytes[1] << 8 | bytes[0];
217 outs() << "\t.short " << Value;
221 dumpBytes(makeArrayRef(bytes, 2), outs());
223 outs() << "\t.byte " << Value;
226 if (Kind == MachO::DICE_KIND_DATA)
227 outs() << "\t@ KIND_DATA\n";
229 outs() << "\t@ data in code kind = " << Kind << "\n";
231 case MachO::DICE_KIND_JUMP_TABLE8:
233 dumpBytes(makeArrayRef(bytes, 1), outs());
235 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
238 case MachO::DICE_KIND_JUMP_TABLE16:
240 dumpBytes(makeArrayRef(bytes, 2), outs());
241 Value = bytes[1] << 8 | bytes[0];
242 outs() << "\t.short " << format("%5u", Value & 0xffff)
243 << "\t@ KIND_JUMP_TABLE16\n";
246 case MachO::DICE_KIND_JUMP_TABLE32:
247 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
249 dumpBytes(makeArrayRef(bytes, 4), outs());
250 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
251 outs() << "\t.long " << Value;
252 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
253 outs() << "\t@ KIND_JUMP_TABLE32\n";
255 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
262 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
263 std::vector<SectionRef> &Sections,
264 std::vector<SymbolRef> &Symbols,
265 SmallVectorImpl<uint64_t> &FoundFns,
266 uint64_t &BaseSegmentAddress) {
267 for (const SymbolRef &Symbol : MachOObj->symbols()) {
268 ErrorOr<StringRef> SymName = Symbol.getName();
269 if (std::error_code EC = SymName.getError())
270 report_fatal_error(EC.message());
271 if (!SymName->startswith("ltmp"))
272 Symbols.push_back(Symbol);
275 for (const SectionRef &Section : MachOObj->sections()) {
277 Section.getName(SectName);
278 Sections.push_back(Section);
281 bool BaseSegmentAddressSet = false;
282 for (const auto &Command : MachOObj->load_commands()) {
283 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
284 // We found a function starts segment, parse the addresses for later
286 MachO::linkedit_data_command LLC =
287 MachOObj->getLinkeditDataLoadCommand(Command);
289 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
290 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
291 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
292 StringRef SegName = SLC.segname;
293 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
294 BaseSegmentAddressSet = true;
295 BaseSegmentAddress = SLC.vmaddr;
301 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
302 uint32_t n, uint32_t count,
303 uint32_t stride, uint64_t addr) {
304 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
305 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
306 if (n > nindirectsyms)
307 outs() << " (entries start past the end of the indirect symbol "
308 "table) (reserved1 field greater than the table size)";
309 else if (n + count > nindirectsyms)
310 outs() << " (entries extends past the end of the indirect symbol "
313 uint32_t cputype = O->getHeader().cputype;
314 if (cputype & MachO::CPU_ARCH_ABI64)
315 outs() << "address index";
317 outs() << "address index";
322 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
323 if (cputype & MachO::CPU_ARCH_ABI64)
324 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
326 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
327 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
328 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
329 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
333 if (indirect_symbol ==
334 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
335 outs() << "LOCAL ABSOLUTE\n";
338 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
339 outs() << "ABSOLUTE\n";
342 outs() << format("%5u ", indirect_symbol);
344 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
345 if (indirect_symbol < Symtab.nsyms) {
346 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
347 SymbolRef Symbol = *Sym;
348 ErrorOr<StringRef> SymName = Symbol.getName();
349 if (std::error_code EC = SymName.getError())
350 report_fatal_error(EC.message());
360 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
361 for (const auto &Load : O->load_commands()) {
362 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
363 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
364 for (unsigned J = 0; J < Seg.nsects; ++J) {
365 MachO::section_64 Sec = O->getSection64(Load, J);
366 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
367 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
368 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
369 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
370 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
371 section_type == MachO::S_SYMBOL_STUBS) {
373 if (section_type == MachO::S_SYMBOL_STUBS)
374 stride = Sec.reserved2;
378 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
379 << Sec.sectname << ") "
380 << "(size of stubs in reserved2 field is zero)\n";
383 uint32_t count = Sec.size / stride;
384 outs() << "Indirect symbols for (" << Sec.segname << ","
385 << Sec.sectname << ") " << count << " entries";
386 uint32_t n = Sec.reserved1;
387 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
390 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
391 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
392 for (unsigned J = 0; J < Seg.nsects; ++J) {
393 MachO::section Sec = O->getSection(Load, J);
394 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
395 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
396 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
397 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
398 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
399 section_type == MachO::S_SYMBOL_STUBS) {
401 if (section_type == MachO::S_SYMBOL_STUBS)
402 stride = Sec.reserved2;
406 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
407 << Sec.sectname << ") "
408 << "(size of stubs in reserved2 field is zero)\n";
411 uint32_t count = Sec.size / stride;
412 outs() << "Indirect symbols for (" << Sec.segname << ","
413 << Sec.sectname << ") " << count << " entries";
414 uint32_t n = Sec.reserved1;
415 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
422 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
423 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
424 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
425 outs() << "Data in code table (" << nentries << " entries)\n";
426 outs() << "offset length kind\n";
427 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
430 DI->getOffset(Offset);
431 outs() << format("0x%08" PRIx32, Offset) << " ";
433 DI->getLength(Length);
434 outs() << format("%6u", Length) << " ";
439 case MachO::DICE_KIND_DATA:
442 case MachO::DICE_KIND_JUMP_TABLE8:
443 outs() << "JUMP_TABLE8";
445 case MachO::DICE_KIND_JUMP_TABLE16:
446 outs() << "JUMP_TABLE16";
448 case MachO::DICE_KIND_JUMP_TABLE32:
449 outs() << "JUMP_TABLE32";
451 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
452 outs() << "ABS_JUMP_TABLE32";
455 outs() << format("0x%04" PRIx32, Kind);
459 outs() << format("0x%04" PRIx32, Kind);
464 static void PrintLinkOptHints(MachOObjectFile *O) {
465 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
466 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
467 uint32_t nloh = LohLC.datasize;
468 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
469 for (uint32_t i = 0; i < nloh;) {
471 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
473 outs() << " identifier " << identifier << " ";
476 switch (identifier) {
478 outs() << "AdrpAdrp\n";
481 outs() << "AdrpLdr\n";
484 outs() << "AdrpAddLdr\n";
487 outs() << "AdrpLdrGotLdr\n";
490 outs() << "AdrpAddStr\n";
493 outs() << "AdrpLdrGotStr\n";
496 outs() << "AdrpAdd\n";
499 outs() << "AdrpLdrGot\n";
502 outs() << "Unknown identifier value\n";
505 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
507 outs() << " narguments " << narguments << "\n";
511 for (uint32_t j = 0; j < narguments; j++) {
512 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
514 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
521 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
523 for (const auto &Load : O->load_commands()) {
524 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
525 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
526 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
527 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
528 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
529 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
530 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
531 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
532 if (dl.dylib.name < dl.cmdsize) {
533 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
538 outs() << " (compatibility version "
539 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
540 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
541 << (dl.dylib.compatibility_version & 0xff) << ",";
542 outs() << " current version "
543 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
544 << ((dl.dylib.current_version >> 8) & 0xff) << "."
545 << (dl.dylib.current_version & 0xff) << ")\n";
548 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
549 if (Load.C.cmd == MachO::LC_ID_DYLIB)
550 outs() << "LC_ID_DYLIB ";
551 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
552 outs() << "LC_LOAD_DYLIB ";
553 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
554 outs() << "LC_LOAD_WEAK_DYLIB ";
555 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
556 outs() << "LC_LAZY_LOAD_DYLIB ";
557 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
558 outs() << "LC_REEXPORT_DYLIB ";
559 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
560 outs() << "LC_LOAD_UPWARD_DYLIB ";
563 outs() << "command " << Index++ << "\n";
569 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
571 static void CreateSymbolAddressMap(MachOObjectFile *O,
572 SymbolAddressMap *AddrMap) {
573 // Create a map of symbol addresses to symbol names.
574 for (const SymbolRef &Symbol : O->symbols()) {
575 SymbolRef::Type ST = Symbol.getType();
576 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
577 ST == SymbolRef::ST_Other) {
578 uint64_t Address = Symbol.getValue();
579 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
580 if (std::error_code EC = SymNameOrErr.getError())
581 report_fatal_error(EC.message());
582 StringRef SymName = *SymNameOrErr;
583 if (!SymName.startswith(".objc"))
584 (*AddrMap)[Address] = SymName;
589 // GuessSymbolName is passed the address of what might be a symbol and a
590 // pointer to the SymbolAddressMap. It returns the name of a symbol
591 // with that address or nullptr if no symbol is found with that address.
592 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
593 const char *SymbolName = nullptr;
594 // A DenseMap can't lookup up some values.
595 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
596 StringRef name = AddrMap->lookup(value);
598 SymbolName = name.data();
603 static void DumpCstringChar(const char c) {
607 outs().write_escaped(p);
610 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
611 uint32_t sect_size, uint64_t sect_addr,
612 bool print_addresses) {
613 for (uint32_t i = 0; i < sect_size; i++) {
614 if (print_addresses) {
616 outs() << format("%016" PRIx64, sect_addr + i) << " ";
618 outs() << format("%08" PRIx64, sect_addr + i) << " ";
620 for (; i < sect_size && sect[i] != '\0'; i++)
621 DumpCstringChar(sect[i]);
622 if (i < sect_size && sect[i] == '\0')
627 static void DumpLiteral4(uint32_t l, float f) {
628 outs() << format("0x%08" PRIx32, l);
629 if ((l & 0x7f800000) != 0x7f800000)
630 outs() << format(" (%.16e)\n", f);
633 outs() << " (+Infinity)\n";
634 else if (l == 0xff800000)
635 outs() << " (-Infinity)\n";
636 else if ((l & 0x00400000) == 0x00400000)
637 outs() << " (non-signaling Not-a-Number)\n";
639 outs() << " (signaling Not-a-Number)\n";
643 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
644 uint32_t sect_size, uint64_t sect_addr,
645 bool print_addresses) {
646 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
647 if (print_addresses) {
649 outs() << format("%016" PRIx64, sect_addr + i) << " ";
651 outs() << format("%08" PRIx64, sect_addr + i) << " ";
654 memcpy(&f, sect + i, sizeof(float));
655 if (O->isLittleEndian() != sys::IsLittleEndianHost)
656 sys::swapByteOrder(f);
658 memcpy(&l, sect + i, sizeof(uint32_t));
659 if (O->isLittleEndian() != sys::IsLittleEndianHost)
660 sys::swapByteOrder(l);
665 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
667 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
669 if (O->isLittleEndian()) {
676 // Hi is the high word, so this is equivalent to if(isfinite(d))
677 if ((Hi & 0x7ff00000) != 0x7ff00000)
678 outs() << format(" (%.16e)\n", d);
680 if (Hi == 0x7ff00000 && Lo == 0)
681 outs() << " (+Infinity)\n";
682 else if (Hi == 0xfff00000 && Lo == 0)
683 outs() << " (-Infinity)\n";
684 else if ((Hi & 0x00080000) == 0x00080000)
685 outs() << " (non-signaling Not-a-Number)\n";
687 outs() << " (signaling Not-a-Number)\n";
691 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
692 uint32_t sect_size, uint64_t sect_addr,
693 bool print_addresses) {
694 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
695 if (print_addresses) {
697 outs() << format("%016" PRIx64, sect_addr + i) << " ";
699 outs() << format("%08" PRIx64, sect_addr + i) << " ";
702 memcpy(&d, sect + i, sizeof(double));
703 if (O->isLittleEndian() != sys::IsLittleEndianHost)
704 sys::swapByteOrder(d);
706 memcpy(&l0, sect + i, sizeof(uint32_t));
707 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
708 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
709 sys::swapByteOrder(l0);
710 sys::swapByteOrder(l1);
712 DumpLiteral8(O, l0, l1, d);
716 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
717 outs() << format("0x%08" PRIx32, l0) << " ";
718 outs() << format("0x%08" PRIx32, l1) << " ";
719 outs() << format("0x%08" PRIx32, l2) << " ";
720 outs() << format("0x%08" PRIx32, l3) << "\n";
723 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
724 uint32_t sect_size, uint64_t sect_addr,
725 bool print_addresses) {
726 for (uint32_t i = 0; i < sect_size; i += 16) {
727 if (print_addresses) {
729 outs() << format("%016" PRIx64, sect_addr + i) << " ";
731 outs() << format("%08" PRIx64, sect_addr + i) << " ";
733 uint32_t l0, l1, l2, l3;
734 memcpy(&l0, sect + i, sizeof(uint32_t));
735 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
736 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
737 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
738 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
739 sys::swapByteOrder(l0);
740 sys::swapByteOrder(l1);
741 sys::swapByteOrder(l2);
742 sys::swapByteOrder(l3);
744 DumpLiteral16(l0, l1, l2, l3);
748 static void DumpLiteralPointerSection(MachOObjectFile *O,
749 const SectionRef &Section,
750 const char *sect, uint32_t sect_size,
752 bool print_addresses) {
753 // Collect the literal sections in this Mach-O file.
754 std::vector<SectionRef> LiteralSections;
755 for (const SectionRef &Section : O->sections()) {
756 DataRefImpl Ref = Section.getRawDataRefImpl();
757 uint32_t section_type;
759 const MachO::section_64 Sec = O->getSection64(Ref);
760 section_type = Sec.flags & MachO::SECTION_TYPE;
762 const MachO::section Sec = O->getSection(Ref);
763 section_type = Sec.flags & MachO::SECTION_TYPE;
765 if (section_type == MachO::S_CSTRING_LITERALS ||
766 section_type == MachO::S_4BYTE_LITERALS ||
767 section_type == MachO::S_8BYTE_LITERALS ||
768 section_type == MachO::S_16BYTE_LITERALS)
769 LiteralSections.push_back(Section);
772 // Set the size of the literal pointer.
773 uint32_t lp_size = O->is64Bit() ? 8 : 4;
775 // Collect the external relocation symbols for the literal pointers.
776 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
777 for (const RelocationRef &Reloc : Section.relocations()) {
779 MachO::any_relocation_info RE;
780 bool isExtern = false;
781 Rel = Reloc.getRawDataRefImpl();
782 RE = O->getRelocation(Rel);
783 isExtern = O->getPlainRelocationExternal(RE);
785 uint64_t RelocOffset = Reloc.getOffset();
786 symbol_iterator RelocSym = Reloc.getSymbol();
787 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
790 array_pod_sort(Relocs.begin(), Relocs.end());
792 // Dump each literal pointer.
793 for (uint32_t i = 0; i < sect_size; i += lp_size) {
794 if (print_addresses) {
796 outs() << format("%016" PRIx64, sect_addr + i) << " ";
798 outs() << format("%08" PRIx64, sect_addr + i) << " ";
802 memcpy(&lp, sect + i, sizeof(uint64_t));
803 if (O->isLittleEndian() != sys::IsLittleEndianHost)
804 sys::swapByteOrder(lp);
807 memcpy(&li, sect + i, sizeof(uint32_t));
808 if (O->isLittleEndian() != sys::IsLittleEndianHost)
809 sys::swapByteOrder(li);
813 // First look for an external relocation entry for this literal pointer.
814 auto Reloc = std::find_if(
815 Relocs.begin(), Relocs.end(),
816 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
817 if (Reloc != Relocs.end()) {
818 symbol_iterator RelocSym = Reloc->second;
819 ErrorOr<StringRef> SymName = RelocSym->getName();
820 if (std::error_code EC = SymName.getError())
821 report_fatal_error(EC.message());
822 outs() << "external relocation entry for symbol:" << *SymName << "\n";
826 // For local references see what the section the literal pointer points to.
827 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
828 [&](const SectionRef &R) {
829 return lp >= R.getAddress() &&
830 lp < R.getAddress() + R.getSize();
832 if (Sect == LiteralSections.end()) {
833 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
837 uint64_t SectAddress = Sect->getAddress();
838 uint64_t SectSize = Sect->getSize();
841 Sect->getName(SectName);
842 DataRefImpl Ref = Sect->getRawDataRefImpl();
843 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
844 outs() << SegmentName << ":" << SectName << ":";
846 uint32_t section_type;
848 const MachO::section_64 Sec = O->getSection64(Ref);
849 section_type = Sec.flags & MachO::SECTION_TYPE;
851 const MachO::section Sec = O->getSection(Ref);
852 section_type = Sec.flags & MachO::SECTION_TYPE;
856 Sect->getContents(BytesStr);
857 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
859 switch (section_type) {
860 case MachO::S_CSTRING_LITERALS:
861 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
863 DumpCstringChar(Contents[i]);
867 case MachO::S_4BYTE_LITERALS:
869 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
871 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
872 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
873 sys::swapByteOrder(f);
874 sys::swapByteOrder(l);
878 case MachO::S_8BYTE_LITERALS: {
880 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
882 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
883 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
885 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
886 sys::swapByteOrder(f);
887 sys::swapByteOrder(l0);
888 sys::swapByteOrder(l1);
890 DumpLiteral8(O, l0, l1, d);
893 case MachO::S_16BYTE_LITERALS: {
894 uint32_t l0, l1, l2, l3;
895 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
896 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
898 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
900 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
902 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
903 sys::swapByteOrder(l0);
904 sys::swapByteOrder(l1);
905 sys::swapByteOrder(l2);
906 sys::swapByteOrder(l3);
908 DumpLiteral16(l0, l1, l2, l3);
915 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
916 uint32_t sect_size, uint64_t sect_addr,
917 SymbolAddressMap *AddrMap,
921 stride = sizeof(uint64_t);
923 stride = sizeof(uint32_t);
924 for (uint32_t i = 0; i < sect_size; i += stride) {
925 const char *SymbolName = nullptr;
927 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
928 uint64_t pointer_value;
929 memcpy(&pointer_value, sect + i, stride);
930 if (O->isLittleEndian() != sys::IsLittleEndianHost)
931 sys::swapByteOrder(pointer_value);
932 outs() << format("0x%016" PRIx64, pointer_value);
934 SymbolName = GuessSymbolName(pointer_value, AddrMap);
936 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
937 uint32_t pointer_value;
938 memcpy(&pointer_value, sect + i, stride);
939 if (O->isLittleEndian() != sys::IsLittleEndianHost)
940 sys::swapByteOrder(pointer_value);
941 outs() << format("0x%08" PRIx32, pointer_value);
943 SymbolName = GuessSymbolName(pointer_value, AddrMap);
946 outs() << " " << SymbolName;
951 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
952 uint32_t size, uint64_t addr) {
953 uint32_t cputype = O->getHeader().cputype;
954 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
956 for (uint32_t i = 0; i < size; i += j, addr += j) {
958 outs() << format("%016" PRIx64, addr) << "\t";
960 outs() << format("%08" PRIx64, addr) << "\t";
961 for (j = 0; j < 16 && i + j < size; j++) {
962 uint8_t byte_word = *(sect + i + j);
963 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
969 for (uint32_t i = 0; i < size; i += j, addr += j) {
971 outs() << format("%016" PRIx64, addr) << "\t";
973 outs() << format("%08" PRIx64, sect) << "\t";
974 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
975 j += sizeof(int32_t)) {
976 if (i + j + sizeof(int32_t) < size) {
978 memcpy(&long_word, sect + i + j, sizeof(int32_t));
979 if (O->isLittleEndian() != sys::IsLittleEndianHost)
980 sys::swapByteOrder(long_word);
981 outs() << format("%08" PRIx32, long_word) << " ";
983 for (uint32_t k = 0; i + j + k < size; k++) {
984 uint8_t byte_word = *(sect + i + j);
985 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
994 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
995 StringRef DisSegName, StringRef DisSectName);
996 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
997 uint32_t size, uint32_t addr);
999 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1001 SymbolAddressMap AddrMap;
1003 CreateSymbolAddressMap(O, &AddrMap);
1005 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1006 StringRef DumpSection = FilterSections[i];
1007 std::pair<StringRef, StringRef> DumpSegSectName;
1008 DumpSegSectName = DumpSection.split(',');
1009 StringRef DumpSegName, DumpSectName;
1010 if (DumpSegSectName.second.size()) {
1011 DumpSegName = DumpSegSectName.first;
1012 DumpSectName = DumpSegSectName.second;
1015 DumpSectName = DumpSegSectName.first;
1017 for (const SectionRef &Section : O->sections()) {
1019 Section.getName(SectName);
1020 DataRefImpl Ref = Section.getRawDataRefImpl();
1021 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1022 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1023 (SectName == DumpSectName)) {
1025 uint32_t section_flags;
1027 const MachO::section_64 Sec = O->getSection64(Ref);
1028 section_flags = Sec.flags;
1031 const MachO::section Sec = O->getSection(Ref);
1032 section_flags = Sec.flags;
1034 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1037 Section.getContents(BytesStr);
1038 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1039 uint32_t sect_size = BytesStr.size();
1040 uint64_t sect_addr = Section.getAddress();
1042 outs() << "Contents of (" << SegName << "," << SectName
1046 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1047 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1048 DisassembleMachO(Filename, O, SegName, SectName);
1051 if (SegName == "__TEXT" && SectName == "__info_plist") {
1055 if (SegName == "__OBJC" && SectName == "__protocol") {
1056 DumpProtocolSection(O, sect, sect_size, sect_addr);
1059 switch (section_type) {
1060 case MachO::S_REGULAR:
1061 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1063 case MachO::S_ZEROFILL:
1064 outs() << "zerofill section and has no contents in the file\n";
1066 case MachO::S_CSTRING_LITERALS:
1067 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1069 case MachO::S_4BYTE_LITERALS:
1070 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1072 case MachO::S_8BYTE_LITERALS:
1073 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1075 case MachO::S_16BYTE_LITERALS:
1076 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1078 case MachO::S_LITERAL_POINTERS:
1079 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1082 case MachO::S_MOD_INIT_FUNC_POINTERS:
1083 case MachO::S_MOD_TERM_FUNC_POINTERS:
1084 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1088 outs() << "Unknown section type ("
1089 << format("0x%08" PRIx32, section_type) << ")\n";
1090 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1094 if (section_type == MachO::S_ZEROFILL)
1095 outs() << "zerofill section and has no contents in the file\n";
1097 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1104 static void DumpInfoPlistSectionContents(StringRef Filename,
1105 MachOObjectFile *O) {
1106 for (const SectionRef &Section : O->sections()) {
1108 Section.getName(SectName);
1109 DataRefImpl Ref = Section.getRawDataRefImpl();
1110 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1111 if (SegName == "__TEXT" && SectName == "__info_plist") {
1112 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1114 Section.getContents(BytesStr);
1115 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1122 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1123 // and if it is and there is a list of architecture flags is specified then
1124 // check to make sure this Mach-O file is one of those architectures or all
1125 // architectures were specified. If not then an error is generated and this
1126 // routine returns false. Else it returns true.
1127 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1128 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1129 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1130 bool ArchFound = false;
1131 MachO::mach_header H;
1132 MachO::mach_header_64 H_64;
1134 if (MachO->is64Bit()) {
1135 H_64 = MachO->MachOObjectFile::getHeader64();
1136 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1138 H = MachO->MachOObjectFile::getHeader();
1139 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1142 for (i = 0; i < ArchFlags.size(); ++i) {
1143 if (ArchFlags[i] == T.getArchName())
1148 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1149 << "architecture: " + ArchFlags[i] + "\n";
1156 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1158 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1159 // archive member and or in a slice of a universal file. It prints the
1160 // the file name and header info and then processes it according to the
1161 // command line options.
1162 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1163 StringRef ArchiveMemberName = StringRef(),
1164 StringRef ArchitectureName = StringRef()) {
1165 // If we are doing some processing here on the Mach-O file print the header
1166 // info. And don't print it otherwise like in the case of printing the
1167 // UniversalHeaders or ArchiveHeaders.
1168 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
1169 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1170 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
1172 if (!ArchiveMemberName.empty())
1173 outs() << '(' << ArchiveMemberName << ')';
1174 if (!ArchitectureName.empty())
1175 outs() << " (architecture " << ArchitectureName << ")";
1180 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1181 if (IndirectSymbols)
1182 PrintIndirectSymbols(MachOOF, !NonVerbose);
1184 PrintDataInCodeTable(MachOOF, !NonVerbose);
1186 PrintLinkOptHints(MachOOF);
1188 PrintRelocations(MachOOF);
1190 PrintSectionHeaders(MachOOF);
1191 if (SectionContents)
1192 PrintSectionContents(MachOOF);
1193 if (FilterSections.size() != 0)
1194 DumpSectionContents(Filename, MachOOF, !NonVerbose);
1196 DumpInfoPlistSectionContents(Filename, MachOOF);
1198 PrintDylibs(MachOOF, false);
1200 PrintDylibs(MachOOF, true);
1202 PrintSymbolTable(MachOOF);
1204 printMachOUnwindInfo(MachOOF);
1206 printMachOFileHeader(MachOOF);
1208 printObjcMetaData(MachOOF, !NonVerbose);
1210 printExportsTrie(MachOOF);
1212 printRebaseTable(MachOOF);
1214 printBindTable(MachOOF);
1216 printLazyBindTable(MachOOF);
1218 printWeakBindTable(MachOOF);
1221 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1222 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1223 outs() << " cputype (" << cputype << ")\n";
1224 outs() << " cpusubtype (" << cpusubtype << ")\n";
1227 // printCPUType() helps print_fat_headers by printing the cputype and
1228 // pusubtype (symbolically for the one's it knows about).
1229 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1231 case MachO::CPU_TYPE_I386:
1232 switch (cpusubtype) {
1233 case MachO::CPU_SUBTYPE_I386_ALL:
1234 outs() << " cputype CPU_TYPE_I386\n";
1235 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1238 printUnknownCPUType(cputype, cpusubtype);
1242 case MachO::CPU_TYPE_X86_64:
1243 switch (cpusubtype) {
1244 case MachO::CPU_SUBTYPE_X86_64_ALL:
1245 outs() << " cputype CPU_TYPE_X86_64\n";
1246 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1248 case MachO::CPU_SUBTYPE_X86_64_H:
1249 outs() << " cputype CPU_TYPE_X86_64\n";
1250 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1253 printUnknownCPUType(cputype, cpusubtype);
1257 case MachO::CPU_TYPE_ARM:
1258 switch (cpusubtype) {
1259 case MachO::CPU_SUBTYPE_ARM_ALL:
1260 outs() << " cputype CPU_TYPE_ARM\n";
1261 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1263 case MachO::CPU_SUBTYPE_ARM_V4T:
1264 outs() << " cputype CPU_TYPE_ARM\n";
1265 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1267 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1268 outs() << " cputype CPU_TYPE_ARM\n";
1269 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1271 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1272 outs() << " cputype CPU_TYPE_ARM\n";
1273 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1275 case MachO::CPU_SUBTYPE_ARM_V6:
1276 outs() << " cputype CPU_TYPE_ARM\n";
1277 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1279 case MachO::CPU_SUBTYPE_ARM_V6M:
1280 outs() << " cputype CPU_TYPE_ARM\n";
1281 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1283 case MachO::CPU_SUBTYPE_ARM_V7:
1284 outs() << " cputype CPU_TYPE_ARM\n";
1285 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1287 case MachO::CPU_SUBTYPE_ARM_V7EM:
1288 outs() << " cputype CPU_TYPE_ARM\n";
1289 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1291 case MachO::CPU_SUBTYPE_ARM_V7K:
1292 outs() << " cputype CPU_TYPE_ARM\n";
1293 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1295 case MachO::CPU_SUBTYPE_ARM_V7M:
1296 outs() << " cputype CPU_TYPE_ARM\n";
1297 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1299 case MachO::CPU_SUBTYPE_ARM_V7S:
1300 outs() << " cputype CPU_TYPE_ARM\n";
1301 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1304 printUnknownCPUType(cputype, cpusubtype);
1308 case MachO::CPU_TYPE_ARM64:
1309 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1310 case MachO::CPU_SUBTYPE_ARM64_ALL:
1311 outs() << " cputype CPU_TYPE_ARM64\n";
1312 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1315 printUnknownCPUType(cputype, cpusubtype);
1320 printUnknownCPUType(cputype, cpusubtype);
1325 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1327 outs() << "Fat headers\n";
1329 outs() << "fat_magic FAT_MAGIC\n";
1331 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1333 uint32_t nfat_arch = UB->getNumberOfObjects();
1334 StringRef Buf = UB->getData();
1335 uint64_t size = Buf.size();
1336 uint64_t big_size = sizeof(struct MachO::fat_header) +
1337 nfat_arch * sizeof(struct MachO::fat_arch);
1338 outs() << "nfat_arch " << UB->getNumberOfObjects();
1340 outs() << " (malformed, contains zero architecture types)\n";
1341 else if (big_size > size)
1342 outs() << " (malformed, architectures past end of file)\n";
1346 for (uint32_t i = 0; i < nfat_arch; ++i) {
1347 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1348 uint32_t cputype = OFA.getCPUType();
1349 uint32_t cpusubtype = OFA.getCPUSubType();
1350 outs() << "architecture ";
1351 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1352 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1353 uint32_t other_cputype = other_OFA.getCPUType();
1354 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1355 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1356 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1357 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1358 outs() << "(illegal duplicate architecture) ";
1363 outs() << OFA.getArchTypeName() << "\n";
1364 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1366 outs() << i << "\n";
1367 outs() << " cputype " << cputype << "\n";
1368 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1372 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1373 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1375 outs() << " capabilities "
1376 << format("0x%" PRIx32,
1377 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1378 outs() << " offset " << OFA.getOffset();
1379 if (OFA.getOffset() > size)
1380 outs() << " (past end of file)";
1381 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1382 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1384 outs() << " size " << OFA.getSize();
1385 big_size = OFA.getOffset() + OFA.getSize();
1386 if (big_size > size)
1387 outs() << " (past end of file)";
1389 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1394 static void printArchiveChild(Archive::Child &C, bool verbose,
1395 bool print_offset) {
1397 outs() << C.getChildOffset() << "\t";
1398 sys::fs::perms Mode = C.getAccessMode();
1400 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1401 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1403 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1404 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1405 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1406 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1407 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1408 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1409 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1410 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1411 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1413 outs() << format("0%o ", Mode);
1416 unsigned UID = C.getUID();
1417 outs() << format("%3d/", UID);
1418 unsigned GID = C.getGID();
1419 outs() << format("%-3d ", GID);
1420 uint64_t Size = C.getRawSize();
1421 outs() << format("%5" PRId64, Size) << " ";
1423 StringRef RawLastModified = C.getRawLastModified();
1426 if (RawLastModified.getAsInteger(10, Seconds))
1427 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1429 // Since cime(3) returns a 26 character string of the form:
1430 // "Sun Sep 16 01:03:52 1973\n\0"
1431 // just print 24 characters.
1433 outs() << format("%.24s ", ctime(&t));
1436 outs() << RawLastModified << " ";
1440 ErrorOr<StringRef> NameOrErr = C.getName();
1441 if (NameOrErr.getError()) {
1442 StringRef RawName = C.getRawName();
1443 outs() << RawName << "\n";
1445 StringRef Name = NameOrErr.get();
1446 outs() << Name << "\n";
1449 StringRef RawName = C.getRawName();
1450 outs() << RawName << "\n";
1454 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1455 if (A->hasSymbolTable()) {
1456 Archive::child_iterator S = A->getSymbolTableChild();
1457 Archive::Child C = *S;
1458 printArchiveChild(C, verbose, print_offset);
1460 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1462 Archive::Child C = *I;
1463 printArchiveChild(C, verbose, print_offset);
1467 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1468 // -arch flags selecting just those slices as specified by them and also parses
1469 // archive files. Then for each individual Mach-O file ProcessMachO() is
1470 // called to process the file based on the command line options.
1471 void llvm::ParseInputMachO(StringRef Filename) {
1472 // Check for -arch all and verifiy the -arch flags are valid.
1473 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1474 if (ArchFlags[i] == "all") {
1477 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1478 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1479 "'for the -arch option\n";
1485 // Attempt to open the binary.
1486 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1487 if (std::error_code EC = BinaryOrErr.getError()) {
1488 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
1491 Binary &Bin = *BinaryOrErr.get().getBinary();
1493 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1494 outs() << "Archive : " << Filename << "\n";
1496 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
1497 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1499 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1500 if (ChildOrErr.getError())
1502 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1503 if (!checkMachOAndArchFlags(O, Filename))
1505 ProcessMachO(Filename, O, O->getFileName());
1510 if (UniversalHeaders) {
1511 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1512 printMachOUniversalHeaders(UB, !NonVerbose);
1514 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1515 // If we have a list of architecture flags specified dump only those.
1516 if (!ArchAll && ArchFlags.size() != 0) {
1517 // Look for a slice in the universal binary that matches each ArchFlag.
1519 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1521 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1522 E = UB->end_objects();
1524 if (ArchFlags[i] == I->getArchTypeName()) {
1526 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1527 I->getAsObjectFile();
1528 std::string ArchitectureName = "";
1529 if (ArchFlags.size() > 1)
1530 ArchitectureName = I->getArchTypeName();
1532 ObjectFile &O = *ObjOrErr.get();
1533 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1534 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1535 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1536 I->getAsArchive()) {
1537 std::unique_ptr<Archive> &A = *AOrErr;
1538 outs() << "Archive : " << Filename;
1539 if (!ArchitectureName.empty())
1540 outs() << " (architecture " << ArchitectureName << ")";
1543 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1544 for (Archive::child_iterator AI = A->child_begin(),
1545 AE = A->child_end();
1547 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1548 if (ChildOrErr.getError())
1550 if (MachOObjectFile *O =
1551 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1552 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1558 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1559 << "architecture: " + ArchFlags[i] + "\n";
1565 // No architecture flags were specified so if this contains a slice that
1566 // matches the host architecture dump only that.
1568 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1569 E = UB->end_objects();
1571 if (MachOObjectFile::getHostArch().getArchName() ==
1572 I->getArchTypeName()) {
1573 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1574 std::string ArchiveName;
1575 ArchiveName.clear();
1577 ObjectFile &O = *ObjOrErr.get();
1578 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1579 ProcessMachO(Filename, MachOOF);
1580 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1581 I->getAsArchive()) {
1582 std::unique_ptr<Archive> &A = *AOrErr;
1583 outs() << "Archive : " << Filename << "\n";
1585 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1586 for (Archive::child_iterator AI = A->child_begin(),
1587 AE = A->child_end();
1589 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1590 if (ChildOrErr.getError())
1592 if (MachOObjectFile *O =
1593 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1594 ProcessMachO(Filename, O, O->getFileName());
1601 // Either all architectures have been specified or none have been specified
1602 // and this does not contain the host architecture so dump all the slices.
1603 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1604 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1605 E = UB->end_objects();
1607 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1608 std::string ArchitectureName = "";
1609 if (moreThanOneArch)
1610 ArchitectureName = I->getArchTypeName();
1612 ObjectFile &Obj = *ObjOrErr.get();
1613 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1614 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1615 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1616 std::unique_ptr<Archive> &A = *AOrErr;
1617 outs() << "Archive : " << Filename;
1618 if (!ArchitectureName.empty())
1619 outs() << " (architecture " << ArchitectureName << ")";
1622 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1623 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1625 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1626 if (ChildOrErr.getError())
1628 if (MachOObjectFile *O =
1629 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1630 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1631 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1639 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1640 if (!checkMachOAndArchFlags(O, Filename))
1642 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1643 ProcessMachO(Filename, MachOOF);
1645 errs() << "llvm-objdump: '" << Filename << "': "
1646 << "Object is not a Mach-O file type.\n";
1648 errs() << "llvm-objdump: '" << Filename << "': "
1649 << "Unrecognized file type.\n";
1652 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1653 typedef std::vector<BindInfoEntry> BindTable;
1654 typedef BindTable::iterator bind_table_iterator;
1656 // The block of info used by the Symbolizer call backs.
1657 struct DisassembleInfo {
1661 SymbolAddressMap *AddrMap;
1662 std::vector<SectionRef> *Sections;
1663 const char *class_name;
1664 const char *selector_name;
1666 char *demangled_name;
1669 BindTable *bindtable;
1673 // SymbolizerGetOpInfo() is the operand information call back function.
1674 // This is called to get the symbolic information for operand(s) of an
1675 // instruction when it is being done. This routine does this from
1676 // the relocation information, symbol table, etc. That block of information
1677 // is a pointer to the struct DisassembleInfo that was passed when the
1678 // disassembler context was created and passed to back to here when
1679 // called back by the disassembler for instruction operands that could have
1680 // relocation information. The address of the instruction containing operand is
1681 // at the Pc parameter. The immediate value the operand has is passed in
1682 // op_info->Value and is at Offset past the start of the instruction and has a
1683 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1684 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1685 // names and addends of the symbolic expression to add for the operand. The
1686 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1687 // information is returned then this function returns 1 else it returns 0.
1688 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1689 uint64_t Size, int TagType, void *TagBuf) {
1690 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1691 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1692 uint64_t value = op_info->Value;
1694 // Make sure all fields returned are zero if we don't set them.
1695 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1696 op_info->Value = value;
1698 // If the TagType is not the value 1 which it code knows about or if no
1699 // verbose symbolic information is wanted then just return 0, indicating no
1700 // information is being returned.
1701 if (TagType != 1 || !info->verbose)
1704 unsigned int Arch = info->O->getArch();
1705 if (Arch == Triple::x86) {
1706 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1708 // First search the section's relocation entries (if any) for an entry
1709 // for this section offset.
1710 uint32_t sect_addr = info->S.getAddress();
1711 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1712 bool reloc_found = false;
1714 MachO::any_relocation_info RE;
1715 bool isExtern = false;
1717 bool r_scattered = false;
1718 uint32_t r_value, pair_r_value, r_type;
1719 for (const RelocationRef &Reloc : info->S.relocations()) {
1720 uint64_t RelocOffset = Reloc.getOffset();
1721 if (RelocOffset == sect_offset) {
1722 Rel = Reloc.getRawDataRefImpl();
1723 RE = info->O->getRelocation(Rel);
1724 r_type = info->O->getAnyRelocationType(RE);
1725 r_scattered = info->O->isRelocationScattered(RE);
1727 r_value = info->O->getScatteredRelocationValue(RE);
1728 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1729 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1730 DataRefImpl RelNext = Rel;
1731 info->O->moveRelocationNext(RelNext);
1732 MachO::any_relocation_info RENext;
1733 RENext = info->O->getRelocation(RelNext);
1734 if (info->O->isRelocationScattered(RENext))
1735 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1740 isExtern = info->O->getPlainRelocationExternal(RE);
1742 symbol_iterator RelocSym = Reloc.getSymbol();
1750 if (reloc_found && isExtern) {
1751 ErrorOr<StringRef> SymName = Symbol.getName();
1752 if (std::error_code EC = SymName.getError())
1753 report_fatal_error(EC.message());
1754 const char *name = SymName->data();
1755 op_info->AddSymbol.Present = 1;
1756 op_info->AddSymbol.Name = name;
1757 // For i386 extern relocation entries the value in the instruction is
1758 // the offset from the symbol, and value is already set in op_info->Value.
1761 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1762 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1763 const char *add = GuessSymbolName(r_value, info->AddrMap);
1764 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1765 uint32_t offset = value - (r_value - pair_r_value);
1766 op_info->AddSymbol.Present = 1;
1768 op_info->AddSymbol.Name = add;
1770 op_info->AddSymbol.Value = r_value;
1771 op_info->SubtractSymbol.Present = 1;
1773 op_info->SubtractSymbol.Name = sub;
1775 op_info->SubtractSymbol.Value = pair_r_value;
1776 op_info->Value = offset;
1780 // Second search the external relocation entries of a fully linked image
1781 // (if any) for an entry that matches this segment offset.
1782 // uint32_t seg_offset = (Pc + Offset);
1785 if (Arch == Triple::x86_64) {
1786 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1788 // First search the section's relocation entries (if any) for an entry
1789 // for this section offset.
1790 uint64_t sect_addr = info->S.getAddress();
1791 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1792 bool reloc_found = false;
1794 MachO::any_relocation_info RE;
1795 bool isExtern = false;
1797 for (const RelocationRef &Reloc : info->S.relocations()) {
1798 uint64_t RelocOffset = Reloc.getOffset();
1799 if (RelocOffset == sect_offset) {
1800 Rel = Reloc.getRawDataRefImpl();
1801 RE = info->O->getRelocation(Rel);
1802 // NOTE: Scattered relocations don't exist on x86_64.
1803 isExtern = info->O->getPlainRelocationExternal(RE);
1805 symbol_iterator RelocSym = Reloc.getSymbol();
1812 if (reloc_found && isExtern) {
1813 // The Value passed in will be adjusted by the Pc if the instruction
1814 // adds the Pc. But for x86_64 external relocation entries the Value
1815 // is the offset from the external symbol.
1816 if (info->O->getAnyRelocationPCRel(RE))
1817 op_info->Value -= Pc + Offset + Size;
1818 ErrorOr<StringRef> SymName = Symbol.getName();
1819 if (std::error_code EC = SymName.getError())
1820 report_fatal_error(EC.message());
1821 const char *name = SymName->data();
1822 unsigned Type = info->O->getAnyRelocationType(RE);
1823 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1824 DataRefImpl RelNext = Rel;
1825 info->O->moveRelocationNext(RelNext);
1826 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1827 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1828 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1829 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1830 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1831 op_info->SubtractSymbol.Present = 1;
1832 op_info->SubtractSymbol.Name = name;
1833 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1834 Symbol = *RelocSymNext;
1835 ErrorOr<StringRef> SymNameNext = Symbol.getName();
1836 if (std::error_code EC = SymNameNext.getError())
1837 report_fatal_error(EC.message());
1838 name = SymNameNext->data();
1841 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1842 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1843 op_info->AddSymbol.Present = 1;
1844 op_info->AddSymbol.Name = name;
1848 // Second search the external relocation entries of a fully linked image
1849 // (if any) for an entry that matches this segment offset.
1850 // uint64_t seg_offset = (Pc + Offset);
1853 if (Arch == Triple::arm) {
1854 if (Offset != 0 || (Size != 4 && Size != 2))
1856 // First search the section's relocation entries (if any) for an entry
1857 // for this section offset.
1858 uint32_t sect_addr = info->S.getAddress();
1859 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1861 MachO::any_relocation_info RE;
1862 bool isExtern = false;
1864 bool r_scattered = false;
1865 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1867 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1868 [&](const RelocationRef &Reloc) {
1869 uint64_t RelocOffset = Reloc.getOffset();
1870 return RelocOffset == sect_offset;
1873 if (Reloc == info->S.relocations().end())
1876 Rel = Reloc->getRawDataRefImpl();
1877 RE = info->O->getRelocation(Rel);
1878 r_length = info->O->getAnyRelocationLength(RE);
1879 r_scattered = info->O->isRelocationScattered(RE);
1881 r_value = info->O->getScatteredRelocationValue(RE);
1882 r_type = info->O->getScatteredRelocationType(RE);
1884 r_type = info->O->getAnyRelocationType(RE);
1885 isExtern = info->O->getPlainRelocationExternal(RE);
1887 symbol_iterator RelocSym = Reloc->getSymbol();
1891 if (r_type == MachO::ARM_RELOC_HALF ||
1892 r_type == MachO::ARM_RELOC_SECTDIFF ||
1893 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1894 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1895 DataRefImpl RelNext = Rel;
1896 info->O->moveRelocationNext(RelNext);
1897 MachO::any_relocation_info RENext;
1898 RENext = info->O->getRelocation(RelNext);
1899 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1900 if (info->O->isRelocationScattered(RENext))
1901 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1905 ErrorOr<StringRef> SymName = Symbol.getName();
1906 if (std::error_code EC = SymName.getError())
1907 report_fatal_error(EC.message());
1908 const char *name = SymName->data();
1909 op_info->AddSymbol.Present = 1;
1910 op_info->AddSymbol.Name = name;
1912 case MachO::ARM_RELOC_HALF:
1913 if ((r_length & 0x1) == 1) {
1914 op_info->Value = value << 16 | other_half;
1915 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1917 op_info->Value = other_half << 16 | value;
1918 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1926 // If we have a branch that is not an external relocation entry then
1927 // return 0 so the code in tryAddingSymbolicOperand() can use the
1928 // SymbolLookUp call back with the branch target address to look up the
1929 // symbol and possiblity add an annotation for a symbol stub.
1930 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1931 r_type == MachO::ARM_THUMB_RELOC_BR22))
1934 uint32_t offset = 0;
1935 if (r_type == MachO::ARM_RELOC_HALF ||
1936 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1937 if ((r_length & 0x1) == 1)
1938 value = value << 16 | other_half;
1940 value = other_half << 16 | value;
1942 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1943 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1944 offset = value - r_value;
1948 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1949 if ((r_length & 0x1) == 1)
1950 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1952 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1953 const char *add = GuessSymbolName(r_value, info->AddrMap);
1954 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1955 int32_t offset = value - (r_value - pair_r_value);
1956 op_info->AddSymbol.Present = 1;
1958 op_info->AddSymbol.Name = add;
1960 op_info->AddSymbol.Value = r_value;
1961 op_info->SubtractSymbol.Present = 1;
1963 op_info->SubtractSymbol.Name = sub;
1965 op_info->SubtractSymbol.Value = pair_r_value;
1966 op_info->Value = offset;
1970 op_info->AddSymbol.Present = 1;
1971 op_info->Value = offset;
1972 if (r_type == MachO::ARM_RELOC_HALF) {
1973 if ((r_length & 0x1) == 1)
1974 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1976 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1978 const char *add = GuessSymbolName(value, info->AddrMap);
1979 if (add != nullptr) {
1980 op_info->AddSymbol.Name = add;
1983 op_info->AddSymbol.Value = value;
1986 if (Arch == Triple::aarch64) {
1987 if (Offset != 0 || Size != 4)
1989 // First search the section's relocation entries (if any) for an entry
1990 // for this section offset.
1991 uint64_t sect_addr = info->S.getAddress();
1992 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1994 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1995 [&](const RelocationRef &Reloc) {
1996 uint64_t RelocOffset = Reloc.getOffset();
1997 return RelocOffset == sect_offset;
2000 if (Reloc == info->S.relocations().end())
2003 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2004 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2005 uint32_t r_type = info->O->getAnyRelocationType(RE);
2006 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2007 DataRefImpl RelNext = Rel;
2008 info->O->moveRelocationNext(RelNext);
2009 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2011 value = info->O->getPlainRelocationSymbolNum(RENext);
2012 op_info->Value = value;
2015 // NOTE: Scattered relocations don't exist on arm64.
2016 if (!info->O->getPlainRelocationExternal(RE))
2018 ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
2019 if (std::error_code EC = SymName.getError())
2020 report_fatal_error(EC.message());
2021 const char *name = SymName->data();
2022 op_info->AddSymbol.Present = 1;
2023 op_info->AddSymbol.Name = name;
2026 case MachO::ARM64_RELOC_PAGE21:
2028 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2030 case MachO::ARM64_RELOC_PAGEOFF12:
2032 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2034 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2036 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2038 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2040 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2042 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2043 /* @tvlppage is not implemented in llvm-mc */
2044 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2046 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2047 /* @tvlppageoff is not implemented in llvm-mc */
2048 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2051 case MachO::ARM64_RELOC_BRANCH26:
2052 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2060 // GuessCstringPointer is passed the address of what might be a pointer to a
2061 // literal string in a cstring section. If that address is in a cstring section
2062 // it returns a pointer to that string. Else it returns nullptr.
2063 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2064 struct DisassembleInfo *info) {
2065 for (const auto &Load : info->O->load_commands()) {
2066 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2067 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2068 for (unsigned J = 0; J < Seg.nsects; ++J) {
2069 MachO::section_64 Sec = info->O->getSection64(Load, J);
2070 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2071 if (section_type == MachO::S_CSTRING_LITERALS &&
2072 ReferenceValue >= Sec.addr &&
2073 ReferenceValue < Sec.addr + Sec.size) {
2074 uint64_t sect_offset = ReferenceValue - Sec.addr;
2075 uint64_t object_offset = Sec.offset + sect_offset;
2076 StringRef MachOContents = info->O->getData();
2077 uint64_t object_size = MachOContents.size();
2078 const char *object_addr = (const char *)MachOContents.data();
2079 if (object_offset < object_size) {
2080 const char *name = object_addr + object_offset;
2087 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2088 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2089 for (unsigned J = 0; J < Seg.nsects; ++J) {
2090 MachO::section Sec = info->O->getSection(Load, J);
2091 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2092 if (section_type == MachO::S_CSTRING_LITERALS &&
2093 ReferenceValue >= Sec.addr &&
2094 ReferenceValue < Sec.addr + Sec.size) {
2095 uint64_t sect_offset = ReferenceValue - Sec.addr;
2096 uint64_t object_offset = Sec.offset + sect_offset;
2097 StringRef MachOContents = info->O->getData();
2098 uint64_t object_size = MachOContents.size();
2099 const char *object_addr = (const char *)MachOContents.data();
2100 if (object_offset < object_size) {
2101 const char *name = object_addr + object_offset;
2113 // GuessIndirectSymbol returns the name of the indirect symbol for the
2114 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2115 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2116 // symbol name being referenced by the stub or pointer.
2117 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2118 struct DisassembleInfo *info) {
2119 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2120 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2121 for (const auto &Load : info->O->load_commands()) {
2122 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2123 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2124 for (unsigned J = 0; J < Seg.nsects; ++J) {
2125 MachO::section_64 Sec = info->O->getSection64(Load, J);
2126 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2127 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2128 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2129 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2130 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2131 section_type == MachO::S_SYMBOL_STUBS) &&
2132 ReferenceValue >= Sec.addr &&
2133 ReferenceValue < Sec.addr + Sec.size) {
2135 if (section_type == MachO::S_SYMBOL_STUBS)
2136 stride = Sec.reserved2;
2141 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2142 if (index < Dysymtab.nindirectsyms) {
2143 uint32_t indirect_symbol =
2144 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2145 if (indirect_symbol < Symtab.nsyms) {
2146 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2147 SymbolRef Symbol = *Sym;
2148 ErrorOr<StringRef> SymName = Symbol.getName();
2149 if (std::error_code EC = SymName.getError())
2150 report_fatal_error(EC.message());
2151 const char *name = SymName->data();
2157 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2158 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2159 for (unsigned J = 0; J < Seg.nsects; ++J) {
2160 MachO::section Sec = info->O->getSection(Load, J);
2161 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2162 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2163 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2164 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2165 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2166 section_type == MachO::S_SYMBOL_STUBS) &&
2167 ReferenceValue >= Sec.addr &&
2168 ReferenceValue < Sec.addr + Sec.size) {
2170 if (section_type == MachO::S_SYMBOL_STUBS)
2171 stride = Sec.reserved2;
2176 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2177 if (index < Dysymtab.nindirectsyms) {
2178 uint32_t indirect_symbol =
2179 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2180 if (indirect_symbol < Symtab.nsyms) {
2181 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2182 SymbolRef Symbol = *Sym;
2183 ErrorOr<StringRef> SymName = Symbol.getName();
2184 if (std::error_code EC = SymName.getError())
2185 report_fatal_error(EC.message());
2186 const char *name = SymName->data();
2197 // method_reference() is called passing it the ReferenceName that might be
2198 // a reference it to an Objective-C method call. If so then it allocates and
2199 // assembles a method call string with the values last seen and saved in
2200 // the DisassembleInfo's class_name and selector_name fields. This is saved
2201 // into the method field of the info and any previous string is free'ed.
2202 // Then the class_name field in the info is set to nullptr. The method call
2203 // string is set into ReferenceName and ReferenceType is set to
2204 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2205 // then both ReferenceType and ReferenceName are left unchanged.
2206 static void method_reference(struct DisassembleInfo *info,
2207 uint64_t *ReferenceType,
2208 const char **ReferenceName) {
2209 unsigned int Arch = info->O->getArch();
2210 if (*ReferenceName != nullptr) {
2211 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2212 if (info->selector_name != nullptr) {
2213 if (info->method != nullptr)
2215 if (info->class_name != nullptr) {
2216 info->method = (char *)malloc(5 + strlen(info->class_name) +
2217 strlen(info->selector_name));
2218 if (info->method != nullptr) {
2219 strcpy(info->method, "+[");
2220 strcat(info->method, info->class_name);
2221 strcat(info->method, " ");
2222 strcat(info->method, info->selector_name);
2223 strcat(info->method, "]");
2224 *ReferenceName = info->method;
2225 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2228 info->method = (char *)malloc(9 + strlen(info->selector_name));
2229 if (info->method != nullptr) {
2230 if (Arch == Triple::x86_64)
2231 strcpy(info->method, "-[%rdi ");
2232 else if (Arch == Triple::aarch64)
2233 strcpy(info->method, "-[x0 ");
2235 strcpy(info->method, "-[r? ");
2236 strcat(info->method, info->selector_name);
2237 strcat(info->method, "]");
2238 *ReferenceName = info->method;
2239 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2242 info->class_name = nullptr;
2244 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2245 if (info->selector_name != nullptr) {
2246 if (info->method != nullptr)
2248 info->method = (char *)malloc(17 + strlen(info->selector_name));
2249 if (info->method != nullptr) {
2250 if (Arch == Triple::x86_64)
2251 strcpy(info->method, "-[[%rdi super] ");
2252 else if (Arch == Triple::aarch64)
2253 strcpy(info->method, "-[[x0 super] ");
2255 strcpy(info->method, "-[[r? super] ");
2256 strcat(info->method, info->selector_name);
2257 strcat(info->method, "]");
2258 *ReferenceName = info->method;
2259 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2261 info->class_name = nullptr;
2267 // GuessPointerPointer() is passed the address of what might be a pointer to
2268 // a reference to an Objective-C class, selector, message ref or cfstring.
2269 // If so the value of the pointer is returned and one of the booleans are set
2270 // to true. If not zero is returned and all the booleans are set to false.
2271 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2272 struct DisassembleInfo *info,
2273 bool &classref, bool &selref, bool &msgref,
2279 for (const auto &Load : info->O->load_commands()) {
2280 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2281 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2282 for (unsigned J = 0; J < Seg.nsects; ++J) {
2283 MachO::section_64 Sec = info->O->getSection64(Load, J);
2284 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2285 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2286 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2287 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2288 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2289 ReferenceValue >= Sec.addr &&
2290 ReferenceValue < Sec.addr + Sec.size) {
2291 uint64_t sect_offset = ReferenceValue - Sec.addr;
2292 uint64_t object_offset = Sec.offset + sect_offset;
2293 StringRef MachOContents = info->O->getData();
2294 uint64_t object_size = MachOContents.size();
2295 const char *object_addr = (const char *)MachOContents.data();
2296 if (object_offset < object_size) {
2297 uint64_t pointer_value;
2298 memcpy(&pointer_value, object_addr + object_offset,
2300 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2301 sys::swapByteOrder(pointer_value);
2302 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2304 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2305 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2307 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2308 ReferenceValue + 8 < Sec.addr + Sec.size) {
2310 memcpy(&pointer_value, object_addr + object_offset + 8,
2312 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2313 sys::swapByteOrder(pointer_value);
2314 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2316 return pointer_value;
2323 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2328 // get_pointer_64 returns a pointer to the bytes in the object file at the
2329 // Address from a section in the Mach-O file. And indirectly returns the
2330 // offset into the section, number of bytes left in the section past the offset
2331 // and which section is was being referenced. If the Address is not in a
2332 // section nullptr is returned.
2333 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2334 uint32_t &left, SectionRef &S,
2335 DisassembleInfo *info,
2336 bool objc_only = false) {
2340 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2341 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2342 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2345 ((*(info->Sections))[SectIdx]).getName(SectName);
2346 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2347 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2348 if (SegName != "__OBJC" && SectName != "__cstring")
2351 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2352 S = (*(info->Sections))[SectIdx];
2353 offset = Address - SectAddress;
2354 left = SectSize - offset;
2355 StringRef SectContents;
2356 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2357 return SectContents.data() + offset;
2363 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2364 uint32_t &left, SectionRef &S,
2365 DisassembleInfo *info,
2366 bool objc_only = false) {
2367 return get_pointer_64(Address, offset, left, S, info, objc_only);
2370 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2371 // the symbol indirectly through n_value. Based on the relocation information
2372 // for the specified section offset in the specified section reference.
2373 // If no relocation information is found and a non-zero ReferenceValue for the
2374 // symbol is passed, look up that address in the info's AddrMap.
2375 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2376 DisassembleInfo *info, uint64_t &n_value,
2377 uint64_t ReferenceValue = 0) {
2382 // See if there is an external relocation entry at the sect_offset.
2383 bool reloc_found = false;
2385 MachO::any_relocation_info RE;
2386 bool isExtern = false;
2388 for (const RelocationRef &Reloc : S.relocations()) {
2389 uint64_t RelocOffset = Reloc.getOffset();
2390 if (RelocOffset == sect_offset) {
2391 Rel = Reloc.getRawDataRefImpl();
2392 RE = info->O->getRelocation(Rel);
2393 if (info->O->isRelocationScattered(RE))
2395 isExtern = info->O->getPlainRelocationExternal(RE);
2397 symbol_iterator RelocSym = Reloc.getSymbol();
2404 // If there is an external relocation entry for a symbol in this section
2405 // at this section_offset then use that symbol's value for the n_value
2406 // and return its name.
2407 const char *SymbolName = nullptr;
2408 if (reloc_found && isExtern) {
2409 n_value = Symbol.getValue();
2410 ErrorOr<StringRef> NameOrError = Symbol.getName();
2411 if (std::error_code EC = NameOrError.getError())
2412 report_fatal_error(EC.message());
2413 StringRef Name = *NameOrError;
2414 if (!Name.empty()) {
2415 SymbolName = Name.data();
2420 // TODO: For fully linked images, look through the external relocation
2421 // entries off the dynamic symtab command. For these the r_offset is from the
2422 // start of the first writeable segment in the Mach-O file. So the offset
2423 // to this section from that segment is passed to this routine by the caller,
2424 // as the database_offset. Which is the difference of the section's starting
2425 // address and the first writable segment.
2427 // NOTE: need add passing the database_offset to this routine.
2429 // We did not find an external relocation entry so look up the ReferenceValue
2430 // as an address of a symbol and if found return that symbol's name.
2431 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2436 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2437 DisassembleInfo *info,
2438 uint32_t ReferenceValue) {
2440 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2443 // These are structs in the Objective-C meta data and read to produce the
2444 // comments for disassembly. While these are part of the ABI they are no
2445 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2447 // The cfstring object in a 64-bit Mach-O file.
2448 struct cfstring64_t {
2449 uint64_t isa; // class64_t * (64-bit pointer)
2450 uint64_t flags; // flag bits
2451 uint64_t characters; // char * (64-bit pointer)
2452 uint64_t length; // number of non-NULL characters in above
2455 // The class object in a 64-bit Mach-O file.
2457 uint64_t isa; // class64_t * (64-bit pointer)
2458 uint64_t superclass; // class64_t * (64-bit pointer)
2459 uint64_t cache; // Cache (64-bit pointer)
2460 uint64_t vtable; // IMP * (64-bit pointer)
2461 uint64_t data; // class_ro64_t * (64-bit pointer)
2465 uint32_t isa; /* class32_t * (32-bit pointer) */
2466 uint32_t superclass; /* class32_t * (32-bit pointer) */
2467 uint32_t cache; /* Cache (32-bit pointer) */
2468 uint32_t vtable; /* IMP * (32-bit pointer) */
2469 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2472 struct class_ro64_t {
2474 uint32_t instanceStart;
2475 uint32_t instanceSize;
2477 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2478 uint64_t name; // const char * (64-bit pointer)
2479 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2480 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2481 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2482 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2483 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2486 struct class_ro32_t {
2488 uint32_t instanceStart;
2489 uint32_t instanceSize;
2490 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2491 uint32_t name; /* const char * (32-bit pointer) */
2492 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2493 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2494 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2495 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2496 uint32_t baseProperties; /* const struct objc_property_list *
2500 /* Values for class_ro{64,32}_t->flags */
2501 #define RO_META (1 << 0)
2502 #define RO_ROOT (1 << 1)
2503 #define RO_HAS_CXX_STRUCTORS (1 << 2)
2505 struct method_list64_t {
2508 /* struct method64_t first; These structures follow inline */
2511 struct method_list32_t {
2514 /* struct method32_t first; These structures follow inline */
2518 uint64_t name; /* SEL (64-bit pointer) */
2519 uint64_t types; /* const char * (64-bit pointer) */
2520 uint64_t imp; /* IMP (64-bit pointer) */
2524 uint32_t name; /* SEL (32-bit pointer) */
2525 uint32_t types; /* const char * (32-bit pointer) */
2526 uint32_t imp; /* IMP (32-bit pointer) */
2529 struct protocol_list64_t {
2530 uint64_t count; /* uintptr_t (a 64-bit value) */
2531 /* struct protocol64_t * list[0]; These pointers follow inline */
2534 struct protocol_list32_t {
2535 uint32_t count; /* uintptr_t (a 32-bit value) */
2536 /* struct protocol32_t * list[0]; These pointers follow inline */
2539 struct protocol64_t {
2540 uint64_t isa; /* id * (64-bit pointer) */
2541 uint64_t name; /* const char * (64-bit pointer) */
2542 uint64_t protocols; /* struct protocol_list64_t *
2544 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2545 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2546 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2547 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2548 uint64_t instanceProperties; /* struct objc_property_list *
2552 struct protocol32_t {
2553 uint32_t isa; /* id * (32-bit pointer) */
2554 uint32_t name; /* const char * (32-bit pointer) */
2555 uint32_t protocols; /* struct protocol_list_t *
2557 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2558 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2559 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2560 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2561 uint32_t instanceProperties; /* struct objc_property_list *
2565 struct ivar_list64_t {
2568 /* struct ivar64_t first; These structures follow inline */
2571 struct ivar_list32_t {
2574 /* struct ivar32_t first; These structures follow inline */
2578 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2579 uint64_t name; /* const char * (64-bit pointer) */
2580 uint64_t type; /* const char * (64-bit pointer) */
2586 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2587 uint32_t name; /* const char * (32-bit pointer) */
2588 uint32_t type; /* const char * (32-bit pointer) */
2593 struct objc_property_list64 {
2596 /* struct objc_property64 first; These structures follow inline */
2599 struct objc_property_list32 {
2602 /* struct objc_property32 first; These structures follow inline */
2605 struct objc_property64 {
2606 uint64_t name; /* const char * (64-bit pointer) */
2607 uint64_t attributes; /* const char * (64-bit pointer) */
2610 struct objc_property32 {
2611 uint32_t name; /* const char * (32-bit pointer) */
2612 uint32_t attributes; /* const char * (32-bit pointer) */
2615 struct category64_t {
2616 uint64_t name; /* const char * (64-bit pointer) */
2617 uint64_t cls; /* struct class_t * (64-bit pointer) */
2618 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2619 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2620 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2621 uint64_t instanceProperties; /* struct objc_property_list *
2625 struct category32_t {
2626 uint32_t name; /* const char * (32-bit pointer) */
2627 uint32_t cls; /* struct class_t * (32-bit pointer) */
2628 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2629 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2630 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2631 uint32_t instanceProperties; /* struct objc_property_list *
2635 struct objc_image_info64 {
2639 struct objc_image_info32 {
2643 struct imageInfo_t {
2647 /* masks for objc_image_info.flags */
2648 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2649 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2651 struct message_ref64 {
2652 uint64_t imp; /* IMP (64-bit pointer) */
2653 uint64_t sel; /* SEL (64-bit pointer) */
2656 struct message_ref32 {
2657 uint32_t imp; /* IMP (32-bit pointer) */
2658 uint32_t sel; /* SEL (32-bit pointer) */
2661 // Objective-C 1 (32-bit only) meta data structs.
2663 struct objc_module_t {
2666 uint32_t name; /* char * (32-bit pointer) */
2667 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2670 struct objc_symtab_t {
2671 uint32_t sel_ref_cnt;
2672 uint32_t refs; /* SEL * (32-bit pointer) */
2673 uint16_t cls_def_cnt;
2674 uint16_t cat_def_cnt;
2675 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2678 struct objc_class_t {
2679 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2680 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2681 uint32_t name; /* const char * (32-bit pointer) */
2684 int32_t instance_size;
2685 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2686 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2687 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2688 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2691 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2692 // class is not a metaclass
2693 #define CLS_CLASS 0x1
2694 // class is a metaclass
2695 #define CLS_META 0x2
2697 struct objc_category_t {
2698 uint32_t category_name; /* char * (32-bit pointer) */
2699 uint32_t class_name; /* char * (32-bit pointer) */
2700 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2701 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2702 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2705 struct objc_ivar_t {
2706 uint32_t ivar_name; /* char * (32-bit pointer) */
2707 uint32_t ivar_type; /* char * (32-bit pointer) */
2708 int32_t ivar_offset;
2711 struct objc_ivar_list_t {
2713 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2716 struct objc_method_list_t {
2717 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2718 int32_t method_count;
2719 // struct objc_method_t method_list[1]; /* variable length structure */
2722 struct objc_method_t {
2723 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2724 uint32_t method_types; /* char * (32-bit pointer) */
2725 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2729 struct objc_protocol_list_t {
2730 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2732 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2733 // (32-bit pointer) */
2736 struct objc_protocol_t {
2737 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2738 uint32_t protocol_name; /* char * (32-bit pointer) */
2739 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2740 uint32_t instance_methods; /* struct objc_method_description_list *
2742 uint32_t class_methods; /* struct objc_method_description_list *
2746 struct objc_method_description_list_t {
2748 // struct objc_method_description_t list[1];
2751 struct objc_method_description_t {
2752 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2753 uint32_t types; /* char * (32-bit pointer) */
2756 inline void swapStruct(struct cfstring64_t &cfs) {
2757 sys::swapByteOrder(cfs.isa);
2758 sys::swapByteOrder(cfs.flags);
2759 sys::swapByteOrder(cfs.characters);
2760 sys::swapByteOrder(cfs.length);
2763 inline void swapStruct(struct class64_t &c) {
2764 sys::swapByteOrder(c.isa);
2765 sys::swapByteOrder(c.superclass);
2766 sys::swapByteOrder(c.cache);
2767 sys::swapByteOrder(c.vtable);
2768 sys::swapByteOrder(c.data);
2771 inline void swapStruct(struct class32_t &c) {
2772 sys::swapByteOrder(c.isa);
2773 sys::swapByteOrder(c.superclass);
2774 sys::swapByteOrder(c.cache);
2775 sys::swapByteOrder(c.vtable);
2776 sys::swapByteOrder(c.data);
2779 inline void swapStruct(struct class_ro64_t &cro) {
2780 sys::swapByteOrder(cro.flags);
2781 sys::swapByteOrder(cro.instanceStart);
2782 sys::swapByteOrder(cro.instanceSize);
2783 sys::swapByteOrder(cro.reserved);
2784 sys::swapByteOrder(cro.ivarLayout);
2785 sys::swapByteOrder(cro.name);
2786 sys::swapByteOrder(cro.baseMethods);
2787 sys::swapByteOrder(cro.baseProtocols);
2788 sys::swapByteOrder(cro.ivars);
2789 sys::swapByteOrder(cro.weakIvarLayout);
2790 sys::swapByteOrder(cro.baseProperties);
2793 inline void swapStruct(struct class_ro32_t &cro) {
2794 sys::swapByteOrder(cro.flags);
2795 sys::swapByteOrder(cro.instanceStart);
2796 sys::swapByteOrder(cro.instanceSize);
2797 sys::swapByteOrder(cro.ivarLayout);
2798 sys::swapByteOrder(cro.name);
2799 sys::swapByteOrder(cro.baseMethods);
2800 sys::swapByteOrder(cro.baseProtocols);
2801 sys::swapByteOrder(cro.ivars);
2802 sys::swapByteOrder(cro.weakIvarLayout);
2803 sys::swapByteOrder(cro.baseProperties);
2806 inline void swapStruct(struct method_list64_t &ml) {
2807 sys::swapByteOrder(ml.entsize);
2808 sys::swapByteOrder(ml.count);
2811 inline void swapStruct(struct method_list32_t &ml) {
2812 sys::swapByteOrder(ml.entsize);
2813 sys::swapByteOrder(ml.count);
2816 inline void swapStruct(struct method64_t &m) {
2817 sys::swapByteOrder(m.name);
2818 sys::swapByteOrder(m.types);
2819 sys::swapByteOrder(m.imp);
2822 inline void swapStruct(struct method32_t &m) {
2823 sys::swapByteOrder(m.name);
2824 sys::swapByteOrder(m.types);
2825 sys::swapByteOrder(m.imp);
2828 inline void swapStruct(struct protocol_list64_t &pl) {
2829 sys::swapByteOrder(pl.count);
2832 inline void swapStruct(struct protocol_list32_t &pl) {
2833 sys::swapByteOrder(pl.count);
2836 inline void swapStruct(struct protocol64_t &p) {
2837 sys::swapByteOrder(p.isa);
2838 sys::swapByteOrder(p.name);
2839 sys::swapByteOrder(p.protocols);
2840 sys::swapByteOrder(p.instanceMethods);
2841 sys::swapByteOrder(p.classMethods);
2842 sys::swapByteOrder(p.optionalInstanceMethods);
2843 sys::swapByteOrder(p.optionalClassMethods);
2844 sys::swapByteOrder(p.instanceProperties);
2847 inline void swapStruct(struct protocol32_t &p) {
2848 sys::swapByteOrder(p.isa);
2849 sys::swapByteOrder(p.name);
2850 sys::swapByteOrder(p.protocols);
2851 sys::swapByteOrder(p.instanceMethods);
2852 sys::swapByteOrder(p.classMethods);
2853 sys::swapByteOrder(p.optionalInstanceMethods);
2854 sys::swapByteOrder(p.optionalClassMethods);
2855 sys::swapByteOrder(p.instanceProperties);
2858 inline void swapStruct(struct ivar_list64_t &il) {
2859 sys::swapByteOrder(il.entsize);
2860 sys::swapByteOrder(il.count);
2863 inline void swapStruct(struct ivar_list32_t &il) {
2864 sys::swapByteOrder(il.entsize);
2865 sys::swapByteOrder(il.count);
2868 inline void swapStruct(struct ivar64_t &i) {
2869 sys::swapByteOrder(i.offset);
2870 sys::swapByteOrder(i.name);
2871 sys::swapByteOrder(i.type);
2872 sys::swapByteOrder(i.alignment);
2873 sys::swapByteOrder(i.size);
2876 inline void swapStruct(struct ivar32_t &i) {
2877 sys::swapByteOrder(i.offset);
2878 sys::swapByteOrder(i.name);
2879 sys::swapByteOrder(i.type);
2880 sys::swapByteOrder(i.alignment);
2881 sys::swapByteOrder(i.size);
2884 inline void swapStruct(struct objc_property_list64 &pl) {
2885 sys::swapByteOrder(pl.entsize);
2886 sys::swapByteOrder(pl.count);
2889 inline void swapStruct(struct objc_property_list32 &pl) {
2890 sys::swapByteOrder(pl.entsize);
2891 sys::swapByteOrder(pl.count);
2894 inline void swapStruct(struct objc_property64 &op) {
2895 sys::swapByteOrder(op.name);
2896 sys::swapByteOrder(op.attributes);
2899 inline void swapStruct(struct objc_property32 &op) {
2900 sys::swapByteOrder(op.name);
2901 sys::swapByteOrder(op.attributes);
2904 inline void swapStruct(struct category64_t &c) {
2905 sys::swapByteOrder(c.name);
2906 sys::swapByteOrder(c.cls);
2907 sys::swapByteOrder(c.instanceMethods);
2908 sys::swapByteOrder(c.classMethods);
2909 sys::swapByteOrder(c.protocols);
2910 sys::swapByteOrder(c.instanceProperties);
2913 inline void swapStruct(struct category32_t &c) {
2914 sys::swapByteOrder(c.name);
2915 sys::swapByteOrder(c.cls);
2916 sys::swapByteOrder(c.instanceMethods);
2917 sys::swapByteOrder(c.classMethods);
2918 sys::swapByteOrder(c.protocols);
2919 sys::swapByteOrder(c.instanceProperties);
2922 inline void swapStruct(struct objc_image_info64 &o) {
2923 sys::swapByteOrder(o.version);
2924 sys::swapByteOrder(o.flags);
2927 inline void swapStruct(struct objc_image_info32 &o) {
2928 sys::swapByteOrder(o.version);
2929 sys::swapByteOrder(o.flags);
2932 inline void swapStruct(struct imageInfo_t &o) {
2933 sys::swapByteOrder(o.version);
2934 sys::swapByteOrder(o.flags);
2937 inline void swapStruct(struct message_ref64 &mr) {
2938 sys::swapByteOrder(mr.imp);
2939 sys::swapByteOrder(mr.sel);
2942 inline void swapStruct(struct message_ref32 &mr) {
2943 sys::swapByteOrder(mr.imp);
2944 sys::swapByteOrder(mr.sel);
2947 inline void swapStruct(struct objc_module_t &module) {
2948 sys::swapByteOrder(module.version);
2949 sys::swapByteOrder(module.size);
2950 sys::swapByteOrder(module.name);
2951 sys::swapByteOrder(module.symtab);
2954 inline void swapStruct(struct objc_symtab_t &symtab) {
2955 sys::swapByteOrder(symtab.sel_ref_cnt);
2956 sys::swapByteOrder(symtab.refs);
2957 sys::swapByteOrder(symtab.cls_def_cnt);
2958 sys::swapByteOrder(symtab.cat_def_cnt);
2961 inline void swapStruct(struct objc_class_t &objc_class) {
2962 sys::swapByteOrder(objc_class.isa);
2963 sys::swapByteOrder(objc_class.super_class);
2964 sys::swapByteOrder(objc_class.name);
2965 sys::swapByteOrder(objc_class.version);
2966 sys::swapByteOrder(objc_class.info);
2967 sys::swapByteOrder(objc_class.instance_size);
2968 sys::swapByteOrder(objc_class.ivars);
2969 sys::swapByteOrder(objc_class.methodLists);
2970 sys::swapByteOrder(objc_class.cache);
2971 sys::swapByteOrder(objc_class.protocols);
2974 inline void swapStruct(struct objc_category_t &objc_category) {
2975 sys::swapByteOrder(objc_category.category_name);
2976 sys::swapByteOrder(objc_category.class_name);
2977 sys::swapByteOrder(objc_category.instance_methods);
2978 sys::swapByteOrder(objc_category.class_methods);
2979 sys::swapByteOrder(objc_category.protocols);
2982 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
2983 sys::swapByteOrder(objc_ivar_list.ivar_count);
2986 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
2987 sys::swapByteOrder(objc_ivar.ivar_name);
2988 sys::swapByteOrder(objc_ivar.ivar_type);
2989 sys::swapByteOrder(objc_ivar.ivar_offset);
2992 inline void swapStruct(struct objc_method_list_t &method_list) {
2993 sys::swapByteOrder(method_list.obsolete);
2994 sys::swapByteOrder(method_list.method_count);
2997 inline void swapStruct(struct objc_method_t &method) {
2998 sys::swapByteOrder(method.method_name);
2999 sys::swapByteOrder(method.method_types);
3000 sys::swapByteOrder(method.method_imp);
3003 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3004 sys::swapByteOrder(protocol_list.next);
3005 sys::swapByteOrder(protocol_list.count);
3008 inline void swapStruct(struct objc_protocol_t &protocol) {
3009 sys::swapByteOrder(protocol.isa);
3010 sys::swapByteOrder(protocol.protocol_name);
3011 sys::swapByteOrder(protocol.protocol_list);
3012 sys::swapByteOrder(protocol.instance_methods);
3013 sys::swapByteOrder(protocol.class_methods);
3016 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3017 sys::swapByteOrder(mdl.count);
3020 inline void swapStruct(struct objc_method_description_t &md) {
3021 sys::swapByteOrder(md.name);
3022 sys::swapByteOrder(md.types);
3025 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3026 struct DisassembleInfo *info);
3028 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3029 // to an Objective-C class and returns the class name. It is also passed the
3030 // address of the pointer, so when the pointer is zero as it can be in an .o
3031 // file, that is used to look for an external relocation entry with a symbol
3033 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3034 uint64_t ReferenceValue,
3035 struct DisassembleInfo *info) {
3037 uint32_t offset, left;
3040 // The pointer_value can be 0 in an object file and have a relocation
3041 // entry for the class symbol at the ReferenceValue (the address of the
3043 if (pointer_value == 0) {
3044 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3045 if (r == nullptr || left < sizeof(uint64_t))
3048 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3049 if (symbol_name == nullptr)
3051 const char *class_name = strrchr(symbol_name, '$');
3052 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3053 return class_name + 2;
3058 // The case were the pointer_value is non-zero and points to a class defined
3059 // in this Mach-O file.
3060 r = get_pointer_64(pointer_value, offset, left, S, info);
3061 if (r == nullptr || left < sizeof(struct class64_t))
3064 memcpy(&c, r, sizeof(struct class64_t));
3065 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3069 r = get_pointer_64(c.data, offset, left, S, info);
3070 if (r == nullptr || left < sizeof(struct class_ro64_t))
3072 struct class_ro64_t cro;
3073 memcpy(&cro, r, sizeof(struct class_ro64_t));
3074 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3078 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3082 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3083 // pointer to a cfstring and returns its name or nullptr.
3084 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3085 struct DisassembleInfo *info) {
3086 const char *r, *name;
3087 uint32_t offset, left;
3089 struct cfstring64_t cfs;
3090 uint64_t cfs_characters;
3092 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3093 if (r == nullptr || left < sizeof(struct cfstring64_t))
3095 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3096 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3098 if (cfs.characters == 0) {
3100 const char *symbol_name = get_symbol_64(
3101 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3102 if (symbol_name == nullptr)
3104 cfs_characters = n_value;
3106 cfs_characters = cfs.characters;
3107 name = get_pointer_64(cfs_characters, offset, left, S, info);
3112 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
3113 // of a pointer to an Objective-C selector reference when the pointer value is
3114 // zero as in a .o file and is likely to have a external relocation entry with
3115 // who's symbol's n_value is the real pointer to the selector name. If that is
3116 // the case the real pointer to the selector name is returned else 0 is
3118 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3119 struct DisassembleInfo *info) {
3120 uint32_t offset, left;
3123 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3124 if (r == nullptr || left < sizeof(uint64_t))
3127 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3128 if (symbol_name == nullptr)
3133 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3134 const char *sectname) {
3135 for (const SectionRef &Section : O->sections()) {
3137 Section.getName(SectName);
3138 DataRefImpl Ref = Section.getRawDataRefImpl();
3139 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3140 if (SegName == segname && SectName == sectname)
3143 return SectionRef();
3147 walk_pointer_list_64(const char *listname, const SectionRef S,
3148 MachOObjectFile *O, struct DisassembleInfo *info,
3149 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3150 if (S == SectionRef())
3154 S.getName(SectName);
3155 DataRefImpl Ref = S.getRawDataRefImpl();
3156 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3157 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3160 S.getContents(BytesStr);
3161 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3163 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3164 uint32_t left = S.getSize() - i;
3165 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3167 memcpy(&p, Contents + i, size);
3168 if (i + sizeof(uint64_t) > S.getSize())
3169 outs() << listname << " list pointer extends past end of (" << SegName
3170 << "," << SectName << ") section\n";
3171 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3173 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3174 sys::swapByteOrder(p);
3176 uint64_t n_value = 0;
3177 const char *name = get_symbol_64(i, S, info, n_value, p);
3178 if (name == nullptr)
3179 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3182 outs() << format("0x%" PRIx64, n_value);
3184 outs() << " + " << format("0x%" PRIx64, p);
3186 outs() << format("0x%" PRIx64, p);
3187 if (name != nullptr)
3188 outs() << " " << name;
3198 walk_pointer_list_32(const char *listname, const SectionRef S,
3199 MachOObjectFile *O, struct DisassembleInfo *info,
3200 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3201 if (S == SectionRef())
3205 S.getName(SectName);
3206 DataRefImpl Ref = S.getRawDataRefImpl();
3207 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3208 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3211 S.getContents(BytesStr);
3212 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3214 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3215 uint32_t left = S.getSize() - i;
3216 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3218 memcpy(&p, Contents + i, size);
3219 if (i + sizeof(uint32_t) > S.getSize())
3220 outs() << listname << " list pointer extends past end of (" << SegName
3221 << "," << SectName << ") section\n";
3222 uint32_t Address = S.getAddress() + i;
3223 outs() << format("%08" PRIx32, Address) << " ";
3225 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3226 sys::swapByteOrder(p);
3227 outs() << format("0x%" PRIx32, p);
3229 const char *name = get_symbol_32(i, S, info, p);
3230 if (name != nullptr)
3231 outs() << " " << name;
3239 static void print_layout_map(const char *layout_map, uint32_t left) {
3240 if (layout_map == nullptr)
3242 outs() << " layout map: ";
3244 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3247 } while (*layout_map != '\0' && left != 0);
3251 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3252 uint32_t offset, left;
3254 const char *layout_map;
3258 layout_map = get_pointer_64(p, offset, left, S, info);
3259 print_layout_map(layout_map, left);
3262 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3263 uint32_t offset, left;
3265 const char *layout_map;
3269 layout_map = get_pointer_32(p, offset, left, S, info);
3270 print_layout_map(layout_map, left);
3273 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3274 const char *indent) {
3275 struct method_list64_t ml;
3276 struct method64_t m;
3278 uint32_t offset, xoffset, left, i;
3280 const char *name, *sym_name;
3283 r = get_pointer_64(p, offset, left, S, info);
3286 memset(&ml, '\0', sizeof(struct method_list64_t));
3287 if (left < sizeof(struct method_list64_t)) {
3288 memcpy(&ml, r, left);
3289 outs() << " (method_list_t entends past the end of the section)\n";
3291 memcpy(&ml, r, sizeof(struct method_list64_t));
3292 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3294 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3295 outs() << indent << "\t\t count " << ml.count << "\n";
3297 p += sizeof(struct method_list64_t);
3298 offset += sizeof(struct method_list64_t);
3299 for (i = 0; i < ml.count; i++) {
3300 r = get_pointer_64(p, offset, left, S, info);
3303 memset(&m, '\0', sizeof(struct method64_t));
3304 if (left < sizeof(struct method64_t)) {
3305 memcpy(&m, r, left);
3306 outs() << indent << " (method_t extends past the end of the section)\n";
3308 memcpy(&m, r, sizeof(struct method64_t));
3309 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3312 outs() << indent << "\t\t name ";
3313 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3314 info, n_value, m.name);
3316 if (info->verbose && sym_name != nullptr)
3319 outs() << format("0x%" PRIx64, n_value);
3321 outs() << " + " << format("0x%" PRIx64, m.name);
3323 outs() << format("0x%" PRIx64, m.name);
3324 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3325 if (name != nullptr)
3326 outs() << format(" %.*s", left, name);
3329 outs() << indent << "\t\t types ";
3330 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3331 info, n_value, m.types);
3333 if (info->verbose && sym_name != nullptr)
3336 outs() << format("0x%" PRIx64, n_value);
3338 outs() << " + " << format("0x%" PRIx64, m.types);
3340 outs() << format("0x%" PRIx64, m.types);
3341 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3342 if (name != nullptr)
3343 outs() << format(" %.*s", left, name);
3346 outs() << indent << "\t\t imp ";
3347 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3349 if (info->verbose && name == nullptr) {
3351 outs() << format("0x%" PRIx64, n_value) << " ";
3353 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3355 outs() << format("0x%" PRIx64, m.imp) << " ";
3357 if (name != nullptr)
3361 p += sizeof(struct method64_t);
3362 offset += sizeof(struct method64_t);
3366 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3367 const char *indent) {
3368 struct method_list32_t ml;
3369 struct method32_t m;
3370 const char *r, *name;
3371 uint32_t offset, xoffset, left, i;
3374 r = get_pointer_32(p, offset, left, S, info);
3377 memset(&ml, '\0', sizeof(struct method_list32_t));
3378 if (left < sizeof(struct method_list32_t)) {
3379 memcpy(&ml, r, left);
3380 outs() << " (method_list_t entends past the end of the section)\n";
3382 memcpy(&ml, r, sizeof(struct method_list32_t));
3383 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3385 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3386 outs() << indent << "\t\t count " << ml.count << "\n";
3388 p += sizeof(struct method_list32_t);
3389 offset += sizeof(struct method_list32_t);
3390 for (i = 0; i < ml.count; i++) {
3391 r = get_pointer_32(p, offset, left, S, info);
3394 memset(&m, '\0', sizeof(struct method32_t));
3395 if (left < sizeof(struct method32_t)) {
3396 memcpy(&ml, r, left);
3397 outs() << indent << " (method_t entends past the end of the section)\n";
3399 memcpy(&m, r, sizeof(struct method32_t));
3400 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3403 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3404 name = get_pointer_32(m.name, xoffset, left, xS, info);
3405 if (name != nullptr)
3406 outs() << format(" %.*s", left, name);
3409 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3410 name = get_pointer_32(m.types, xoffset, left, xS, info);
3411 if (name != nullptr)
3412 outs() << format(" %.*s", left, name);
3415 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3416 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3418 if (name != nullptr)
3419 outs() << " " << name;
3422 p += sizeof(struct method32_t);
3423 offset += sizeof(struct method32_t);
3427 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3428 uint32_t offset, left, xleft;
3430 struct objc_method_list_t method_list;
3431 struct objc_method_t method;
3432 const char *r, *methods, *name, *SymbolName;
3435 r = get_pointer_32(p, offset, left, S, info, true);
3440 if (left > sizeof(struct objc_method_list_t)) {
3441 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3443 outs() << "\t\t objc_method_list extends past end of the section\n";
3444 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3445 memcpy(&method_list, r, left);
3447 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3448 swapStruct(method_list);
3450 outs() << "\t\t obsolete "
3451 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3452 outs() << "\t\t method_count " << method_list.method_count << "\n";
3454 methods = r + sizeof(struct objc_method_list_t);
3455 for (i = 0; i < method_list.method_count; i++) {
3456 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3457 outs() << "\t\t remaining method's extend past the of the section\n";
3460 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3461 sizeof(struct objc_method_t));
3462 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3465 outs() << "\t\t method_name "
3466 << format("0x%08" PRIx32, method.method_name);
3467 if (info->verbose) {
3468 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3469 if (name != nullptr)
3470 outs() << format(" %.*s", xleft, name);
3472 outs() << " (not in an __OBJC section)";
3476 outs() << "\t\t method_types "
3477 << format("0x%08" PRIx32, method.method_types);
3478 if (info->verbose) {
3479 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3480 if (name != nullptr)
3481 outs() << format(" %.*s", xleft, name);
3483 outs() << " (not in an __OBJC section)";
3487 outs() << "\t\t method_imp "
3488 << format("0x%08" PRIx32, method.method_imp) << " ";
3489 if (info->verbose) {
3490 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3491 if (SymbolName != nullptr)
3492 outs() << SymbolName;
3499 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3500 struct protocol_list64_t pl;
3501 uint64_t q, n_value;
3502 struct protocol64_t pc;
3504 uint32_t offset, xoffset, left, i;
3506 const char *name, *sym_name;
3508 r = get_pointer_64(p, offset, left, S, info);
3511 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3512 if (left < sizeof(struct protocol_list64_t)) {
3513 memcpy(&pl, r, left);
3514 outs() << " (protocol_list_t entends past the end of the section)\n";
3516 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3517 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3519 outs() << " count " << pl.count << "\n";
3521 p += sizeof(struct protocol_list64_t);
3522 offset += sizeof(struct protocol_list64_t);
3523 for (i = 0; i < pl.count; i++) {
3524 r = get_pointer_64(p, offset, left, S, info);
3528 if (left < sizeof(uint64_t)) {
3529 memcpy(&q, r, left);
3530 outs() << " (protocol_t * entends past the end of the section)\n";
3532 memcpy(&q, r, sizeof(uint64_t));
3533 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3534 sys::swapByteOrder(q);
3536 outs() << "\t\t list[" << i << "] ";
3537 sym_name = get_symbol_64(offset, S, info, n_value, q);
3539 if (info->verbose && sym_name != nullptr)
3542 outs() << format("0x%" PRIx64, n_value);
3544 outs() << " + " << format("0x%" PRIx64, q);
3546 outs() << format("0x%" PRIx64, q);
3547 outs() << " (struct protocol_t *)\n";
3549 r = get_pointer_64(q + n_value, offset, left, S, info);
3552 memset(&pc, '\0', sizeof(struct protocol64_t));
3553 if (left < sizeof(struct protocol64_t)) {
3554 memcpy(&pc, r, left);
3555 outs() << " (protocol_t entends past the end of the section)\n";
3557 memcpy(&pc, r, sizeof(struct protocol64_t));
3558 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3561 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3563 outs() << "\t\t\t name ";
3564 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3565 info, n_value, pc.name);
3567 if (info->verbose && sym_name != nullptr)
3570 outs() << format("0x%" PRIx64, n_value);
3572 outs() << " + " << format("0x%" PRIx64, pc.name);
3574 outs() << format("0x%" PRIx64, pc.name);
3575 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3576 if (name != nullptr)
3577 outs() << format(" %.*s", left, name);
3580 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3582 outs() << "\t\t instanceMethods ";
3584 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3585 S, info, n_value, pc.instanceMethods);
3587 if (info->verbose && sym_name != nullptr)
3590 outs() << format("0x%" PRIx64, n_value);
3591 if (pc.instanceMethods != 0)
3592 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3594 outs() << format("0x%" PRIx64, pc.instanceMethods);
3595 outs() << " (struct method_list_t *)\n";
3596 if (pc.instanceMethods + n_value != 0)
3597 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3599 outs() << "\t\t classMethods ";
3601 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3602 info, n_value, pc.classMethods);
3604 if (info->verbose && sym_name != nullptr)
3607 outs() << format("0x%" PRIx64, n_value);
3608 if (pc.classMethods != 0)
3609 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3611 outs() << format("0x%" PRIx64, pc.classMethods);
3612 outs() << " (struct method_list_t *)\n";
3613 if (pc.classMethods + n_value != 0)
3614 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3616 outs() << "\t optionalInstanceMethods "
3617 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3618 outs() << "\t optionalClassMethods "
3619 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3620 outs() << "\t instanceProperties "
3621 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3623 p += sizeof(uint64_t);
3624 offset += sizeof(uint64_t);
3628 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3629 struct protocol_list32_t pl;
3631 struct protocol32_t pc;
3633 uint32_t offset, xoffset, left, i;
3637 r = get_pointer_32(p, offset, left, S, info);
3640 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3641 if (left < sizeof(struct protocol_list32_t)) {
3642 memcpy(&pl, r, left);
3643 outs() << " (protocol_list_t entends past the end of the section)\n";
3645 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3646 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3648 outs() << " count " << pl.count << "\n";
3650 p += sizeof(struct protocol_list32_t);
3651 offset += sizeof(struct protocol_list32_t);
3652 for (i = 0; i < pl.count; i++) {
3653 r = get_pointer_32(p, offset, left, S, info);
3657 if (left < sizeof(uint32_t)) {
3658 memcpy(&q, r, left);
3659 outs() << " (protocol_t * entends past the end of the section)\n";
3661 memcpy(&q, r, sizeof(uint32_t));
3662 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3663 sys::swapByteOrder(q);
3664 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3665 << " (struct protocol_t *)\n";
3666 r = get_pointer_32(q, offset, left, S, info);
3669 memset(&pc, '\0', sizeof(struct protocol32_t));
3670 if (left < sizeof(struct protocol32_t)) {
3671 memcpy(&pc, r, left);
3672 outs() << " (protocol_t entends past the end of the section)\n";
3674 memcpy(&pc, r, sizeof(struct protocol32_t));
3675 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3677 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3678 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3679 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3680 if (name != nullptr)
3681 outs() << format(" %.*s", left, name);
3683 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3684 outs() << "\t\t instanceMethods "
3685 << format("0x%" PRIx32, pc.instanceMethods)
3686 << " (struct method_list_t *)\n";
3687 if (pc.instanceMethods != 0)
3688 print_method_list32_t(pc.instanceMethods, info, "\t");
3689 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3690 << " (struct method_list_t *)\n";
3691 if (pc.classMethods != 0)
3692 print_method_list32_t(pc.classMethods, info, "\t");
3693 outs() << "\t optionalInstanceMethods "
3694 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3695 outs() << "\t optionalClassMethods "
3696 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3697 outs() << "\t instanceProperties "
3698 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3699 p += sizeof(uint32_t);
3700 offset += sizeof(uint32_t);
3704 static void print_indent(uint32_t indent) {
3705 for (uint32_t i = 0; i < indent;) {
3706 if (indent - i >= 8) {
3710 for (uint32_t j = i; j < indent; j++)
3717 static bool print_method_description_list(uint32_t p, uint32_t indent,
3718 struct DisassembleInfo *info) {
3719 uint32_t offset, left, xleft;
3721 struct objc_method_description_list_t mdl;
3722 struct objc_method_description_t md;
3723 const char *r, *list, *name;
3726 r = get_pointer_32(p, offset, left, S, info, true);
3731 if (left > sizeof(struct objc_method_description_list_t)) {
3732 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3734 print_indent(indent);
3735 outs() << " objc_method_description_list extends past end of the section\n";
3736 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3737 memcpy(&mdl, r, left);
3739 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3742 print_indent(indent);
3743 outs() << " count " << mdl.count << "\n";
3745 list = r + sizeof(struct objc_method_description_list_t);
3746 for (i = 0; i < mdl.count; i++) {
3747 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3748 print_indent(indent);
3749 outs() << " remaining list entries extend past the of the section\n";
3752 print_indent(indent);
3753 outs() << " list[" << i << "]\n";
3754 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3755 sizeof(struct objc_method_description_t));
3756 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3759 print_indent(indent);
3760 outs() << " name " << format("0x%08" PRIx32, md.name);
3761 if (info->verbose) {
3762 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3763 if (name != nullptr)
3764 outs() << format(" %.*s", xleft, name);
3766 outs() << " (not in an __OBJC section)";
3770 print_indent(indent);
3771 outs() << " types " << format("0x%08" PRIx32, md.types);
3772 if (info->verbose) {
3773 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3774 if (name != nullptr)
3775 outs() << format(" %.*s", xleft, name);
3777 outs() << " (not in an __OBJC section)";
3784 static bool print_protocol_list(uint32_t p, uint32_t indent,
3785 struct DisassembleInfo *info);
3787 static bool print_protocol(uint32_t p, uint32_t indent,
3788 struct DisassembleInfo *info) {
3789 uint32_t offset, left;
3791 struct objc_protocol_t protocol;
3792 const char *r, *name;
3794 r = get_pointer_32(p, offset, left, S, info, true);
3799 if (left >= sizeof(struct objc_protocol_t)) {
3800 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3802 print_indent(indent);
3803 outs() << " Protocol extends past end of the section\n";
3804 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3805 memcpy(&protocol, r, left);
3807 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3808 swapStruct(protocol);
3810 print_indent(indent);
3811 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3814 print_indent(indent);
3815 outs() << " protocol_name "
3816 << format("0x%08" PRIx32, protocol.protocol_name);
3817 if (info->verbose) {
3818 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3819 if (name != nullptr)
3820 outs() << format(" %.*s", left, name);
3822 outs() << " (not in an __OBJC section)";
3826 print_indent(indent);
3827 outs() << " protocol_list "
3828 << format("0x%08" PRIx32, protocol.protocol_list);
3829 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3830 outs() << " (not in an __OBJC section)\n";
3832 print_indent(indent);
3833 outs() << " instance_methods "
3834 << format("0x%08" PRIx32, protocol.instance_methods);
3835 if (print_method_description_list(protocol.instance_methods, indent, info))
3836 outs() << " (not in an __OBJC section)\n";
3838 print_indent(indent);
3839 outs() << " class_methods "
3840 << format("0x%08" PRIx32, protocol.class_methods);
3841 if (print_method_description_list(protocol.class_methods, indent, info))
3842 outs() << " (not in an __OBJC section)\n";
3847 static bool print_protocol_list(uint32_t p, uint32_t indent,
3848 struct DisassembleInfo *info) {
3849 uint32_t offset, left, l;
3851 struct objc_protocol_list_t protocol_list;
3852 const char *r, *list;
3855 r = get_pointer_32(p, offset, left, S, info, true);
3860 if (left > sizeof(struct objc_protocol_list_t)) {
3861 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3863 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3864 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3865 memcpy(&protocol_list, r, left);
3867 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3868 swapStruct(protocol_list);
3870 print_indent(indent);
3871 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3873 print_indent(indent);
3874 outs() << " count " << protocol_list.count << "\n";
3876 list = r + sizeof(struct objc_protocol_list_t);
3877 for (i = 0; i < protocol_list.count; i++) {
3878 if ((i + 1) * sizeof(uint32_t) > left) {
3879 outs() << "\t\t remaining list entries extend past the of the section\n";
3882 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3883 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3884 sys::swapByteOrder(l);
3886 print_indent(indent);
3887 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3888 if (print_protocol(l, indent, info))
3889 outs() << "(not in an __OBJC section)\n";
3894 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3895 struct ivar_list64_t il;
3898 uint32_t offset, xoffset, left, j;
3900 const char *name, *sym_name, *ivar_offset_p;
3901 uint64_t ivar_offset, n_value;
3903 r = get_pointer_64(p, offset, left, S, info);
3906 memset(&il, '\0', sizeof(struct ivar_list64_t));
3907 if (left < sizeof(struct ivar_list64_t)) {
3908 memcpy(&il, r, left);
3909 outs() << " (ivar_list_t entends past the end of the section)\n";
3911 memcpy(&il, r, sizeof(struct ivar_list64_t));
3912 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3914 outs() << " entsize " << il.entsize << "\n";
3915 outs() << " count " << il.count << "\n";
3917 p += sizeof(struct ivar_list64_t);
3918 offset += sizeof(struct ivar_list64_t);
3919 for (j = 0; j < il.count; j++) {
3920 r = get_pointer_64(p, offset, left, S, info);
3923 memset(&i, '\0', sizeof(struct ivar64_t));
3924 if (left < sizeof(struct ivar64_t)) {
3925 memcpy(&i, r, left);
3926 outs() << " (ivar_t entends past the end of the section)\n";
3928 memcpy(&i, r, sizeof(struct ivar64_t));
3929 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3932 outs() << "\t\t\t offset ";
3933 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3934 info, n_value, i.offset);
3936 if (info->verbose && sym_name != nullptr)
3939 outs() << format("0x%" PRIx64, n_value);
3941 outs() << " + " << format("0x%" PRIx64, i.offset);
3943 outs() << format("0x%" PRIx64, i.offset);
3944 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3945 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3946 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3947 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3948 sys::swapByteOrder(ivar_offset);
3949 outs() << " " << ivar_offset << "\n";
3953 outs() << "\t\t\t name ";
3954 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
3957 if (info->verbose && sym_name != nullptr)
3960 outs() << format("0x%" PRIx64, n_value);
3962 outs() << " + " << format("0x%" PRIx64, i.name);
3964 outs() << format("0x%" PRIx64, i.name);
3965 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
3966 if (name != nullptr)
3967 outs() << format(" %.*s", left, name);
3970 outs() << "\t\t\t type ";
3971 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
3973 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
3975 if (info->verbose && sym_name != nullptr)
3978 outs() << format("0x%" PRIx64, n_value);
3980 outs() << " + " << format("0x%" PRIx64, i.type);
3982 outs() << format("0x%" PRIx64, i.type);
3983 if (name != nullptr)
3984 outs() << format(" %.*s", left, name);
3987 outs() << "\t\t\talignment " << i.alignment << "\n";
3988 outs() << "\t\t\t size " << i.size << "\n";
3990 p += sizeof(struct ivar64_t);
3991 offset += sizeof(struct ivar64_t);
3995 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
3996 struct ivar_list32_t il;
3999 uint32_t offset, xoffset, left, j;
4001 const char *name, *ivar_offset_p;
4002 uint32_t ivar_offset;
4004 r = get_pointer_32(p, offset, left, S, info);
4007 memset(&il, '\0', sizeof(struct ivar_list32_t));
4008 if (left < sizeof(struct ivar_list32_t)) {
4009 memcpy(&il, r, left);
4010 outs() << " (ivar_list_t entends past the end of the section)\n";
4012 memcpy(&il, r, sizeof(struct ivar_list32_t));
4013 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4015 outs() << " entsize " << il.entsize << "\n";
4016 outs() << " count " << il.count << "\n";
4018 p += sizeof(struct ivar_list32_t);
4019 offset += sizeof(struct ivar_list32_t);
4020 for (j = 0; j < il.count; j++) {
4021 r = get_pointer_32(p, offset, left, S, info);
4024 memset(&i, '\0', sizeof(struct ivar32_t));
4025 if (left < sizeof(struct ivar32_t)) {
4026 memcpy(&i, r, left);
4027 outs() << " (ivar_t entends past the end of the section)\n";
4029 memcpy(&i, r, sizeof(struct ivar32_t));
4030 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4033 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4034 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4035 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4036 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4037 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4038 sys::swapByteOrder(ivar_offset);
4039 outs() << " " << ivar_offset << "\n";
4043 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4044 name = get_pointer_32(i.name, xoffset, left, xS, info);
4045 if (name != nullptr)
4046 outs() << format(" %.*s", left, name);
4049 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4050 name = get_pointer_32(i.type, xoffset, left, xS, info);
4051 if (name != nullptr)
4052 outs() << format(" %.*s", left, name);
4055 outs() << "\t\t\talignment " << i.alignment << "\n";
4056 outs() << "\t\t\t size " << i.size << "\n";
4058 p += sizeof(struct ivar32_t);
4059 offset += sizeof(struct ivar32_t);
4063 static void print_objc_property_list64(uint64_t p,
4064 struct DisassembleInfo *info) {
4065 struct objc_property_list64 opl;
4066 struct objc_property64 op;
4068 uint32_t offset, xoffset, left, j;
4070 const char *name, *sym_name;
4073 r = get_pointer_64(p, offset, left, S, info);
4076 memset(&opl, '\0', sizeof(struct objc_property_list64));
4077 if (left < sizeof(struct objc_property_list64)) {
4078 memcpy(&opl, r, left);
4079 outs() << " (objc_property_list entends past the end of the section)\n";
4081 memcpy(&opl, r, sizeof(struct objc_property_list64));
4082 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4084 outs() << " entsize " << opl.entsize << "\n";
4085 outs() << " count " << opl.count << "\n";
4087 p += sizeof(struct objc_property_list64);
4088 offset += sizeof(struct objc_property_list64);
4089 for (j = 0; j < opl.count; j++) {
4090 r = get_pointer_64(p, offset, left, S, info);
4093 memset(&op, '\0', sizeof(struct objc_property64));
4094 if (left < sizeof(struct objc_property64)) {
4095 memcpy(&op, r, left);
4096 outs() << " (objc_property entends past the end of the section)\n";
4098 memcpy(&op, r, sizeof(struct objc_property64));
4099 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4102 outs() << "\t\t\t name ";
4103 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4104 info, n_value, op.name);
4106 if (info->verbose && sym_name != nullptr)
4109 outs() << format("0x%" PRIx64, n_value);
4111 outs() << " + " << format("0x%" PRIx64, op.name);
4113 outs() << format("0x%" PRIx64, op.name);
4114 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4115 if (name != nullptr)
4116 outs() << format(" %.*s", left, name);
4119 outs() << "\t\t\tattributes ";
4121 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4122 info, n_value, op.attributes);
4124 if (info->verbose && sym_name != nullptr)
4127 outs() << format("0x%" PRIx64, n_value);
4128 if (op.attributes != 0)
4129 outs() << " + " << format("0x%" PRIx64, op.attributes);
4131 outs() << format("0x%" PRIx64, op.attributes);
4132 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4133 if (name != nullptr)
4134 outs() << format(" %.*s", left, name);
4137 p += sizeof(struct objc_property64);
4138 offset += sizeof(struct objc_property64);
4142 static void print_objc_property_list32(uint32_t p,
4143 struct DisassembleInfo *info) {
4144 struct objc_property_list32 opl;
4145 struct objc_property32 op;
4147 uint32_t offset, xoffset, left, j;
4151 r = get_pointer_32(p, offset, left, S, info);
4154 memset(&opl, '\0', sizeof(struct objc_property_list32));
4155 if (left < sizeof(struct objc_property_list32)) {
4156 memcpy(&opl, r, left);
4157 outs() << " (objc_property_list entends past the end of the section)\n";
4159 memcpy(&opl, r, sizeof(struct objc_property_list32));
4160 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4162 outs() << " entsize " << opl.entsize << "\n";
4163 outs() << " count " << opl.count << "\n";
4165 p += sizeof(struct objc_property_list32);
4166 offset += sizeof(struct objc_property_list32);
4167 for (j = 0; j < opl.count; j++) {
4168 r = get_pointer_32(p, offset, left, S, info);
4171 memset(&op, '\0', sizeof(struct objc_property32));
4172 if (left < sizeof(struct objc_property32)) {
4173 memcpy(&op, r, left);
4174 outs() << " (objc_property entends past the end of the section)\n";
4176 memcpy(&op, r, sizeof(struct objc_property32));
4177 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4180 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4181 name = get_pointer_32(op.name, xoffset, left, xS, info);
4182 if (name != nullptr)
4183 outs() << format(" %.*s", left, name);
4186 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4187 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4188 if (name != nullptr)
4189 outs() << format(" %.*s", left, name);
4192 p += sizeof(struct objc_property32);
4193 offset += sizeof(struct objc_property32);
4197 static void print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
4198 bool &is_meta_class) {
4199 struct class_ro64_t cro;
4201 uint32_t offset, xoffset, left;
4203 const char *name, *sym_name;
4206 r = get_pointer_64(p, offset, left, S, info);
4207 if (r == nullptr || left < sizeof(struct class_ro64_t))
4209 memset(&cro, '\0', sizeof(struct class_ro64_t));
4210 if (left < sizeof(struct class_ro64_t)) {
4211 memcpy(&cro, r, left);
4212 outs() << " (class_ro_t entends past the end of the section)\n";
4214 memcpy(&cro, r, sizeof(struct class_ro64_t));
4215 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4217 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4218 if (cro.flags & RO_META)
4219 outs() << " RO_META";
4220 if (cro.flags & RO_ROOT)
4221 outs() << " RO_ROOT";
4222 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4223 outs() << " RO_HAS_CXX_STRUCTORS";
4225 outs() << " instanceStart " << cro.instanceStart << "\n";
4226 outs() << " instanceSize " << cro.instanceSize << "\n";
4227 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4229 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4231 print_layout_map64(cro.ivarLayout, info);
4234 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4235 info, n_value, cro.name);
4237 if (info->verbose && sym_name != nullptr)
4240 outs() << format("0x%" PRIx64, n_value);
4242 outs() << " + " << format("0x%" PRIx64, cro.name);
4244 outs() << format("0x%" PRIx64, cro.name);
4245 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4246 if (name != nullptr)
4247 outs() << format(" %.*s", left, name);
4250 outs() << " baseMethods ";
4251 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4252 S, info, n_value, cro.baseMethods);
4254 if (info->verbose && sym_name != nullptr)
4257 outs() << format("0x%" PRIx64, n_value);
4258 if (cro.baseMethods != 0)
4259 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4261 outs() << format("0x%" PRIx64, cro.baseMethods);
4262 outs() << " (struct method_list_t *)\n";
4263 if (cro.baseMethods + n_value != 0)
4264 print_method_list64_t(cro.baseMethods + n_value, info, "");
4266 outs() << " baseProtocols ";
4268 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4269 info, n_value, cro.baseProtocols);
4271 if (info->verbose && sym_name != nullptr)
4274 outs() << format("0x%" PRIx64, n_value);
4275 if (cro.baseProtocols != 0)
4276 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4278 outs() << format("0x%" PRIx64, cro.baseProtocols);
4280 if (cro.baseProtocols + n_value != 0)
4281 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4283 outs() << " ivars ";
4284 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
4285 info, n_value, cro.ivars);
4287 if (info->verbose && sym_name != nullptr)
4290 outs() << format("0x%" PRIx64, n_value);
4292 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4294 outs() << format("0x%" PRIx64, cro.ivars);
4296 if (cro.ivars + n_value != 0)
4297 print_ivar_list64_t(cro.ivars + n_value, info);
4299 outs() << " weakIvarLayout ";
4301 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4302 info, n_value, cro.weakIvarLayout);
4304 if (info->verbose && sym_name != nullptr)
4307 outs() << format("0x%" PRIx64, n_value);
4308 if (cro.weakIvarLayout != 0)
4309 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4311 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4313 print_layout_map64(cro.weakIvarLayout + n_value, info);
4315 outs() << " baseProperties ";
4317 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4318 info, n_value, cro.baseProperties);
4320 if (info->verbose && sym_name != nullptr)
4323 outs() << format("0x%" PRIx64, n_value);
4324 if (cro.baseProperties != 0)
4325 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4327 outs() << format("0x%" PRIx64, cro.baseProperties);
4329 if (cro.baseProperties + n_value != 0)
4330 print_objc_property_list64(cro.baseProperties + n_value, info);
4332 is_meta_class = (cro.flags & RO_META) ? true : false;
4335 static void print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
4336 bool &is_meta_class) {
4337 struct class_ro32_t cro;
4339 uint32_t offset, xoffset, left;
4343 r = get_pointer_32(p, offset, left, S, info);
4346 memset(&cro, '\0', sizeof(struct class_ro32_t));
4347 if (left < sizeof(struct class_ro32_t)) {
4348 memcpy(&cro, r, left);
4349 outs() << " (class_ro_t entends past the end of the section)\n";
4351 memcpy(&cro, r, sizeof(struct class_ro32_t));
4352 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4354 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4355 if (cro.flags & RO_META)
4356 outs() << " RO_META";
4357 if (cro.flags & RO_ROOT)
4358 outs() << " RO_ROOT";
4359 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4360 outs() << " RO_HAS_CXX_STRUCTORS";
4362 outs() << " instanceStart " << cro.instanceStart << "\n";
4363 outs() << " instanceSize " << cro.instanceSize << "\n";
4364 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4366 print_layout_map32(cro.ivarLayout, info);
4368 outs() << " name " << format("0x%" PRIx32, cro.name);
4369 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4370 if (name != nullptr)
4371 outs() << format(" %.*s", left, name);
4374 outs() << " baseMethods "
4375 << format("0x%" PRIx32, cro.baseMethods)
4376 << " (struct method_list_t *)\n";
4377 if (cro.baseMethods != 0)
4378 print_method_list32_t(cro.baseMethods, info, "");
4380 outs() << " baseProtocols "
4381 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4382 if (cro.baseProtocols != 0)
4383 print_protocol_list32_t(cro.baseProtocols, info);
4384 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4387 print_ivar_list32_t(cro.ivars, info);
4388 outs() << " weakIvarLayout "
4389 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4390 print_layout_map32(cro.weakIvarLayout, info);
4391 outs() << " baseProperties "
4392 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4393 if (cro.baseProperties != 0)
4394 print_objc_property_list32(cro.baseProperties, info);
4395 is_meta_class = (cro.flags & RO_META) ? true : false;
4398 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4401 uint32_t offset, left;
4404 uint64_t isa_n_value, n_value;
4406 r = get_pointer_64(p, offset, left, S, info);
4407 if (r == nullptr || left < sizeof(struct class64_t))
4409 memset(&c, '\0', sizeof(struct class64_t));
4410 if (left < sizeof(struct class64_t)) {
4411 memcpy(&c, r, left);
4412 outs() << " (class_t entends past the end of the section)\n";
4414 memcpy(&c, r, sizeof(struct class64_t));
4415 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4418 outs() << " isa " << format("0x%" PRIx64, c.isa);
4419 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4420 isa_n_value, c.isa);
4421 if (name != nullptr)
4422 outs() << " " << name;
4425 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4426 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4427 n_value, c.superclass);
4428 if (name != nullptr)
4429 outs() << " " << name;
4432 outs() << " cache " << format("0x%" PRIx64, c.cache);
4433 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4435 if (name != nullptr)
4436 outs() << " " << name;
4439 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4440 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4442 if (name != nullptr)
4443 outs() << " " << name;
4446 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4450 if (info->verbose && name != nullptr)
4453 outs() << format("0x%" PRIx64, n_value);
4455 outs() << " + " << format("0x%" PRIx64, c.data);
4457 outs() << format("0x%" PRIx64, c.data);
4458 outs() << " (struct class_ro_t *)";
4460 // This is a Swift class if some of the low bits of the pointer are set.
4461 if ((c.data + n_value) & 0x7)
4462 outs() << " Swift class";
4465 print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class);
4467 if (!is_meta_class &&
4468 c.isa + isa_n_value != p &&
4469 c.isa + isa_n_value != 0 &&
4470 info->depth < 100) {
4472 outs() << "Meta Class\n";
4473 print_class64_t(c.isa + isa_n_value, info);
4477 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4480 uint32_t offset, left;
4484 r = get_pointer_32(p, offset, left, S, info);
4487 memset(&c, '\0', sizeof(struct class32_t));
4488 if (left < sizeof(struct class32_t)) {
4489 memcpy(&c, r, left);
4490 outs() << " (class_t entends past the end of the section)\n";
4492 memcpy(&c, r, sizeof(struct class32_t));
4493 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4496 outs() << " isa " << format("0x%" PRIx32, c.isa);
4498 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4499 if (name != nullptr)
4500 outs() << " " << name;
4503 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4504 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4506 if (name != nullptr)
4507 outs() << " " << name;
4510 outs() << " cache " << format("0x%" PRIx32, c.cache);
4511 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4513 if (name != nullptr)
4514 outs() << " " << name;
4517 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4518 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4520 if (name != nullptr)
4521 outs() << " " << name;
4525 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4526 outs() << " data " << format("0x%" PRIx32, c.data)
4527 << " (struct class_ro_t *)";
4529 // This is a Swift class if some of the low bits of the pointer are set.
4531 outs() << " Swift class";
4534 print_class_ro32_t(c.data & ~0x3, info, is_meta_class);
4536 if (!is_meta_class) {
4537 outs() << "Meta Class\n";
4538 print_class32_t(c.isa, info);
4542 static void print_objc_class_t(struct objc_class_t *objc_class,
4543 struct DisassembleInfo *info) {
4544 uint32_t offset, left, xleft;
4545 const char *name, *p, *ivar_list;
4548 struct objc_ivar_list_t objc_ivar_list;
4549 struct objc_ivar_t ivar;
4551 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4552 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4553 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4554 if (name != nullptr)
4555 outs() << format(" %.*s", left, name);
4557 outs() << " (not in an __OBJC section)";
4561 outs() << "\t super_class "
4562 << format("0x%08" PRIx32, objc_class->super_class);
4563 if (info->verbose) {
4564 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4565 if (name != nullptr)
4566 outs() << format(" %.*s", left, name);
4568 outs() << " (not in an __OBJC section)";
4572 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4573 if (info->verbose) {
4574 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4575 if (name != nullptr)
4576 outs() << format(" %.*s", left, name);
4578 outs() << " (not in an __OBJC section)";
4582 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4585 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4586 if (info->verbose) {
4587 if (CLS_GETINFO(objc_class, CLS_CLASS))
4588 outs() << " CLS_CLASS";
4589 else if (CLS_GETINFO(objc_class, CLS_META))
4590 outs() << " CLS_META";
4594 outs() << "\t instance_size "
4595 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4597 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4598 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4600 if (left > sizeof(struct objc_ivar_list_t)) {
4602 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4604 outs() << " (entends past the end of the section)\n";
4605 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4606 memcpy(&objc_ivar_list, p, left);
4608 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4609 swapStruct(objc_ivar_list);
4610 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4611 ivar_list = p + sizeof(struct objc_ivar_list_t);
4612 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4613 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4614 outs() << "\t\t remaining ivar's extend past the of the section\n";
4617 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4618 sizeof(struct objc_ivar_t));
4619 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4622 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4623 if (info->verbose) {
4624 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4625 if (name != nullptr)
4626 outs() << format(" %.*s", xleft, name);
4628 outs() << " (not in an __OBJC section)";
4632 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4633 if (info->verbose) {
4634 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4635 if (name != nullptr)
4636 outs() << format(" %.*s", xleft, name);
4638 outs() << " (not in an __OBJC section)";
4642 outs() << "\t\t ivar_offset "
4643 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4646 outs() << " (not in an __OBJC section)\n";
4649 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4650 if (print_method_list(objc_class->methodLists, info))
4651 outs() << " (not in an __OBJC section)\n";
4653 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4656 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4657 if (print_protocol_list(objc_class->protocols, 16, info))
4658 outs() << " (not in an __OBJC section)\n";
4661 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4662 struct DisassembleInfo *info) {
4663 uint32_t offset, left;
4667 outs() << "\t category name "
4668 << format("0x%08" PRIx32, objc_category->category_name);
4669 if (info->verbose) {
4670 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4672 if (name != nullptr)
4673 outs() << format(" %.*s", left, name);
4675 outs() << " (not in an __OBJC section)";
4679 outs() << "\t\t class name "
4680 << format("0x%08" PRIx32, objc_category->class_name);
4681 if (info->verbose) {
4683 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4684 if (name != nullptr)
4685 outs() << format(" %.*s", left, name);
4687 outs() << " (not in an __OBJC section)";
4691 outs() << "\t instance methods "
4692 << format("0x%08" PRIx32, objc_category->instance_methods);
4693 if (print_method_list(objc_category->instance_methods, info))
4694 outs() << " (not in an __OBJC section)\n";
4696 outs() << "\t class methods "
4697 << format("0x%08" PRIx32, objc_category->class_methods);
4698 if (print_method_list(objc_category->class_methods, info))
4699 outs() << " (not in an __OBJC section)\n";
4702 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4703 struct category64_t c;
4705 uint32_t offset, xoffset, left;
4707 const char *name, *sym_name;
4710 r = get_pointer_64(p, offset, left, S, info);
4713 memset(&c, '\0', sizeof(struct category64_t));
4714 if (left < sizeof(struct category64_t)) {
4715 memcpy(&c, r, left);
4716 outs() << " (category_t entends past the end of the section)\n";
4718 memcpy(&c, r, sizeof(struct category64_t));
4719 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4723 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4724 info, n_value, c.name);
4726 if (info->verbose && sym_name != nullptr)
4729 outs() << format("0x%" PRIx64, n_value);
4731 outs() << " + " << format("0x%" PRIx64, c.name);
4733 outs() << format("0x%" PRIx64, c.name);
4734 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4735 if (name != nullptr)
4736 outs() << format(" %.*s", left, name);
4740 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4743 if (info->verbose && sym_name != nullptr)
4746 outs() << format("0x%" PRIx64, n_value);
4748 outs() << " + " << format("0x%" PRIx64, c.cls);
4750 outs() << format("0x%" PRIx64, c.cls);
4752 if (c.cls + n_value != 0)
4753 print_class64_t(c.cls + n_value, info);
4755 outs() << " instanceMethods ";
4757 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4758 info, n_value, c.instanceMethods);
4760 if (info->verbose && sym_name != nullptr)
4763 outs() << format("0x%" PRIx64, n_value);
4764 if (c.instanceMethods != 0)
4765 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4767 outs() << format("0x%" PRIx64, c.instanceMethods);
4769 if (c.instanceMethods + n_value != 0)
4770 print_method_list64_t(c.instanceMethods + n_value, info, "");
4772 outs() << " classMethods ";
4773 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4774 S, info, n_value, c.classMethods);
4776 if (info->verbose && sym_name != nullptr)
4779 outs() << format("0x%" PRIx64, n_value);
4780 if (c.classMethods != 0)
4781 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4783 outs() << format("0x%" PRIx64, c.classMethods);
4785 if (c.classMethods + n_value != 0)
4786 print_method_list64_t(c.classMethods + n_value, info, "");
4788 outs() << " protocols ";
4789 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4790 info, n_value, c.protocols);
4792 if (info->verbose && sym_name != nullptr)
4795 outs() << format("0x%" PRIx64, n_value);
4796 if (c.protocols != 0)
4797 outs() << " + " << format("0x%" PRIx64, c.protocols);
4799 outs() << format("0x%" PRIx64, c.protocols);
4801 if (c.protocols + n_value != 0)
4802 print_protocol_list64_t(c.protocols + n_value, info);
4804 outs() << "instanceProperties ";
4806 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4807 S, info, n_value, c.instanceProperties);
4809 if (info->verbose && sym_name != nullptr)
4812 outs() << format("0x%" PRIx64, n_value);
4813 if (c.instanceProperties != 0)
4814 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4816 outs() << format("0x%" PRIx64, c.instanceProperties);
4818 if (c.instanceProperties + n_value != 0)
4819 print_objc_property_list64(c.instanceProperties + n_value, info);
4822 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4823 struct category32_t c;
4825 uint32_t offset, left;
4829 r = get_pointer_32(p, offset, left, S, info);
4832 memset(&c, '\0', sizeof(struct category32_t));
4833 if (left < sizeof(struct category32_t)) {
4834 memcpy(&c, r, left);
4835 outs() << " (category_t entends past the end of the section)\n";
4837 memcpy(&c, r, sizeof(struct category32_t));
4838 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4841 outs() << " name " << format("0x%" PRIx32, c.name);
4842 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4845 outs() << " " << name;
4848 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4850 print_class32_t(c.cls, info);
4851 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4853 if (c.instanceMethods != 0)
4854 print_method_list32_t(c.instanceMethods, info, "");
4855 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4857 if (c.classMethods != 0)
4858 print_method_list32_t(c.classMethods, info, "");
4859 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4860 if (c.protocols != 0)
4861 print_protocol_list32_t(c.protocols, info);
4862 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4864 if (c.instanceProperties != 0)
4865 print_objc_property_list32(c.instanceProperties, info);
4868 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4869 uint32_t i, left, offset, xoffset;
4870 uint64_t p, n_value;
4871 struct message_ref64 mr;
4872 const char *name, *sym_name;
4876 if (S == SectionRef())
4880 S.getName(SectName);
4881 DataRefImpl Ref = S.getRawDataRefImpl();
4882 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4883 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4885 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4886 p = S.getAddress() + i;
4887 r = get_pointer_64(p, offset, left, S, info);
4890 memset(&mr, '\0', sizeof(struct message_ref64));
4891 if (left < sizeof(struct message_ref64)) {
4892 memcpy(&mr, r, left);
4893 outs() << " (message_ref entends past the end of the section)\n";
4895 memcpy(&mr, r, sizeof(struct message_ref64));
4896 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4900 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4903 outs() << format("0x%" PRIx64, n_value) << " ";
4905 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4907 outs() << format("0x%" PRIx64, mr.imp) << " ";
4908 if (name != nullptr)
4909 outs() << " " << name;
4913 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4914 info, n_value, mr.sel);
4916 if (info->verbose && sym_name != nullptr)
4919 outs() << format("0x%" PRIx64, n_value);
4921 outs() << " + " << format("0x%" PRIx64, mr.sel);
4923 outs() << format("0x%" PRIx64, mr.sel);
4924 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4925 if (name != nullptr)
4926 outs() << format(" %.*s", left, name);
4929 offset += sizeof(struct message_ref64);
4933 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
4934 uint32_t i, left, offset, xoffset, p;
4935 struct message_ref32 mr;
4936 const char *name, *r;
4939 if (S == SectionRef())
4943 S.getName(SectName);
4944 DataRefImpl Ref = S.getRawDataRefImpl();
4945 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4946 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4948 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4949 p = S.getAddress() + i;
4950 r = get_pointer_32(p, offset, left, S, info);
4953 memset(&mr, '\0', sizeof(struct message_ref32));
4954 if (left < sizeof(struct message_ref32)) {
4955 memcpy(&mr, r, left);
4956 outs() << " (message_ref entends past the end of the section)\n";
4958 memcpy(&mr, r, sizeof(struct message_ref32));
4959 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4962 outs() << " imp " << format("0x%" PRIx32, mr.imp);
4963 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
4965 if (name != nullptr)
4966 outs() << " " << name;
4969 outs() << " sel " << format("0x%" PRIx32, mr.sel);
4970 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
4971 if (name != nullptr)
4972 outs() << " " << name;
4975 offset += sizeof(struct message_ref32);
4979 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
4980 uint32_t left, offset, swift_version;
4982 struct objc_image_info64 o;
4986 S.getName(SectName);
4987 DataRefImpl Ref = S.getRawDataRefImpl();
4988 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4989 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4991 r = get_pointer_64(p, offset, left, S, info);
4994 memset(&o, '\0', sizeof(struct objc_image_info64));
4995 if (left < sizeof(struct objc_image_info64)) {
4996 memcpy(&o, r, left);
4997 outs() << " (objc_image_info entends past the end of the section)\n";
4999 memcpy(&o, r, sizeof(struct objc_image_info64));
5000 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5002 outs() << " version " << o.version << "\n";
5003 outs() << " flags " << format("0x%" PRIx32, o.flags);
5004 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5005 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5006 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5007 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5008 swift_version = (o.flags >> 8) & 0xff;
5009 if (swift_version != 0) {
5010 if (swift_version == 1)
5011 outs() << " Swift 1.0";
5012 else if (swift_version == 2)
5013 outs() << " Swift 1.1";
5015 outs() << " unknown future Swift version (" << swift_version << ")";
5020 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5021 uint32_t left, offset, swift_version, p;
5022 struct objc_image_info32 o;
5026 S.getName(SectName);
5027 DataRefImpl Ref = S.getRawDataRefImpl();
5028 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5029 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5031 r = get_pointer_32(p, offset, left, S, info);
5034 memset(&o, '\0', sizeof(struct objc_image_info32));
5035 if (left < sizeof(struct objc_image_info32)) {
5036 memcpy(&o, r, left);
5037 outs() << " (objc_image_info entends past the end of the section)\n";
5039 memcpy(&o, r, sizeof(struct objc_image_info32));
5040 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5042 outs() << " version " << o.version << "\n";
5043 outs() << " flags " << format("0x%" PRIx32, o.flags);
5044 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5045 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5046 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5047 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5048 swift_version = (o.flags >> 8) & 0xff;
5049 if (swift_version != 0) {
5050 if (swift_version == 1)
5051 outs() << " Swift 1.0";
5052 else if (swift_version == 2)
5053 outs() << " Swift 1.1";
5055 outs() << " unknown future Swift version (" << swift_version << ")";
5060 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5061 uint32_t left, offset, p;
5062 struct imageInfo_t o;
5066 S.getName(SectName);
5067 DataRefImpl Ref = S.getRawDataRefImpl();
5068 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5069 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5071 r = get_pointer_32(p, offset, left, S, info);
5074 memset(&o, '\0', sizeof(struct imageInfo_t));
5075 if (left < sizeof(struct imageInfo_t)) {
5076 memcpy(&o, r, left);
5077 outs() << " (imageInfo entends past the end of the section)\n";
5079 memcpy(&o, r, sizeof(struct imageInfo_t));
5080 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5082 outs() << " version " << o.version << "\n";
5083 outs() << " flags " << format("0x%" PRIx32, o.flags);
5089 outs() << " GC-only";
5095 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5096 SymbolAddressMap AddrMap;
5098 CreateSymbolAddressMap(O, &AddrMap);
5100 std::vector<SectionRef> Sections;
5101 for (const SectionRef &Section : O->sections()) {
5103 Section.getName(SectName);
5104 Sections.push_back(Section);
5107 struct DisassembleInfo info;
5108 // Set up the block of info used by the Symbolizer call backs.
5109 info.verbose = verbose;
5111 info.AddrMap = &AddrMap;
5112 info.Sections = &Sections;
5113 info.class_name = nullptr;
5114 info.selector_name = nullptr;
5115 info.method = nullptr;
5116 info.demangled_name = nullptr;
5117 info.bindtable = nullptr;
5122 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5123 if (CL != SectionRef()) {
5125 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5127 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5129 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5132 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5133 if (CR != SectionRef()) {
5135 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5137 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5139 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5142 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5143 if (SR != SectionRef()) {
5145 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5147 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5149 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5152 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5153 if (CA != SectionRef()) {
5155 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5157 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5159 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5162 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5163 if (PL != SectionRef()) {
5165 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5167 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5169 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5172 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5173 if (MR != SectionRef()) {
5175 print_message_refs64(MR, &info);
5177 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5179 print_message_refs64(MR, &info);
5182 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5183 if (II != SectionRef()) {
5185 print_image_info64(II, &info);
5187 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5189 print_image_info64(II, &info);
5192 if (info.bindtable != nullptr)
5193 delete info.bindtable;
5196 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5197 SymbolAddressMap AddrMap;
5199 CreateSymbolAddressMap(O, &AddrMap);
5201 std::vector<SectionRef> Sections;
5202 for (const SectionRef &Section : O->sections()) {
5204 Section.getName(SectName);
5205 Sections.push_back(Section);
5208 struct DisassembleInfo info;
5209 // Set up the block of info used by the Symbolizer call backs.
5210 info.verbose = verbose;
5212 info.AddrMap = &AddrMap;
5213 info.Sections = &Sections;
5214 info.class_name = nullptr;
5215 info.selector_name = nullptr;
5216 info.method = nullptr;
5217 info.demangled_name = nullptr;
5218 info.bindtable = nullptr;
5222 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5223 if (CL != SectionRef()) {
5225 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5227 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5229 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5232 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5233 if (CR != SectionRef()) {
5235 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5237 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5239 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5242 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5243 if (SR != SectionRef()) {
5245 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5247 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5249 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5252 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5253 if (CA != SectionRef()) {
5255 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5257 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5259 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5262 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5263 if (PL != SectionRef()) {
5265 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5267 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5269 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5272 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5273 if (MR != SectionRef()) {
5275 print_message_refs32(MR, &info);
5277 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5279 print_message_refs32(MR, &info);
5282 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5283 if (II != SectionRef()) {
5285 print_image_info32(II, &info);
5287 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5289 print_image_info32(II, &info);
5293 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5294 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5295 const char *r, *name, *defs;
5296 struct objc_module_t module;
5298 struct objc_symtab_t symtab;
5299 struct objc_class_t objc_class;
5300 struct objc_category_t objc_category;
5302 outs() << "Objective-C segment\n";
5303 S = get_section(O, "__OBJC", "__module_info");
5304 if (S == SectionRef())
5307 SymbolAddressMap AddrMap;
5309 CreateSymbolAddressMap(O, &AddrMap);
5311 std::vector<SectionRef> Sections;
5312 for (const SectionRef &Section : O->sections()) {
5314 Section.getName(SectName);
5315 Sections.push_back(Section);
5318 struct DisassembleInfo info;
5319 // Set up the block of info used by the Symbolizer call backs.
5320 info.verbose = verbose;
5322 info.AddrMap = &AddrMap;
5323 info.Sections = &Sections;
5324 info.class_name = nullptr;
5325 info.selector_name = nullptr;
5326 info.method = nullptr;
5327 info.demangled_name = nullptr;
5328 info.bindtable = nullptr;
5332 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5333 p = S.getAddress() + i;
5334 r = get_pointer_32(p, offset, left, S, &info, true);
5337 memset(&module, '\0', sizeof(struct objc_module_t));
5338 if (left < sizeof(struct objc_module_t)) {
5339 memcpy(&module, r, left);
5340 outs() << " (module extends past end of __module_info section)\n";
5342 memcpy(&module, r, sizeof(struct objc_module_t));
5343 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5346 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5347 outs() << " version " << module.version << "\n";
5348 outs() << " size " << module.size << "\n";
5350 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5351 if (name != nullptr)
5352 outs() << format("%.*s", left, name);
5354 outs() << format("0x%08" PRIx32, module.name)
5355 << "(not in an __OBJC section)";
5358 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5359 if (module.symtab == 0 || r == nullptr) {
5360 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5361 << " (not in an __OBJC section)\n";
5364 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5365 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5368 if (left < sizeof(struct objc_symtab_t)) {
5369 memcpy(&symtab, r, left);
5370 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5372 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5373 if (left > sizeof(struct objc_symtab_t)) {
5374 defs_left = left - sizeof(struct objc_symtab_t);
5375 defs = r + sizeof(struct objc_symtab_t);
5378 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5381 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5382 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5383 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5385 outs() << " (not in an __OBJC section)";
5387 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5388 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5389 if (symtab.cls_def_cnt > 0)
5390 outs() << "\tClass Definitions\n";
5391 for (j = 0; j < symtab.cls_def_cnt; j++) {
5392 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5393 outs() << "\t(remaining class defs entries entends past the end of the "
5397 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5398 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5399 sys::swapByteOrder(def);
5401 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5402 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5404 if (left > sizeof(struct objc_class_t)) {
5406 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5408 outs() << " (entends past the end of the section)\n";
5409 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5410 memcpy(&objc_class, r, left);
5412 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5413 swapStruct(objc_class);
5414 print_objc_class_t(&objc_class, &info);
5416 outs() << "(not in an __OBJC section)\n";
5419 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5420 outs() << "\tMeta Class";
5421 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5423 if (left > sizeof(struct objc_class_t)) {
5425 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5427 outs() << " (entends past the end of the section)\n";
5428 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5429 memcpy(&objc_class, r, left);
5431 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5432 swapStruct(objc_class);
5433 print_objc_class_t(&objc_class, &info);
5435 outs() << "(not in an __OBJC section)\n";
5439 if (symtab.cat_def_cnt > 0)
5440 outs() << "\tCategory Definitions\n";
5441 for (j = 0; j < symtab.cat_def_cnt; j++) {
5442 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5443 outs() << "\t(remaining category defs entries entends past the end of "
5444 << "the section)\n";
5447 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5449 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5450 sys::swapByteOrder(def);
5452 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5453 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5454 << format("0x%08" PRIx32, def);
5456 if (left > sizeof(struct objc_category_t)) {
5458 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5460 outs() << " (entends past the end of the section)\n";
5461 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5462 memcpy(&objc_category, r, left);
5464 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5465 swapStruct(objc_category);
5466 print_objc_objc_category_t(&objc_category, &info);
5468 outs() << "(not in an __OBJC section)\n";
5472 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5473 if (II != SectionRef())
5474 print_image_info(II, &info);
5479 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5480 uint32_t size, uint32_t addr) {
5481 SymbolAddressMap AddrMap;
5482 CreateSymbolAddressMap(O, &AddrMap);
5484 std::vector<SectionRef> Sections;
5485 for (const SectionRef &Section : O->sections()) {
5487 Section.getName(SectName);
5488 Sections.push_back(Section);
5491 struct DisassembleInfo info;
5492 // Set up the block of info used by the Symbolizer call backs.
5493 info.verbose = true;
5495 info.AddrMap = &AddrMap;
5496 info.Sections = &Sections;
5497 info.class_name = nullptr;
5498 info.selector_name = nullptr;
5499 info.method = nullptr;
5500 info.demangled_name = nullptr;
5501 info.bindtable = nullptr;
5506 struct objc_protocol_t protocol;
5507 uint32_t left, paddr;
5508 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5509 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5510 left = size - (p - sect);
5511 if (left < sizeof(struct objc_protocol_t)) {
5512 outs() << "Protocol extends past end of __protocol section\n";
5513 memcpy(&protocol, p, left);
5515 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5516 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5517 swapStruct(protocol);
5518 paddr = addr + (p - sect);
5519 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5520 if (print_protocol(paddr, 0, &info))
5521 outs() << "(not in an __OBJC section)\n";
5525 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5527 printObjc2_64bit_MetaData(O, verbose);
5529 MachO::mach_header H;
5531 if (H.cputype == MachO::CPU_TYPE_ARM)
5532 printObjc2_32bit_MetaData(O, verbose);
5534 // This is the 32-bit non-arm cputype case. Which is normally
5535 // the first Objective-C ABI. But it may be the case of a
5536 // binary for the iOS simulator which is the second Objective-C
5537 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5538 // and return false.
5539 if (!printObjc1_32bit_MetaData(O, verbose))
5540 printObjc2_32bit_MetaData(O, verbose);
5545 // GuessLiteralPointer returns a string which for the item in the Mach-O file
5546 // for the address passed in as ReferenceValue for printing as a comment with
5547 // the instruction and also returns the corresponding type of that item
5548 // indirectly through ReferenceType.
5550 // If ReferenceValue is an address of literal cstring then a pointer to the
5551 // cstring is returned and ReferenceType is set to
5552 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5554 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5555 // Class ref that name is returned and the ReferenceType is set accordingly.
5557 // Lastly, literals which are Symbol address in a literal pool are looked for
5558 // and if found the symbol name is returned and ReferenceType is set to
5559 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5561 // If there is no item in the Mach-O file for the address passed in as
5562 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
5563 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5564 uint64_t ReferencePC,
5565 uint64_t *ReferenceType,
5566 struct DisassembleInfo *info) {
5567 // First see if there is an external relocation entry at the ReferencePC.
5568 uint64_t sect_addr = info->S.getAddress();
5569 uint64_t sect_offset = ReferencePC - sect_addr;
5570 bool reloc_found = false;
5572 MachO::any_relocation_info RE;
5573 bool isExtern = false;
5575 for (const RelocationRef &Reloc : info->S.relocations()) {
5576 uint64_t RelocOffset = Reloc.getOffset();
5577 if (RelocOffset == sect_offset) {
5578 Rel = Reloc.getRawDataRefImpl();
5579 RE = info->O->getRelocation(Rel);
5580 if (info->O->isRelocationScattered(RE))
5582 isExtern = info->O->getPlainRelocationExternal(RE);
5584 symbol_iterator RelocSym = Reloc.getSymbol();
5591 // If there is an external relocation entry for a symbol in a section
5592 // then used that symbol's value for the value of the reference.
5593 if (reloc_found && isExtern) {
5594 if (info->O->getAnyRelocationPCRel(RE)) {
5595 unsigned Type = info->O->getAnyRelocationType(RE);
5596 if (Type == MachO::X86_64_RELOC_SIGNED) {
5597 ReferenceValue = Symbol.getValue();
5602 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5603 // Message refs and Class refs.
5604 bool classref, selref, msgref, cfstring;
5605 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5606 selref, msgref, cfstring);
5607 if (classref && pointer_value == 0) {
5608 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5609 // And the pointer_value in that section is typically zero as it will be
5610 // set by dyld as part of the "bind information".
5611 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5612 if (name != nullptr) {
5613 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5614 const char *class_name = strrchr(name, '$');
5615 if (class_name != nullptr && class_name[1] == '_' &&
5616 class_name[2] != '\0') {
5617 info->class_name = class_name + 2;
5624 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5626 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5627 if (name != nullptr)
5628 info->class_name = name;
5630 name = "bad class ref";
5635 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5636 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5640 if (selref && pointer_value == 0)
5641 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5643 if (pointer_value != 0)
5644 ReferenceValue = pointer_value;
5646 const char *name = GuessCstringPointer(ReferenceValue, info);
5648 if (pointer_value != 0 && selref) {
5649 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5650 info->selector_name = name;
5651 } else if (pointer_value != 0 && msgref) {
5652 info->class_name = nullptr;
5653 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5654 info->selector_name = name;
5656 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5660 // Lastly look for an indirect symbol with this ReferenceValue which is in
5661 // a literal pool. If found return that symbol name.
5662 name = GuessIndirectSymbol(ReferenceValue, info);
5664 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5671 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
5672 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
5673 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5674 // is created and returns the symbol name that matches the ReferenceValue or
5675 // nullptr if none. The ReferenceType is passed in for the IN type of
5676 // reference the instruction is making from the values in defined in the header
5677 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5678 // Out type and the ReferenceName will also be set which is added as a comment
5679 // to the disassembled instruction.
5682 // If the symbol name is a C++ mangled name then the demangled name is
5683 // returned through ReferenceName and ReferenceType is set to
5684 // LLVMDisassembler_ReferenceType_DeMangled_Name .
5687 // When this is called to get a symbol name for a branch target then the
5688 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5689 // SymbolValue will be looked for in the indirect symbol table to determine if
5690 // it is an address for a symbol stub. If so then the symbol name for that
5691 // stub is returned indirectly through ReferenceName and then ReferenceType is
5692 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5694 // When this is called with an value loaded via a PC relative load then
5695 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5696 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
5697 // or an Objective-C meta data reference. If so the output ReferenceType is
5698 // set to correspond to that as well as setting the ReferenceName.
5699 static const char *SymbolizerSymbolLookUp(void *DisInfo,
5700 uint64_t ReferenceValue,
5701 uint64_t *ReferenceType,
5702 uint64_t ReferencePC,
5703 const char **ReferenceName) {
5704 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
5705 // If no verbose symbolic information is wanted then just return nullptr.
5706 if (!info->verbose) {
5707 *ReferenceName = nullptr;
5708 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5712 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
5714 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5715 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
5716 if (*ReferenceName != nullptr) {
5717 method_reference(info, ReferenceType, ReferenceName);
5718 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5719 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5722 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5723 if (info->demangled_name != nullptr)
5724 free(info->demangled_name);
5726 info->demangled_name =
5727 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5728 if (info->demangled_name != nullptr) {
5729 *ReferenceName = info->demangled_name;
5730 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5732 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5735 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5736 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5738 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5740 method_reference(info, ReferenceType, ReferenceName);
5742 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5743 // If this is arm64 and the reference is an adrp instruction save the
5744 // instruction, passed in ReferenceValue and the address of the instruction
5745 // for use later if we see and add immediate instruction.
5746 } else if (info->O->getArch() == Triple::aarch64 &&
5747 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5748 info->adrp_inst = ReferenceValue;
5749 info->adrp_addr = ReferencePC;
5750 SymbolName = nullptr;
5751 *ReferenceName = nullptr;
5752 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5753 // If this is arm64 and reference is an add immediate instruction and we
5755 // seen an adrp instruction just before it and the adrp's Xd register
5757 // this add's Xn register reconstruct the value being referenced and look to
5758 // see if it is a literal pointer. Note the add immediate instruction is
5759 // passed in ReferenceValue.
5760 } else if (info->O->getArch() == Triple::aarch64 &&
5761 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5762 ReferencePC - 4 == info->adrp_addr &&
5763 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5764 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5765 uint32_t addxri_inst;
5766 uint64_t adrp_imm, addxri_imm;
5769 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5770 if (info->adrp_inst & 0x0200000)
5771 adrp_imm |= 0xfffffffffc000000LL;
5773 addxri_inst = ReferenceValue;
5774 addxri_imm = (addxri_inst >> 10) & 0xfff;
5775 if (((addxri_inst >> 22) & 0x3) == 1)
5778 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5779 (adrp_imm << 12) + addxri_imm;
5782 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5783 if (*ReferenceName == nullptr)
5784 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5785 // If this is arm64 and the reference is a load register instruction and we
5786 // have seen an adrp instruction just before it and the adrp's Xd register
5787 // matches this add's Xn register reconstruct the value being referenced and
5788 // look to see if it is a literal pointer. Note the load register
5789 // instruction is passed in ReferenceValue.
5790 } else if (info->O->getArch() == Triple::aarch64 &&
5791 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5792 ReferencePC - 4 == info->adrp_addr &&
5793 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5794 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5795 uint32_t ldrxui_inst;
5796 uint64_t adrp_imm, ldrxui_imm;
5799 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5800 if (info->adrp_inst & 0x0200000)
5801 adrp_imm |= 0xfffffffffc000000LL;
5803 ldrxui_inst = ReferenceValue;
5804 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5806 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5807 (adrp_imm << 12) + (ldrxui_imm << 3);
5810 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5811 if (*ReferenceName == nullptr)
5812 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5814 // If this arm64 and is an load register (PC-relative) instruction the
5815 // ReferenceValue is the PC plus the immediate value.
5816 else if (info->O->getArch() == Triple::aarch64 &&
5817 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5818 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5820 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5821 if (*ReferenceName == nullptr)
5822 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5825 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5826 if (info->demangled_name != nullptr)
5827 free(info->demangled_name);
5829 info->demangled_name =
5830 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5831 if (info->demangled_name != nullptr) {
5832 *ReferenceName = info->demangled_name;
5833 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5838 *ReferenceName = nullptr;
5839 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5845 /// \brief Emits the comments that are stored in the CommentStream.
5846 /// Each comment in the CommentStream must end with a newline.
5847 static void emitComments(raw_svector_ostream &CommentStream,
5848 SmallString<128> &CommentsToEmit,
5849 formatted_raw_ostream &FormattedOS,
5850 const MCAsmInfo &MAI) {
5851 // Flush the stream before taking its content.
5852 StringRef Comments = CommentsToEmit.str();
5853 // Get the default information for printing a comment.
5854 const char *CommentBegin = MAI.getCommentString();
5855 unsigned CommentColumn = MAI.getCommentColumn();
5856 bool IsFirst = true;
5857 while (!Comments.empty()) {
5859 FormattedOS << '\n';
5860 // Emit a line of comments.
5861 FormattedOS.PadToColumn(CommentColumn);
5862 size_t Position = Comments.find('\n');
5863 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5864 // Move after the newline character.
5865 Comments = Comments.substr(Position + 1);
5868 FormattedOS.flush();
5870 // Tell the comment stream that the vector changed underneath it.
5871 CommentsToEmit.clear();
5874 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5875 StringRef DisSegName, StringRef DisSectName) {
5876 const char *McpuDefault = nullptr;
5877 const Target *ThumbTarget = nullptr;
5878 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
5880 // GetTarget prints out stuff.
5883 if (MCPU.empty() && McpuDefault)
5886 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
5887 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
5889 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
5891 // Package up features to be passed to target/subtarget
5892 std::string FeaturesStr;
5893 if (MAttrs.size()) {
5894 SubtargetFeatures Features;
5895 for (unsigned i = 0; i != MAttrs.size(); ++i)
5896 Features.AddFeature(MAttrs[i]);
5897 FeaturesStr = Features.getString();
5900 // Set up disassembler.
5901 std::unique_ptr<const MCRegisterInfo> MRI(
5902 TheTarget->createMCRegInfo(TripleName));
5903 std::unique_ptr<const MCAsmInfo> AsmInfo(
5904 TheTarget->createMCAsmInfo(*MRI, TripleName));
5905 std::unique_ptr<const MCSubtargetInfo> STI(
5906 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
5907 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
5908 std::unique_ptr<MCDisassembler> DisAsm(
5909 TheTarget->createMCDisassembler(*STI, Ctx));
5910 std::unique_ptr<MCSymbolizer> Symbolizer;
5911 struct DisassembleInfo SymbolizerInfo;
5912 std::unique_ptr<MCRelocationInfo> RelInfo(
5913 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5915 Symbolizer.reset(TheTarget->createMCSymbolizer(
5916 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5917 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
5918 DisAsm->setSymbolizer(std::move(Symbolizer));
5920 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
5921 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
5922 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
5923 // Set the display preference for hex vs. decimal immediates.
5924 IP->setPrintImmHex(PrintImmHex);
5925 // Comment stream and backing vector.
5926 SmallString<128> CommentsToEmit;
5927 raw_svector_ostream CommentStream(CommentsToEmit);
5928 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5929 // if it is done then arm64 comments for string literals don't get printed
5930 // and some constant get printed instead and not setting it causes intel
5931 // (32-bit and 64-bit) comments printed with different spacing before the
5932 // comment causing different diffs with the 'C' disassembler library API.
5933 // IP->setCommentStream(CommentStream);
5935 if (!AsmInfo || !STI || !DisAsm || !IP) {
5936 errs() << "error: couldn't initialize disassembler for target "
5937 << TripleName << '\n';
5941 // Set up thumb disassembler.
5942 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5943 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5944 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
5945 std::unique_ptr<MCDisassembler> ThumbDisAsm;
5946 std::unique_ptr<MCInstPrinter> ThumbIP;
5947 std::unique_ptr<MCContext> ThumbCtx;
5948 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5949 struct DisassembleInfo ThumbSymbolizerInfo;
5950 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
5952 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
5954 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
5956 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
5957 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
5958 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
5959 MCContext *PtrThumbCtx = ThumbCtx.get();
5961 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
5963 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
5964 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5965 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
5966 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
5968 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
5969 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
5970 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
5971 *ThumbInstrInfo, *ThumbMRI));
5972 // Set the display preference for hex vs. decimal immediates.
5973 ThumbIP->setPrintImmHex(PrintImmHex);
5976 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
5977 errs() << "error: couldn't initialize disassembler for target "
5978 << ThumbTripleName << '\n';
5982 MachO::mach_header Header = MachOOF->getHeader();
5984 // FIXME: Using the -cfg command line option, this code used to be able to
5985 // annotate relocations with the referenced symbol's name, and if this was
5986 // inside a __[cf]string section, the data it points to. This is now replaced
5987 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
5988 std::vector<SectionRef> Sections;
5989 std::vector<SymbolRef> Symbols;
5990 SmallVector<uint64_t, 8> FoundFns;
5991 uint64_t BaseSegmentAddress;
5993 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
5994 BaseSegmentAddress);
5996 // Sort the symbols by address, just in case they didn't come in that way.
5997 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
5999 // Build a data in code table that is sorted on by the address of each entry.
6000 uint64_t BaseAddress = 0;
6001 if (Header.filetype == MachO::MH_OBJECT)
6002 BaseAddress = Sections[0].getAddress();
6004 BaseAddress = BaseSegmentAddress;
6006 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
6009 DI->getOffset(Offset);
6010 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6012 array_pod_sort(Dices.begin(), Dices.end());
6015 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6017 raw_ostream &DebugOut = nulls();
6020 std::unique_ptr<DIContext> diContext;
6021 ObjectFile *DbgObj = MachOOF;
6022 // Try to find debug info and set up the DIContext for it.
6024 // A separate DSym file path was specified, parse it as a macho file,
6025 // get the sections and supply it to the section name parsing machinery.
6026 if (!DSYMFile.empty()) {
6027 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
6028 MemoryBuffer::getFileOrSTDIN(DSYMFile);
6029 if (std::error_code EC = BufOrErr.getError()) {
6030 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
6034 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6039 // Setup the DIContext
6040 diContext.reset(new DWARFContextInMemory(*DbgObj));
6043 if (FilterSections.size() == 0)
6044 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
6046 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
6048 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6051 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
6053 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
6054 if (SegmentName != DisSegName)
6058 Sections[SectIdx].getContents(BytesStr);
6059 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6061 uint64_t SectAddress = Sections[SectIdx].getAddress();
6063 bool symbolTableWorked = false;
6065 // Parse relocations.
6066 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
6067 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
6068 uint64_t RelocOffset = Reloc.getOffset();
6069 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6070 RelocOffset -= SectionAddress;
6072 symbol_iterator RelocSym = Reloc.getSymbol();
6074 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
6076 array_pod_sort(Relocs.begin(), Relocs.end());
6078 // Create a map of symbol addresses to symbol names for use by
6079 // the SymbolizerSymbolLookUp() routine.
6080 SymbolAddressMap AddrMap;
6081 bool DisSymNameFound = false;
6082 for (const SymbolRef &Symbol : MachOOF->symbols()) {
6083 SymbolRef::Type ST = Symbol.getType();
6084 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6085 ST == SymbolRef::ST_Other) {
6086 uint64_t Address = Symbol.getValue();
6087 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6088 if (std::error_code EC = SymNameOrErr.getError())
6089 report_fatal_error(EC.message());
6090 StringRef SymName = *SymNameOrErr;
6091 AddrMap[Address] = SymName;
6092 if (!DisSymName.empty() && DisSymName == SymName)
6093 DisSymNameFound = true;
6096 if (!DisSymName.empty() && !DisSymNameFound) {
6097 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6100 // Set up the block of info used by the Symbolizer call backs.
6101 SymbolizerInfo.verbose = !NoSymbolicOperands;
6102 SymbolizerInfo.O = MachOOF;
6103 SymbolizerInfo.S = Sections[SectIdx];
6104 SymbolizerInfo.AddrMap = &AddrMap;
6105 SymbolizerInfo.Sections = &Sections;
6106 SymbolizerInfo.class_name = nullptr;
6107 SymbolizerInfo.selector_name = nullptr;
6108 SymbolizerInfo.method = nullptr;
6109 SymbolizerInfo.demangled_name = nullptr;
6110 SymbolizerInfo.bindtable = nullptr;
6111 SymbolizerInfo.adrp_addr = 0;
6112 SymbolizerInfo.adrp_inst = 0;
6113 // Same for the ThumbSymbolizer
6114 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
6115 ThumbSymbolizerInfo.O = MachOOF;
6116 ThumbSymbolizerInfo.S = Sections[SectIdx];
6117 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6118 ThumbSymbolizerInfo.Sections = &Sections;
6119 ThumbSymbolizerInfo.class_name = nullptr;
6120 ThumbSymbolizerInfo.selector_name = nullptr;
6121 ThumbSymbolizerInfo.method = nullptr;
6122 ThumbSymbolizerInfo.demangled_name = nullptr;
6123 ThumbSymbolizerInfo.bindtable = nullptr;
6124 ThumbSymbolizerInfo.adrp_addr = 0;
6125 ThumbSymbolizerInfo.adrp_inst = 0;
6127 // Disassemble symbol by symbol.
6128 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
6129 ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6130 if (std::error_code EC = SymNameOrErr.getError())
6131 report_fatal_error(EC.message());
6132 StringRef SymName = *SymNameOrErr;
6134 SymbolRef::Type ST = Symbols[SymIdx].getType();
6135 if (ST != SymbolRef::ST_Function)
6138 // Make sure the symbol is defined in this section.
6139 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
6143 // If we are only disassembling one symbol see if this is that symbol.
6144 if (!DisSymName.empty() && DisSymName != SymName)
6147 // Start at the address of the symbol relative to the section's address.
6148 uint64_t Start = Symbols[SymIdx].getValue();
6149 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6150 Start -= SectionAddress;
6152 // Stop disassembling either at the beginning of the next symbol or at
6153 // the end of the section.
6154 bool containsNextSym = false;
6155 uint64_t NextSym = 0;
6156 uint64_t NextSymIdx = SymIdx + 1;
6157 while (Symbols.size() > NextSymIdx) {
6158 SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
6159 if (NextSymType == SymbolRef::ST_Function) {
6161 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
6162 NextSym = Symbols[NextSymIdx].getValue();
6163 NextSym -= SectionAddress;
6169 uint64_t SectSize = Sections[SectIdx].getSize();
6170 uint64_t End = containsNextSym ? NextSym : SectSize;
6173 symbolTableWorked = true;
6175 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6177 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6179 outs() << SymName << ":\n";
6180 DILineInfo lastLine;
6181 for (uint64_t Index = Start; Index < End; Index += Size) {
6184 uint64_t PC = SectAddress + Index;
6185 if (!NoLeadingAddr) {
6186 if (FullLeadingAddr) {
6187 if (MachOOF->is64Bit())
6188 outs() << format("%016" PRIx64, PC);
6190 outs() << format("%08" PRIx64, PC);
6192 outs() << format("%8" PRIx64 ":", PC);
6198 // Check the data in code table here to see if this is data not an
6199 // instruction to be disassembled.
6201 Dice.push_back(std::make_pair(PC, DiceRef()));
6202 dice_table_iterator DTI =
6203 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6204 compareDiceTableEntries);
6205 if (DTI != Dices.end()) {
6207 DTI->second.getLength(Length);
6209 DTI->second.getKind(Kind);
6210 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
6211 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6212 (PC == (DTI->first + Length - 1)) && (Length & 1))
6217 SmallVector<char, 64> AnnotationsBytes;
6218 raw_svector_ostream Annotations(AnnotationsBytes);
6222 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
6223 PC, DebugOut, Annotations);
6225 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
6226 DebugOut, Annotations);
6228 if (!NoShowRawInsn) {
6229 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
6231 formatted_raw_ostream FormattedOS(outs());
6232 StringRef AnnotationsStr = Annotations.str();
6234 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
6236 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
6237 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
6239 // Print debug info.
6241 DILineInfo dli = diContext->getLineInfoForAddress(PC);
6242 // Print valid line info if it changed.
6243 if (dli != lastLine && dli.Line != 0)
6244 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6250 unsigned int Arch = MachOOF->getArch();
6251 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6252 outs() << format("\t.byte 0x%02x #bad opcode\n",
6253 *(Bytes.data() + Index) & 0xff);
6254 Size = 1; // skip exactly one illegible byte and move on.
6255 } else if (Arch == Triple::aarch64) {
6256 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6257 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6258 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6259 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6260 outs() << format("\t.long\t0x%08x\n", opcode);
6263 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6265 Size = 1; // skip illegible bytes
6270 if (!symbolTableWorked) {
6271 // Reading the symbol table didn't work, disassemble the whole section.
6272 uint64_t SectAddress = Sections[SectIdx].getAddress();
6273 uint64_t SectSize = Sections[SectIdx].getSize();
6275 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
6278 uint64_t PC = SectAddress + Index;
6279 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6280 DebugOut, nulls())) {
6281 if (!NoLeadingAddr) {
6282 if (FullLeadingAddr) {
6283 if (MachOOF->is64Bit())
6284 outs() << format("%016" PRIx64, PC);
6286 outs() << format("%08" PRIx64, PC);
6288 outs() << format("%8" PRIx64 ":", PC);
6291 if (!NoShowRawInsn) {
6293 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
6295 IP->printInst(&Inst, outs(), "", *STI);
6298 unsigned int Arch = MachOOF->getArch();
6299 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6300 outs() << format("\t.byte 0x%02x #bad opcode\n",
6301 *(Bytes.data() + Index) & 0xff);
6302 InstSize = 1; // skip exactly one illegible byte and move on.
6304 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6306 InstSize = 1; // skip illegible bytes
6311 // The TripleName's need to be reset if we are called again for a different
6314 ThumbTripleName = "";
6316 if (SymbolizerInfo.method != nullptr)
6317 free(SymbolizerInfo.method);
6318 if (SymbolizerInfo.demangled_name != nullptr)
6319 free(SymbolizerInfo.demangled_name);
6320 if (SymbolizerInfo.bindtable != nullptr)
6321 delete SymbolizerInfo.bindtable;
6322 if (ThumbSymbolizerInfo.method != nullptr)
6323 free(ThumbSymbolizerInfo.method);
6324 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6325 free(ThumbSymbolizerInfo.demangled_name);
6326 if (ThumbSymbolizerInfo.bindtable != nullptr)
6327 delete ThumbSymbolizerInfo.bindtable;
6331 //===----------------------------------------------------------------------===//
6332 // __compact_unwind section dumping
6333 //===----------------------------------------------------------------------===//
6337 template <typename T> static uint64_t readNext(const char *&Buf) {
6338 using llvm::support::little;
6339 using llvm::support::unaligned;
6341 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6346 struct CompactUnwindEntry {
6347 uint32_t OffsetInSection;
6349 uint64_t FunctionAddr;
6351 uint32_t CompactEncoding;
6352 uint64_t PersonalityAddr;
6355 RelocationRef FunctionReloc;
6356 RelocationRef PersonalityReloc;
6357 RelocationRef LSDAReloc;
6359 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
6360 : OffsetInSection(Offset) {
6362 read<uint64_t>(Contents.data() + Offset);
6364 read<uint32_t>(Contents.data() + Offset);
6368 template <typename UIntPtr> void read(const char *Buf) {
6369 FunctionAddr = readNext<UIntPtr>(Buf);
6370 Length = readNext<uint32_t>(Buf);
6371 CompactEncoding = readNext<uint32_t>(Buf);
6372 PersonalityAddr = readNext<UIntPtr>(Buf);
6373 LSDAAddr = readNext<UIntPtr>(Buf);
6378 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
6379 /// and data being relocated, determine the best base Name and Addend to use for
6380 /// display purposes.
6382 /// 1. An Extern relocation will directly reference a symbol (and the data is
6383 /// then already an addend), so use that.
6384 /// 2. Otherwise the data is an offset in the object file's layout; try to find
6385 // a symbol before it in the same section, and use the offset from there.
6386 /// 3. Finally, if all that fails, fall back to an offset from the start of the
6387 /// referenced section.
6388 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6389 std::map<uint64_t, SymbolRef> &Symbols,
6390 const RelocationRef &Reloc, uint64_t Addr,
6391 StringRef &Name, uint64_t &Addend) {
6392 if (Reloc.getSymbol() != Obj->symbol_end()) {
6393 ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6394 if (std::error_code EC = NameOrErr.getError())
6395 report_fatal_error(EC.message());
6401 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
6402 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
6404 uint64_t SectionAddr = RelocSection.getAddress();
6406 auto Sym = Symbols.upper_bound(Addr);
6407 if (Sym == Symbols.begin()) {
6408 // The first symbol in the object is after this reference, the best we can
6409 // do is section-relative notation.
6410 RelocSection.getName(Name);
6411 Addend = Addr - SectionAddr;
6415 // Go back one so that SymbolAddress <= Addr.
6418 section_iterator SymSection = *Sym->second.getSection();
6419 if (RelocSection == *SymSection) {
6420 // There's a valid symbol in the same section before this reference.
6421 ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6422 if (std::error_code EC = NameOrErr.getError())
6423 report_fatal_error(EC.message());
6425 Addend = Addr - Sym->first;
6429 // There is a symbol before this reference, but it's in a different
6430 // section. Probably not helpful to mention it, so use the section name.
6431 RelocSection.getName(Name);
6432 Addend = Addr - SectionAddr;
6435 static void printUnwindRelocDest(const MachOObjectFile *Obj,
6436 std::map<uint64_t, SymbolRef> &Symbols,
6437 const RelocationRef &Reloc, uint64_t Addr) {
6441 if (!Reloc.getObject())
6444 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6448 outs() << " + " << format("0x%" PRIx64, Addend);
6452 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6453 std::map<uint64_t, SymbolRef> &Symbols,
6454 const SectionRef &CompactUnwind) {
6456 assert(Obj->isLittleEndian() &&
6457 "There should not be a big-endian .o with __compact_unwind");
6459 bool Is64 = Obj->is64Bit();
6460 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6461 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6464 CompactUnwind.getContents(Contents);
6466 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6468 // First populate the initial raw offsets, encodings and so on from the entry.
6469 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6470 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6471 CompactUnwinds.push_back(Entry);
6474 // Next we need to look at the relocations to find out what objects are
6475 // actually being referred to.
6476 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
6477 uint64_t RelocAddress = Reloc.getOffset();
6479 uint32_t EntryIdx = RelocAddress / EntrySize;
6480 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6481 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6483 if (OffsetInEntry == 0)
6484 Entry.FunctionReloc = Reloc;
6485 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6486 Entry.PersonalityReloc = Reloc;
6487 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6488 Entry.LSDAReloc = Reloc;
6490 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6493 // Finally, we're ready to print the data we've gathered.
6494 outs() << "Contents of __compact_unwind section:\n";
6495 for (auto &Entry : CompactUnwinds) {
6496 outs() << " Entry at offset "
6497 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
6499 // 1. Start of the region this entry applies to.
6500 outs() << " start: " << format("0x%" PRIx64,
6501 Entry.FunctionAddr) << ' ';
6502 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
6505 // 2. Length of the region this entry applies to.
6506 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6508 // 3. The 32-bit compact encoding.
6509 outs() << " compact encoding: "
6510 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
6512 // 4. The personality function, if present.
6513 if (Entry.PersonalityReloc.getObject()) {
6514 outs() << " personality function: "
6515 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
6516 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6517 Entry.PersonalityAddr);
6521 // 5. This entry's language-specific data area.
6522 if (Entry.LSDAReloc.getObject()) {
6523 outs() << " LSDA: " << format("0x%" PRIx64,
6524 Entry.LSDAAddr) << ' ';
6525 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6531 //===----------------------------------------------------------------------===//
6532 // __unwind_info section dumping
6533 //===----------------------------------------------------------------------===//
6535 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6536 const char *Pos = PageStart;
6537 uint32_t Kind = readNext<uint32_t>(Pos);
6539 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6541 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6542 uint16_t NumEntries = readNext<uint16_t>(Pos);
6544 Pos = PageStart + EntriesStart;
6545 for (unsigned i = 0; i < NumEntries; ++i) {
6546 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6547 uint32_t Encoding = readNext<uint32_t>(Pos);
6549 outs() << " [" << i << "]: "
6550 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6552 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
6556 static void printCompressedSecondLevelUnwindPage(
6557 const char *PageStart, uint32_t FunctionBase,
6558 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6559 const char *Pos = PageStart;
6560 uint32_t Kind = readNext<uint32_t>(Pos);
6562 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6564 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6565 uint16_t NumEntries = readNext<uint16_t>(Pos);
6567 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6568 readNext<uint16_t>(Pos);
6569 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6570 PageStart + EncodingsStart);
6572 Pos = PageStart + EntriesStart;
6573 for (unsigned i = 0; i < NumEntries; ++i) {
6574 uint32_t Entry = readNext<uint32_t>(Pos);
6575 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6576 uint32_t EncodingIdx = Entry >> 24;
6579 if (EncodingIdx < CommonEncodings.size())
6580 Encoding = CommonEncodings[EncodingIdx];
6582 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6584 outs() << " [" << i << "]: "
6585 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6587 << "encoding[" << EncodingIdx
6588 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
6592 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6593 std::map<uint64_t, SymbolRef> &Symbols,
6594 const SectionRef &UnwindInfo) {
6596 assert(Obj->isLittleEndian() &&
6597 "There should not be a big-endian .o with __unwind_info");
6599 outs() << "Contents of __unwind_info section:\n";
6602 UnwindInfo.getContents(Contents);
6603 const char *Pos = Contents.data();
6605 //===----------------------------------
6607 //===----------------------------------
6609 uint32_t Version = readNext<uint32_t>(Pos);
6610 outs() << " Version: "
6611 << format("0x%" PRIx32, Version) << '\n';
6612 assert(Version == 1 && "only understand version 1");
6614 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6615 outs() << " Common encodings array section offset: "
6616 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6617 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6618 outs() << " Number of common encodings in array: "
6619 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6621 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6622 outs() << " Personality function array section offset: "
6623 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6624 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6625 outs() << " Number of personality functions in array: "
6626 << format("0x%" PRIx32, NumPersonalities) << '\n';
6628 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6629 outs() << " Index array section offset: "
6630 << format("0x%" PRIx32, IndicesStart) << '\n';
6631 uint32_t NumIndices = readNext<uint32_t>(Pos);
6632 outs() << " Number of indices in array: "
6633 << format("0x%" PRIx32, NumIndices) << '\n';
6635 //===----------------------------------
6636 // A shared list of common encodings
6637 //===----------------------------------
6639 // These occupy indices in the range [0, N] whenever an encoding is referenced
6640 // from a compressed 2nd level index table. In practice the linker only
6641 // creates ~128 of these, so that indices are available to embed encodings in
6642 // the 2nd level index.
6644 SmallVector<uint32_t, 64> CommonEncodings;
6645 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6646 Pos = Contents.data() + CommonEncodingsStart;
6647 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6648 uint32_t Encoding = readNext<uint32_t>(Pos);
6649 CommonEncodings.push_back(Encoding);
6651 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6655 //===----------------------------------
6656 // Personality functions used in this executable
6657 //===----------------------------------
6659 // There should be only a handful of these (one per source language,
6660 // roughly). Particularly since they only get 2 bits in the compact encoding.
6662 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6663 Pos = Contents.data() + PersonalitiesStart;
6664 for (unsigned i = 0; i < NumPersonalities; ++i) {
6665 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6666 outs() << " personality[" << i + 1
6667 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6670 //===----------------------------------
6671 // The level 1 index entries
6672 //===----------------------------------
6674 // These specify an approximate place to start searching for the more detailed
6675 // information, sorted by PC.
6678 uint32_t FunctionOffset;
6679 uint32_t SecondLevelPageStart;
6683 SmallVector<IndexEntry, 4> IndexEntries;
6685 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6686 Pos = Contents.data() + IndicesStart;
6687 for (unsigned i = 0; i < NumIndices; ++i) {
6690 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6691 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6692 Entry.LSDAStart = readNext<uint32_t>(Pos);
6693 IndexEntries.push_back(Entry);
6695 outs() << " [" << i << "]: "
6696 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6698 << "2nd level page offset="
6699 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
6700 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
6703 //===----------------------------------
6704 // Next come the LSDA tables
6705 //===----------------------------------
6707 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6708 // the first top-level index's LSDAOffset to the last (sentinel).
6710 outs() << " LSDA descriptors:\n";
6711 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6712 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6713 (2 * sizeof(uint32_t));
6714 for (int i = 0; i < NumLSDAs; ++i) {
6715 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6716 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6717 outs() << " [" << i << "]: "
6718 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6720 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
6723 //===----------------------------------
6724 // Finally, the 2nd level indices
6725 //===----------------------------------
6727 // Generally these are 4K in size, and have 2 possible forms:
6728 // + Regular stores up to 511 entries with disparate encodings
6729 // + Compressed stores up to 1021 entries if few enough compact encoding
6731 outs() << " Second level indices:\n";
6732 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6733 // The final sentinel top-level index has no associated 2nd level page
6734 if (IndexEntries[i].SecondLevelPageStart == 0)
6737 outs() << " Second level index[" << i << "]: "
6738 << "offset in section="
6739 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6741 << "base function offset="
6742 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6744 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
6745 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
6747 printRegularSecondLevelUnwindPage(Pos);
6749 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6752 llvm_unreachable("Do not know how to print this kind of 2nd level page");
6756 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6757 std::map<uint64_t, SymbolRef> Symbols;
6758 for (const SymbolRef &SymRef : Obj->symbols()) {
6759 // Discard any undefined or absolute symbols. They're not going to take part
6760 // in the convenience lookup for unwind info and just take up resources.
6761 section_iterator Section = *SymRef.getSection();
6762 if (Section == Obj->section_end())
6765 uint64_t Addr = SymRef.getValue();
6766 Symbols.insert(std::make_pair(Addr, SymRef));
6769 for (const SectionRef &Section : Obj->sections()) {
6771 Section.getName(SectName);
6772 if (SectName == "__compact_unwind")
6773 printMachOCompactUnwindSection(Obj, Symbols, Section);
6774 else if (SectName == "__unwind_info")
6775 printMachOUnwindInfoSection(Obj, Symbols, Section);
6776 else if (SectName == "__eh_frame")
6777 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
6781 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6782 uint32_t cpusubtype, uint32_t filetype,
6783 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6785 outs() << "Mach header\n";
6786 outs() << " magic cputype cpusubtype caps filetype ncmds "
6787 "sizeofcmds flags\n";
6789 if (magic == MachO::MH_MAGIC)
6790 outs() << " MH_MAGIC";
6791 else if (magic == MachO::MH_MAGIC_64)
6792 outs() << "MH_MAGIC_64";
6794 outs() << format(" 0x%08" PRIx32, magic);
6796 case MachO::CPU_TYPE_I386:
6798 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6799 case MachO::CPU_SUBTYPE_I386_ALL:
6803 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6807 case MachO::CPU_TYPE_X86_64:
6808 outs() << " X86_64";
6809 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6810 case MachO::CPU_SUBTYPE_X86_64_ALL:
6813 case MachO::CPU_SUBTYPE_X86_64_H:
6814 outs() << " Haswell";
6817 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6821 case MachO::CPU_TYPE_ARM:
6823 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6824 case MachO::CPU_SUBTYPE_ARM_ALL:
6827 case MachO::CPU_SUBTYPE_ARM_V4T:
6830 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6833 case MachO::CPU_SUBTYPE_ARM_XSCALE:
6834 outs() << " XSCALE";
6836 case MachO::CPU_SUBTYPE_ARM_V6:
6839 case MachO::CPU_SUBTYPE_ARM_V6M:
6842 case MachO::CPU_SUBTYPE_ARM_V7:
6845 case MachO::CPU_SUBTYPE_ARM_V7EM:
6848 case MachO::CPU_SUBTYPE_ARM_V7K:
6851 case MachO::CPU_SUBTYPE_ARM_V7M:
6854 case MachO::CPU_SUBTYPE_ARM_V7S:
6858 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6862 case MachO::CPU_TYPE_ARM64:
6864 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6865 case MachO::CPU_SUBTYPE_ARM64_ALL:
6869 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6873 case MachO::CPU_TYPE_POWERPC:
6875 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6876 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6880 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6884 case MachO::CPU_TYPE_POWERPC64:
6886 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6887 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6891 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6896 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
6899 outs() << format(" 0x%02" PRIx32,
6900 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
6903 case MachO::MH_OBJECT:
6904 outs() << " OBJECT";
6906 case MachO::MH_EXECUTE:
6907 outs() << " EXECUTE";
6909 case MachO::MH_FVMLIB:
6910 outs() << " FVMLIB";
6912 case MachO::MH_CORE:
6915 case MachO::MH_PRELOAD:
6916 outs() << " PRELOAD";
6918 case MachO::MH_DYLIB:
6921 case MachO::MH_DYLIB_STUB:
6922 outs() << " DYLIB_STUB";
6924 case MachO::MH_DYLINKER:
6925 outs() << " DYLINKER";
6927 case MachO::MH_BUNDLE:
6928 outs() << " BUNDLE";
6930 case MachO::MH_DSYM:
6933 case MachO::MH_KEXT_BUNDLE:
6934 outs() << " KEXTBUNDLE";
6937 outs() << format(" %10u", filetype);
6940 outs() << format(" %5u", ncmds);
6941 outs() << format(" %10u", sizeofcmds);
6943 if (f & MachO::MH_NOUNDEFS) {
6944 outs() << " NOUNDEFS";
6945 f &= ~MachO::MH_NOUNDEFS;
6947 if (f & MachO::MH_INCRLINK) {
6948 outs() << " INCRLINK";
6949 f &= ~MachO::MH_INCRLINK;
6951 if (f & MachO::MH_DYLDLINK) {
6952 outs() << " DYLDLINK";
6953 f &= ~MachO::MH_DYLDLINK;
6955 if (f & MachO::MH_BINDATLOAD) {
6956 outs() << " BINDATLOAD";
6957 f &= ~MachO::MH_BINDATLOAD;
6959 if (f & MachO::MH_PREBOUND) {
6960 outs() << " PREBOUND";
6961 f &= ~MachO::MH_PREBOUND;
6963 if (f & MachO::MH_SPLIT_SEGS) {
6964 outs() << " SPLIT_SEGS";
6965 f &= ~MachO::MH_SPLIT_SEGS;
6967 if (f & MachO::MH_LAZY_INIT) {
6968 outs() << " LAZY_INIT";
6969 f &= ~MachO::MH_LAZY_INIT;
6971 if (f & MachO::MH_TWOLEVEL) {
6972 outs() << " TWOLEVEL";
6973 f &= ~MachO::MH_TWOLEVEL;
6975 if (f & MachO::MH_FORCE_FLAT) {
6976 outs() << " FORCE_FLAT";
6977 f &= ~MachO::MH_FORCE_FLAT;
6979 if (f & MachO::MH_NOMULTIDEFS) {
6980 outs() << " NOMULTIDEFS";
6981 f &= ~MachO::MH_NOMULTIDEFS;
6983 if (f & MachO::MH_NOFIXPREBINDING) {
6984 outs() << " NOFIXPREBINDING";
6985 f &= ~MachO::MH_NOFIXPREBINDING;
6987 if (f & MachO::MH_PREBINDABLE) {
6988 outs() << " PREBINDABLE";
6989 f &= ~MachO::MH_PREBINDABLE;
6991 if (f & MachO::MH_ALLMODSBOUND) {
6992 outs() << " ALLMODSBOUND";
6993 f &= ~MachO::MH_ALLMODSBOUND;
6995 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
6996 outs() << " SUBSECTIONS_VIA_SYMBOLS";
6997 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
6999 if (f & MachO::MH_CANONICAL) {
7000 outs() << " CANONICAL";
7001 f &= ~MachO::MH_CANONICAL;
7003 if (f & MachO::MH_WEAK_DEFINES) {
7004 outs() << " WEAK_DEFINES";
7005 f &= ~MachO::MH_WEAK_DEFINES;
7007 if (f & MachO::MH_BINDS_TO_WEAK) {
7008 outs() << " BINDS_TO_WEAK";
7009 f &= ~MachO::MH_BINDS_TO_WEAK;
7011 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7012 outs() << " ALLOW_STACK_EXECUTION";
7013 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7015 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7016 outs() << " DEAD_STRIPPABLE_DYLIB";
7017 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7019 if (f & MachO::MH_PIE) {
7021 f &= ~MachO::MH_PIE;
7023 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7024 outs() << " NO_REEXPORTED_DYLIBS";
7025 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7027 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7028 outs() << " MH_HAS_TLV_DESCRIPTORS";
7029 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7031 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7032 outs() << " MH_NO_HEAP_EXECUTION";
7033 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7035 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7036 outs() << " APP_EXTENSION_SAFE";
7037 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7039 if (f != 0 || flags == 0)
7040 outs() << format(" 0x%08" PRIx32, f);
7042 outs() << format(" 0x%08" PRIx32, magic);
7043 outs() << format(" %7d", cputype);
7044 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7045 outs() << format(" 0x%02" PRIx32,
7046 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7047 outs() << format(" %10u", filetype);
7048 outs() << format(" %5u", ncmds);
7049 outs() << format(" %10u", sizeofcmds);
7050 outs() << format(" 0x%08" PRIx32, flags);
7055 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7056 StringRef SegName, uint64_t vmaddr,
7057 uint64_t vmsize, uint64_t fileoff,
7058 uint64_t filesize, uint32_t maxprot,
7059 uint32_t initprot, uint32_t nsects,
7060 uint32_t flags, uint32_t object_size,
7062 uint64_t expected_cmdsize;
7063 if (cmd == MachO::LC_SEGMENT) {
7064 outs() << " cmd LC_SEGMENT\n";
7065 expected_cmdsize = nsects;
7066 expected_cmdsize *= sizeof(struct MachO::section);
7067 expected_cmdsize += sizeof(struct MachO::segment_command);
7069 outs() << " cmd LC_SEGMENT_64\n";
7070 expected_cmdsize = nsects;
7071 expected_cmdsize *= sizeof(struct MachO::section_64);
7072 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7074 outs() << " cmdsize " << cmdsize;
7075 if (cmdsize != expected_cmdsize)
7076 outs() << " Inconsistent size\n";
7079 outs() << " segname " << SegName << "\n";
7080 if (cmd == MachO::LC_SEGMENT_64) {
7081 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7082 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7084 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7085 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
7087 outs() << " fileoff " << fileoff;
7088 if (fileoff > object_size)
7089 outs() << " (past end of file)\n";
7092 outs() << " filesize " << filesize;
7093 if (fileoff + filesize > object_size)
7094 outs() << " (past end of file)\n";
7099 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7100 MachO::VM_PROT_EXECUTE)) != 0)
7101 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7103 outs() << " maxprot ";
7104 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7105 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7106 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7109 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7110 MachO::VM_PROT_EXECUTE)) != 0)
7111 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7113 outs() << " initprot ";
7114 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7115 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7116 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7119 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7120 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7122 outs() << " nsects " << nsects << "\n";
7126 outs() << " (none)\n";
7128 if (flags & MachO::SG_HIGHVM) {
7129 outs() << " HIGHVM";
7130 flags &= ~MachO::SG_HIGHVM;
7132 if (flags & MachO::SG_FVMLIB) {
7133 outs() << " FVMLIB";
7134 flags &= ~MachO::SG_FVMLIB;
7136 if (flags & MachO::SG_NORELOC) {
7137 outs() << " NORELOC";
7138 flags &= ~MachO::SG_NORELOC;
7140 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7141 outs() << " PROTECTED_VERSION_1";
7142 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7145 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7150 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7154 static void PrintSection(const char *sectname, const char *segname,
7155 uint64_t addr, uint64_t size, uint32_t offset,
7156 uint32_t align, uint32_t reloff, uint32_t nreloc,
7157 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7158 uint32_t cmd, const char *sg_segname,
7159 uint32_t filetype, uint32_t object_size,
7161 outs() << "Section\n";
7162 outs() << " sectname " << format("%.16s\n", sectname);
7163 outs() << " segname " << format("%.16s", segname);
7164 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7165 outs() << " (does not match segment)\n";
7168 if (cmd == MachO::LC_SEGMENT_64) {
7169 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7170 outs() << " size " << format("0x%016" PRIx64, size);
7172 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7173 outs() << " size " << format("0x%08" PRIx64, size);
7175 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7176 outs() << " (past end of file)\n";
7179 outs() << " offset " << offset;
7180 if (offset > object_size)
7181 outs() << " (past end of file)\n";
7184 uint32_t align_shifted = 1 << align;
7185 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7186 outs() << " reloff " << reloff;
7187 if (reloff > object_size)
7188 outs() << " (past end of file)\n";
7191 outs() << " nreloc " << nreloc;
7192 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7193 outs() << " (past end of file)\n";
7196 uint32_t section_type = flags & MachO::SECTION_TYPE;
7199 if (section_type == MachO::S_REGULAR)
7200 outs() << " S_REGULAR\n";
7201 else if (section_type == MachO::S_ZEROFILL)
7202 outs() << " S_ZEROFILL\n";
7203 else if (section_type == MachO::S_CSTRING_LITERALS)
7204 outs() << " S_CSTRING_LITERALS\n";
7205 else if (section_type == MachO::S_4BYTE_LITERALS)
7206 outs() << " S_4BYTE_LITERALS\n";
7207 else if (section_type == MachO::S_8BYTE_LITERALS)
7208 outs() << " S_8BYTE_LITERALS\n";
7209 else if (section_type == MachO::S_16BYTE_LITERALS)
7210 outs() << " S_16BYTE_LITERALS\n";
7211 else if (section_type == MachO::S_LITERAL_POINTERS)
7212 outs() << " S_LITERAL_POINTERS\n";
7213 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7214 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7215 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7216 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7217 else if (section_type == MachO::S_SYMBOL_STUBS)
7218 outs() << " S_SYMBOL_STUBS\n";
7219 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7220 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7221 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7222 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7223 else if (section_type == MachO::S_COALESCED)
7224 outs() << " S_COALESCED\n";
7225 else if (section_type == MachO::S_INTERPOSING)
7226 outs() << " S_INTERPOSING\n";
7227 else if (section_type == MachO::S_DTRACE_DOF)
7228 outs() << " S_DTRACE_DOF\n";
7229 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7230 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7231 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7232 outs() << " S_THREAD_LOCAL_REGULAR\n";
7233 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7234 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7235 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7236 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7237 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7238 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7239 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7240 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7242 outs() << format("0x%08" PRIx32, section_type) << "\n";
7243 outs() << "attributes";
7244 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7245 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7246 outs() << " PURE_INSTRUCTIONS";
7247 if (section_attributes & MachO::S_ATTR_NO_TOC)
7248 outs() << " NO_TOC";
7249 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7250 outs() << " STRIP_STATIC_SYMS";
7251 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7252 outs() << " NO_DEAD_STRIP";
7253 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7254 outs() << " LIVE_SUPPORT";
7255 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7256 outs() << " SELF_MODIFYING_CODE";
7257 if (section_attributes & MachO::S_ATTR_DEBUG)
7259 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7260 outs() << " SOME_INSTRUCTIONS";
7261 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7262 outs() << " EXT_RELOC";
7263 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7264 outs() << " LOC_RELOC";
7265 if (section_attributes == 0)
7266 outs() << " (none)";
7269 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7270 outs() << " reserved1 " << reserved1;
7271 if (section_type == MachO::S_SYMBOL_STUBS ||
7272 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7273 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7274 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7275 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7276 outs() << " (index into indirect symbol table)\n";
7279 outs() << " reserved2 " << reserved2;
7280 if (section_type == MachO::S_SYMBOL_STUBS)
7281 outs() << " (size of stubs)\n";
7286 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
7287 uint32_t object_size) {
7288 outs() << " cmd LC_SYMTAB\n";
7289 outs() << " cmdsize " << st.cmdsize;
7290 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7291 outs() << " Incorrect size\n";
7294 outs() << " symoff " << st.symoff;
7295 if (st.symoff > object_size)
7296 outs() << " (past end of file)\n";
7299 outs() << " nsyms " << st.nsyms;
7302 big_size = st.nsyms;
7303 big_size *= sizeof(struct MachO::nlist_64);
7304 big_size += st.symoff;
7305 if (big_size > object_size)
7306 outs() << " (past end of file)\n";
7310 big_size = st.nsyms;
7311 big_size *= sizeof(struct MachO::nlist);
7312 big_size += st.symoff;
7313 if (big_size > object_size)
7314 outs() << " (past end of file)\n";
7318 outs() << " stroff " << st.stroff;
7319 if (st.stroff > object_size)
7320 outs() << " (past end of file)\n";
7323 outs() << " strsize " << st.strsize;
7324 big_size = st.stroff;
7325 big_size += st.strsize;
7326 if (big_size > object_size)
7327 outs() << " (past end of file)\n";
7332 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7333 uint32_t nsyms, uint32_t object_size,
7335 outs() << " cmd LC_DYSYMTAB\n";
7336 outs() << " cmdsize " << dyst.cmdsize;
7337 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7338 outs() << " Incorrect size\n";
7341 outs() << " ilocalsym " << dyst.ilocalsym;
7342 if (dyst.ilocalsym > nsyms)
7343 outs() << " (greater than the number of symbols)\n";
7346 outs() << " nlocalsym " << dyst.nlocalsym;
7348 big_size = dyst.ilocalsym;
7349 big_size += dyst.nlocalsym;
7350 if (big_size > nsyms)
7351 outs() << " (past the end of the symbol table)\n";
7354 outs() << " iextdefsym " << dyst.iextdefsym;
7355 if (dyst.iextdefsym > nsyms)
7356 outs() << " (greater than the number of symbols)\n";
7359 outs() << " nextdefsym " << dyst.nextdefsym;
7360 big_size = dyst.iextdefsym;
7361 big_size += dyst.nextdefsym;
7362 if (big_size > nsyms)
7363 outs() << " (past the end of the symbol table)\n";
7366 outs() << " iundefsym " << dyst.iundefsym;
7367 if (dyst.iundefsym > nsyms)
7368 outs() << " (greater than the number of symbols)\n";
7371 outs() << " nundefsym " << dyst.nundefsym;
7372 big_size = dyst.iundefsym;
7373 big_size += dyst.nundefsym;
7374 if (big_size > nsyms)
7375 outs() << " (past the end of the symbol table)\n";
7378 outs() << " tocoff " << dyst.tocoff;
7379 if (dyst.tocoff > object_size)
7380 outs() << " (past end of file)\n";
7383 outs() << " ntoc " << dyst.ntoc;
7384 big_size = dyst.ntoc;
7385 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7386 big_size += dyst.tocoff;
7387 if (big_size > object_size)
7388 outs() << " (past end of file)\n";
7391 outs() << " modtaboff " << dyst.modtaboff;
7392 if (dyst.modtaboff > object_size)
7393 outs() << " (past end of file)\n";
7396 outs() << " nmodtab " << dyst.nmodtab;
7399 modtabend = dyst.nmodtab;
7400 modtabend *= sizeof(struct MachO::dylib_module_64);
7401 modtabend += dyst.modtaboff;
7403 modtabend = dyst.nmodtab;
7404 modtabend *= sizeof(struct MachO::dylib_module);
7405 modtabend += dyst.modtaboff;
7407 if (modtabend > object_size)
7408 outs() << " (past end of file)\n";
7411 outs() << " extrefsymoff " << dyst.extrefsymoff;
7412 if (dyst.extrefsymoff > object_size)
7413 outs() << " (past end of file)\n";
7416 outs() << " nextrefsyms " << dyst.nextrefsyms;
7417 big_size = dyst.nextrefsyms;
7418 big_size *= sizeof(struct MachO::dylib_reference);
7419 big_size += dyst.extrefsymoff;
7420 if (big_size > object_size)
7421 outs() << " (past end of file)\n";
7424 outs() << " indirectsymoff " << dyst.indirectsymoff;
7425 if (dyst.indirectsymoff > object_size)
7426 outs() << " (past end of file)\n";
7429 outs() << " nindirectsyms " << dyst.nindirectsyms;
7430 big_size = dyst.nindirectsyms;
7431 big_size *= sizeof(uint32_t);
7432 big_size += dyst.indirectsymoff;
7433 if (big_size > object_size)
7434 outs() << " (past end of file)\n";
7437 outs() << " extreloff " << dyst.extreloff;
7438 if (dyst.extreloff > object_size)
7439 outs() << " (past end of file)\n";
7442 outs() << " nextrel " << dyst.nextrel;
7443 big_size = dyst.nextrel;
7444 big_size *= sizeof(struct MachO::relocation_info);
7445 big_size += dyst.extreloff;
7446 if (big_size > object_size)
7447 outs() << " (past end of file)\n";
7450 outs() << " locreloff " << dyst.locreloff;
7451 if (dyst.locreloff > object_size)
7452 outs() << " (past end of file)\n";
7455 outs() << " nlocrel " << dyst.nlocrel;
7456 big_size = dyst.nlocrel;
7457 big_size *= sizeof(struct MachO::relocation_info);
7458 big_size += dyst.locreloff;
7459 if (big_size > object_size)
7460 outs() << " (past end of file)\n";
7465 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7466 uint32_t object_size) {
7467 if (dc.cmd == MachO::LC_DYLD_INFO)
7468 outs() << " cmd LC_DYLD_INFO\n";
7470 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7471 outs() << " cmdsize " << dc.cmdsize;
7472 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7473 outs() << " Incorrect size\n";
7476 outs() << " rebase_off " << dc.rebase_off;
7477 if (dc.rebase_off > object_size)
7478 outs() << " (past end of file)\n";
7481 outs() << " rebase_size " << dc.rebase_size;
7483 big_size = dc.rebase_off;
7484 big_size += dc.rebase_size;
7485 if (big_size > object_size)
7486 outs() << " (past end of file)\n";
7489 outs() << " bind_off " << dc.bind_off;
7490 if (dc.bind_off > object_size)
7491 outs() << " (past end of file)\n";
7494 outs() << " bind_size " << dc.bind_size;
7495 big_size = dc.bind_off;
7496 big_size += dc.bind_size;
7497 if (big_size > object_size)
7498 outs() << " (past end of file)\n";
7501 outs() << " weak_bind_off " << dc.weak_bind_off;
7502 if (dc.weak_bind_off > object_size)
7503 outs() << " (past end of file)\n";
7506 outs() << " weak_bind_size " << dc.weak_bind_size;
7507 big_size = dc.weak_bind_off;
7508 big_size += dc.weak_bind_size;
7509 if (big_size > object_size)
7510 outs() << " (past end of file)\n";
7513 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7514 if (dc.lazy_bind_off > object_size)
7515 outs() << " (past end of file)\n";
7518 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7519 big_size = dc.lazy_bind_off;
7520 big_size += dc.lazy_bind_size;
7521 if (big_size > object_size)
7522 outs() << " (past end of file)\n";
7525 outs() << " export_off " << dc.export_off;
7526 if (dc.export_off > object_size)
7527 outs() << " (past end of file)\n";
7530 outs() << " export_size " << dc.export_size;
7531 big_size = dc.export_off;
7532 big_size += dc.export_size;
7533 if (big_size > object_size)
7534 outs() << " (past end of file)\n";
7539 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7541 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7542 outs() << " cmd LC_ID_DYLINKER\n";
7543 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7544 outs() << " cmd LC_LOAD_DYLINKER\n";
7545 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7546 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7548 outs() << " cmd ?(" << dyld.cmd << ")\n";
7549 outs() << " cmdsize " << dyld.cmdsize;
7550 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7551 outs() << " Incorrect size\n";
7554 if (dyld.name >= dyld.cmdsize)
7555 outs() << " name ?(bad offset " << dyld.name << ")\n";
7557 const char *P = (const char *)(Ptr) + dyld.name;
7558 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7562 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7563 outs() << " cmd LC_UUID\n";
7564 outs() << " cmdsize " << uuid.cmdsize;
7565 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7566 outs() << " Incorrect size\n";
7570 outs() << format("%02" PRIX32, uuid.uuid[0]);
7571 outs() << format("%02" PRIX32, uuid.uuid[1]);
7572 outs() << format("%02" PRIX32, uuid.uuid[2]);
7573 outs() << format("%02" PRIX32, uuid.uuid[3]);
7575 outs() << format("%02" PRIX32, uuid.uuid[4]);
7576 outs() << format("%02" PRIX32, uuid.uuid[5]);
7578 outs() << format("%02" PRIX32, uuid.uuid[6]);
7579 outs() << format("%02" PRIX32, uuid.uuid[7]);
7581 outs() << format("%02" PRIX32, uuid.uuid[8]);
7582 outs() << format("%02" PRIX32, uuid.uuid[9]);
7584 outs() << format("%02" PRIX32, uuid.uuid[10]);
7585 outs() << format("%02" PRIX32, uuid.uuid[11]);
7586 outs() << format("%02" PRIX32, uuid.uuid[12]);
7587 outs() << format("%02" PRIX32, uuid.uuid[13]);
7588 outs() << format("%02" PRIX32, uuid.uuid[14]);
7589 outs() << format("%02" PRIX32, uuid.uuid[15]);
7593 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
7594 outs() << " cmd LC_RPATH\n";
7595 outs() << " cmdsize " << rpath.cmdsize;
7596 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7597 outs() << " Incorrect size\n";
7600 if (rpath.path >= rpath.cmdsize)
7601 outs() << " path ?(bad offset " << rpath.path << ")\n";
7603 const char *P = (const char *)(Ptr) + rpath.path;
7604 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7608 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
7609 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
7610 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
7611 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
7612 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
7614 outs() << " cmd " << vd.cmd << " (?)\n";
7615 outs() << " cmdsize " << vd.cmdsize;
7616 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7617 outs() << " Incorrect size\n";
7620 outs() << " version "
7621 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7622 << MachOObjectFile::getVersionMinMinor(vd, false);
7623 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7625 outs() << "." << Update;
7628 outs() << " sdk n/a";
7631 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7632 << MachOObjectFile::getVersionMinMinor(vd, true);
7634 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7636 outs() << "." << Update;
7640 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7641 outs() << " cmd LC_SOURCE_VERSION\n";
7642 outs() << " cmdsize " << sd.cmdsize;
7643 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7644 outs() << " Incorrect size\n";
7647 uint64_t a = (sd.version >> 40) & 0xffffff;
7648 uint64_t b = (sd.version >> 30) & 0x3ff;
7649 uint64_t c = (sd.version >> 20) & 0x3ff;
7650 uint64_t d = (sd.version >> 10) & 0x3ff;
7651 uint64_t e = sd.version & 0x3ff;
7652 outs() << " version " << a << "." << b;
7654 outs() << "." << c << "." << d << "." << e;
7656 outs() << "." << c << "." << d;
7662 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7663 outs() << " cmd LC_MAIN\n";
7664 outs() << " cmdsize " << ep.cmdsize;
7665 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7666 outs() << " Incorrect size\n";
7669 outs() << " entryoff " << ep.entryoff << "\n";
7670 outs() << " stacksize " << ep.stacksize << "\n";
7673 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7674 uint32_t object_size) {
7675 outs() << " cmd LC_ENCRYPTION_INFO\n";
7676 outs() << " cmdsize " << ec.cmdsize;
7677 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7678 outs() << " Incorrect size\n";
7681 outs() << " cryptoff " << ec.cryptoff;
7682 if (ec.cryptoff > object_size)
7683 outs() << " (past end of file)\n";
7686 outs() << " cryptsize " << ec.cryptsize;
7687 if (ec.cryptsize > object_size)
7688 outs() << " (past end of file)\n";
7691 outs() << " cryptid " << ec.cryptid << "\n";
7694 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
7695 uint32_t object_size) {
7696 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7697 outs() << " cmdsize " << ec.cmdsize;
7698 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7699 outs() << " Incorrect size\n";
7702 outs() << " cryptoff " << ec.cryptoff;
7703 if (ec.cryptoff > object_size)
7704 outs() << " (past end of file)\n";
7707 outs() << " cryptsize " << ec.cryptsize;
7708 if (ec.cryptsize > object_size)
7709 outs() << " (past end of file)\n";
7712 outs() << " cryptid " << ec.cryptid << "\n";
7713 outs() << " pad " << ec.pad << "\n";
7716 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7718 outs() << " cmd LC_LINKER_OPTION\n";
7719 outs() << " cmdsize " << lo.cmdsize;
7720 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7721 outs() << " Incorrect size\n";
7724 outs() << " count " << lo.count << "\n";
7725 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7726 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7729 while (*string == '\0' && left > 0) {
7735 outs() << " string #" << i << " " << format("%.*s\n", left, string);
7736 uint32_t NullPos = StringRef(string, left).find('\0');
7737 uint32_t len = std::min(NullPos, left) + 1;
7743 outs() << " count " << lo.count << " does not match number of strings "
7747 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7749 outs() << " cmd LC_SUB_FRAMEWORK\n";
7750 outs() << " cmdsize " << sub.cmdsize;
7751 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7752 outs() << " Incorrect size\n";
7755 if (sub.umbrella < sub.cmdsize) {
7756 const char *P = Ptr + sub.umbrella;
7757 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7759 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7763 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7765 outs() << " cmd LC_SUB_UMBRELLA\n";
7766 outs() << " cmdsize " << sub.cmdsize;
7767 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7768 outs() << " Incorrect size\n";
7771 if (sub.sub_umbrella < sub.cmdsize) {
7772 const char *P = Ptr + sub.sub_umbrella;
7773 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7775 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7779 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
7781 outs() << " cmd LC_SUB_LIBRARY\n";
7782 outs() << " cmdsize " << sub.cmdsize;
7783 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7784 outs() << " Incorrect size\n";
7787 if (sub.sub_library < sub.cmdsize) {
7788 const char *P = Ptr + sub.sub_library;
7789 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7791 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7795 static void PrintSubClientCommand(MachO::sub_client_command sub,
7797 outs() << " cmd LC_SUB_CLIENT\n";
7798 outs() << " cmdsize " << sub.cmdsize;
7799 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7800 outs() << " Incorrect size\n";
7803 if (sub.client < sub.cmdsize) {
7804 const char *P = Ptr + sub.client;
7805 outs() << " client " << P << " (offset " << sub.client << ")\n";
7807 outs() << " client ?(bad offset " << sub.client << ")\n";
7811 static void PrintRoutinesCommand(MachO::routines_command r) {
7812 outs() << " cmd LC_ROUTINES\n";
7813 outs() << " cmdsize " << r.cmdsize;
7814 if (r.cmdsize != sizeof(struct MachO::routines_command))
7815 outs() << " Incorrect size\n";
7818 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7819 outs() << " init_module " << r.init_module << "\n";
7820 outs() << " reserved1 " << r.reserved1 << "\n";
7821 outs() << " reserved2 " << r.reserved2 << "\n";
7822 outs() << " reserved3 " << r.reserved3 << "\n";
7823 outs() << " reserved4 " << r.reserved4 << "\n";
7824 outs() << " reserved5 " << r.reserved5 << "\n";
7825 outs() << " reserved6 " << r.reserved6 << "\n";
7828 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7829 outs() << " cmd LC_ROUTINES_64\n";
7830 outs() << " cmdsize " << r.cmdsize;
7831 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
7832 outs() << " Incorrect size\n";
7835 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
7836 outs() << " init_module " << r.init_module << "\n";
7837 outs() << " reserved1 " << r.reserved1 << "\n";
7838 outs() << " reserved2 " << r.reserved2 << "\n";
7839 outs() << " reserved3 " << r.reserved3 << "\n";
7840 outs() << " reserved4 " << r.reserved4 << "\n";
7841 outs() << " reserved5 " << r.reserved5 << "\n";
7842 outs() << " reserved6 " << r.reserved6 << "\n";
7845 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
7846 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
7847 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
7848 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
7849 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
7850 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
7851 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
7852 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
7853 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
7854 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
7855 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
7856 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
7857 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
7858 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
7859 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
7860 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
7861 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
7862 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
7863 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
7864 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
7865 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
7866 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
7869 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
7871 outs() << "\t mmst_reg ";
7872 for (f = 0; f < 10; f++)
7873 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
7875 outs() << "\t mmst_rsrv ";
7876 for (f = 0; f < 6; f++)
7877 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
7881 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
7883 outs() << "\t xmm_reg ";
7884 for (f = 0; f < 16; f++)
7885 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
7889 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
7890 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
7891 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
7892 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
7893 outs() << " denorm " << fpu.fpu_fcw.denorm;
7894 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
7895 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
7896 outs() << " undfl " << fpu.fpu_fcw.undfl;
7897 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
7898 outs() << "\t\t pc ";
7899 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
7900 outs() << "FP_PREC_24B ";
7901 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
7902 outs() << "FP_PREC_53B ";
7903 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
7904 outs() << "FP_PREC_64B ";
7906 outs() << fpu.fpu_fcw.pc << " ";
7908 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
7909 outs() << "FP_RND_NEAR ";
7910 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
7911 outs() << "FP_RND_DOWN ";
7912 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
7913 outs() << "FP_RND_UP ";
7914 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
7915 outs() << "FP_CHOP ";
7917 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
7918 outs() << " denorm " << fpu.fpu_fsw.denorm;
7919 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
7920 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
7921 outs() << " undfl " << fpu.fpu_fsw.undfl;
7922 outs() << " precis " << fpu.fpu_fsw.precis;
7923 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
7924 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
7925 outs() << " c0 " << fpu.fpu_fsw.c0;
7926 outs() << " c1 " << fpu.fpu_fsw.c1;
7927 outs() << " c2 " << fpu.fpu_fsw.c2;
7928 outs() << " tos " << fpu.fpu_fsw.tos;
7929 outs() << " c3 " << fpu.fpu_fsw.c3;
7930 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
7931 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
7932 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
7933 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
7934 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
7935 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
7936 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
7937 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
7938 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
7939 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
7940 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
7941 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
7943 outs() << "\t fpu_stmm0:\n";
7944 Print_mmst_reg(fpu.fpu_stmm0);
7945 outs() << "\t fpu_stmm1:\n";
7946 Print_mmst_reg(fpu.fpu_stmm1);
7947 outs() << "\t fpu_stmm2:\n";
7948 Print_mmst_reg(fpu.fpu_stmm2);
7949 outs() << "\t fpu_stmm3:\n";
7950 Print_mmst_reg(fpu.fpu_stmm3);
7951 outs() << "\t fpu_stmm4:\n";
7952 Print_mmst_reg(fpu.fpu_stmm4);
7953 outs() << "\t fpu_stmm5:\n";
7954 Print_mmst_reg(fpu.fpu_stmm5);
7955 outs() << "\t fpu_stmm6:\n";
7956 Print_mmst_reg(fpu.fpu_stmm6);
7957 outs() << "\t fpu_stmm7:\n";
7958 Print_mmst_reg(fpu.fpu_stmm7);
7959 outs() << "\t fpu_xmm0:\n";
7960 Print_xmm_reg(fpu.fpu_xmm0);
7961 outs() << "\t fpu_xmm1:\n";
7962 Print_xmm_reg(fpu.fpu_xmm1);
7963 outs() << "\t fpu_xmm2:\n";
7964 Print_xmm_reg(fpu.fpu_xmm2);
7965 outs() << "\t fpu_xmm3:\n";
7966 Print_xmm_reg(fpu.fpu_xmm3);
7967 outs() << "\t fpu_xmm4:\n";
7968 Print_xmm_reg(fpu.fpu_xmm4);
7969 outs() << "\t fpu_xmm5:\n";
7970 Print_xmm_reg(fpu.fpu_xmm5);
7971 outs() << "\t fpu_xmm6:\n";
7972 Print_xmm_reg(fpu.fpu_xmm6);
7973 outs() << "\t fpu_xmm7:\n";
7974 Print_xmm_reg(fpu.fpu_xmm7);
7975 outs() << "\t fpu_xmm8:\n";
7976 Print_xmm_reg(fpu.fpu_xmm8);
7977 outs() << "\t fpu_xmm9:\n";
7978 Print_xmm_reg(fpu.fpu_xmm9);
7979 outs() << "\t fpu_xmm10:\n";
7980 Print_xmm_reg(fpu.fpu_xmm10);
7981 outs() << "\t fpu_xmm11:\n";
7982 Print_xmm_reg(fpu.fpu_xmm11);
7983 outs() << "\t fpu_xmm12:\n";
7984 Print_xmm_reg(fpu.fpu_xmm12);
7985 outs() << "\t fpu_xmm13:\n";
7986 Print_xmm_reg(fpu.fpu_xmm13);
7987 outs() << "\t fpu_xmm14:\n";
7988 Print_xmm_reg(fpu.fpu_xmm14);
7989 outs() << "\t fpu_xmm15:\n";
7990 Print_xmm_reg(fpu.fpu_xmm15);
7991 outs() << "\t fpu_rsrv4:\n";
7992 for (uint32_t f = 0; f < 6; f++) {
7994 for (uint32_t g = 0; g < 16; g++)
7995 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
7998 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8002 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8003 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8004 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8005 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8008 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8009 bool isLittleEndian, uint32_t cputype) {
8010 if (t.cmd == MachO::LC_THREAD)
8011 outs() << " cmd LC_THREAD\n";
8012 else if (t.cmd == MachO::LC_UNIXTHREAD)
8013 outs() << " cmd LC_UNIXTHREAD\n";
8015 outs() << " cmd " << t.cmd << " (unknown)\n";
8016 outs() << " cmdsize " << t.cmdsize;
8017 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8018 outs() << " Incorrect size\n";
8022 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8023 const char *end = Ptr + t.cmdsize;
8024 uint32_t flavor, count, left;
8025 if (cputype == MachO::CPU_TYPE_X86_64) {
8026 while (begin < end) {
8027 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8028 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8029 begin += sizeof(uint32_t);
8034 if (isLittleEndian != sys::IsLittleEndianHost)
8035 sys::swapByteOrder(flavor);
8036 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8037 memcpy((char *)&count, begin, sizeof(uint32_t));
8038 begin += sizeof(uint32_t);
8043 if (isLittleEndian != sys::IsLittleEndianHost)
8044 sys::swapByteOrder(count);
8045 if (flavor == MachO::x86_THREAD_STATE64) {
8046 outs() << " flavor x86_THREAD_STATE64\n";
8047 if (count == MachO::x86_THREAD_STATE64_COUNT)
8048 outs() << " count x86_THREAD_STATE64_COUNT\n";
8050 outs() << " count " << count
8051 << " (not x86_THREAD_STATE64_COUNT)\n";
8052 MachO::x86_thread_state64_t cpu64;
8054 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8055 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8056 begin += sizeof(MachO::x86_thread_state64_t);
8058 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8059 memcpy(&cpu64, begin, left);
8062 if (isLittleEndian != sys::IsLittleEndianHost)
8064 Print_x86_thread_state64_t(cpu64);
8065 } else if (flavor == MachO::x86_THREAD_STATE) {
8066 outs() << " flavor x86_THREAD_STATE\n";
8067 if (count == MachO::x86_THREAD_STATE_COUNT)
8068 outs() << " count x86_THREAD_STATE_COUNT\n";
8070 outs() << " count " << count
8071 << " (not x86_THREAD_STATE_COUNT)\n";
8072 struct MachO::x86_thread_state_t ts;
8074 if (left >= sizeof(MachO::x86_thread_state_t)) {
8075 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8076 begin += sizeof(MachO::x86_thread_state_t);
8078 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8079 memcpy(&ts, begin, left);
8082 if (isLittleEndian != sys::IsLittleEndianHost)
8084 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8085 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8086 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8087 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8089 outs() << "tsh.count " << ts.tsh.count
8090 << " (not x86_THREAD_STATE64_COUNT\n";
8091 Print_x86_thread_state64_t(ts.uts.ts64);
8093 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8094 << ts.tsh.count << "\n";
8096 } else if (flavor == MachO::x86_FLOAT_STATE) {
8097 outs() << " flavor x86_FLOAT_STATE\n";
8098 if (count == MachO::x86_FLOAT_STATE_COUNT)
8099 outs() << " count x86_FLOAT_STATE_COUNT\n";
8101 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
8102 struct MachO::x86_float_state_t fs;
8104 if (left >= sizeof(MachO::x86_float_state_t)) {
8105 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8106 begin += sizeof(MachO::x86_float_state_t);
8108 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8109 memcpy(&fs, begin, left);
8112 if (isLittleEndian != sys::IsLittleEndianHost)
8114 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8115 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
8116 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
8117 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8119 outs() << "fsh.count " << fs.fsh.count
8120 << " (not x86_FLOAT_STATE64_COUNT\n";
8121 Print_x86_float_state_t(fs.ufs.fs64);
8123 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8124 << fs.fsh.count << "\n";
8126 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8127 outs() << " flavor x86_EXCEPTION_STATE\n";
8128 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8129 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8131 outs() << " count " << count
8132 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8133 struct MachO::x86_exception_state_t es;
8135 if (left >= sizeof(MachO::x86_exception_state_t)) {
8136 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8137 begin += sizeof(MachO::x86_exception_state_t);
8139 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8140 memcpy(&es, begin, left);
8143 if (isLittleEndian != sys::IsLittleEndianHost)
8145 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8146 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
8147 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
8148 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8150 outs() << "\t esh.count " << es.esh.count
8151 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8152 Print_x86_exception_state_t(es.ues.es64);
8154 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8155 << es.esh.count << "\n";
8158 outs() << " flavor " << flavor << " (unknown)\n";
8159 outs() << " count " << count << "\n";
8160 outs() << " state (unknown)\n";
8161 begin += count * sizeof(uint32_t);
8165 while (begin < end) {
8166 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8167 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8168 begin += sizeof(uint32_t);
8173 if (isLittleEndian != sys::IsLittleEndianHost)
8174 sys::swapByteOrder(flavor);
8175 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8176 memcpy((char *)&count, begin, sizeof(uint32_t));
8177 begin += sizeof(uint32_t);
8182 if (isLittleEndian != sys::IsLittleEndianHost)
8183 sys::swapByteOrder(count);
8184 outs() << " flavor " << flavor << "\n";
8185 outs() << " count " << count << "\n";
8186 outs() << " state (Unknown cputype/cpusubtype)\n";
8187 begin += count * sizeof(uint32_t);
8192 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8193 if (dl.cmd == MachO::LC_ID_DYLIB)
8194 outs() << " cmd LC_ID_DYLIB\n";
8195 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8196 outs() << " cmd LC_LOAD_DYLIB\n";
8197 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8198 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8199 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8200 outs() << " cmd LC_REEXPORT_DYLIB\n";
8201 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8202 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8203 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8204 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8206 outs() << " cmd " << dl.cmd << " (unknown)\n";
8207 outs() << " cmdsize " << dl.cmdsize;
8208 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8209 outs() << " Incorrect size\n";
8212 if (dl.dylib.name < dl.cmdsize) {
8213 const char *P = (const char *)(Ptr) + dl.dylib.name;
8214 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8216 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8218 outs() << " time stamp " << dl.dylib.timestamp << " ";
8219 time_t t = dl.dylib.timestamp;
8220 outs() << ctime(&t);
8221 outs() << " current version ";
8222 if (dl.dylib.current_version == 0xffffffff)
8225 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8226 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8227 << (dl.dylib.current_version & 0xff) << "\n";
8228 outs() << "compatibility version ";
8229 if (dl.dylib.compatibility_version == 0xffffffff)
8232 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8233 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8234 << (dl.dylib.compatibility_version & 0xff) << "\n";
8237 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8238 uint32_t object_size) {
8239 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8240 outs() << " cmd LC_FUNCTION_STARTS\n";
8241 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8242 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8243 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8244 outs() << " cmd LC_FUNCTION_STARTS\n";
8245 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8246 outs() << " cmd LC_DATA_IN_CODE\n";
8247 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8248 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8249 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8250 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8252 outs() << " cmd " << ld.cmd << " (?)\n";
8253 outs() << " cmdsize " << ld.cmdsize;
8254 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8255 outs() << " Incorrect size\n";
8258 outs() << " dataoff " << ld.dataoff;
8259 if (ld.dataoff > object_size)
8260 outs() << " (past end of file)\n";
8263 outs() << " datasize " << ld.datasize;
8264 uint64_t big_size = ld.dataoff;
8265 big_size += ld.datasize;
8266 if (big_size > object_size)
8267 outs() << " (past end of file)\n";
8272 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8273 uint32_t cputype, bool verbose) {
8274 StringRef Buf = Obj->getData();
8276 for (const auto &Command : Obj->load_commands()) {
8277 outs() << "Load command " << Index++ << "\n";
8278 if (Command.C.cmd == MachO::LC_SEGMENT) {
8279 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8280 const char *sg_segname = SLC.segname;
8281 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8282 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8283 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8285 for (unsigned j = 0; j < SLC.nsects; j++) {
8286 MachO::section S = Obj->getSection(Command, j);
8287 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8288 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8289 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8291 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8292 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8293 const char *sg_segname = SLC_64.segname;
8294 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8295 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8296 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8297 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8298 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8299 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8300 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8301 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8302 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8303 sg_segname, filetype, Buf.size(), verbose);
8305 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8306 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8307 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
8308 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8309 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8310 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8311 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8313 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8314 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8315 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8316 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8317 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8318 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8319 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8320 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8321 PrintDyldLoadCommand(Dyld, Command.Ptr);
8322 } else if (Command.C.cmd == MachO::LC_UUID) {
8323 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8324 PrintUuidLoadCommand(Uuid);
8325 } else if (Command.C.cmd == MachO::LC_RPATH) {
8326 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8327 PrintRpathLoadCommand(Rpath, Command.Ptr);
8328 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
8329 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
8330 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8331 PrintVersionMinLoadCommand(Vd);
8332 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8333 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8334 PrintSourceVersionCommand(Sd);
8335 } else if (Command.C.cmd == MachO::LC_MAIN) {
8336 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8337 PrintEntryPointCommand(Ep);
8338 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
8339 MachO::encryption_info_command Ei =
8340 Obj->getEncryptionInfoCommand(Command);
8341 PrintEncryptionInfoCommand(Ei, Buf.size());
8342 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
8343 MachO::encryption_info_command_64 Ei =
8344 Obj->getEncryptionInfoCommand64(Command);
8345 PrintEncryptionInfoCommand64(Ei, Buf.size());
8346 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
8347 MachO::linker_option_command Lo =
8348 Obj->getLinkerOptionLoadCommand(Command);
8349 PrintLinkerOptionCommand(Lo, Command.Ptr);
8350 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8351 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8352 PrintSubFrameworkCommand(Sf, Command.Ptr);
8353 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8354 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8355 PrintSubUmbrellaCommand(Sf, Command.Ptr);
8356 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8357 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8358 PrintSubLibraryCommand(Sl, Command.Ptr);
8359 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8360 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8361 PrintSubClientCommand(Sc, Command.Ptr);
8362 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8363 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8364 PrintRoutinesCommand(Rc);
8365 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8366 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8367 PrintRoutinesCommand64(Rc);
8368 } else if (Command.C.cmd == MachO::LC_THREAD ||
8369 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8370 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8371 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
8372 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8373 Command.C.cmd == MachO::LC_ID_DYLIB ||
8374 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8375 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8376 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8377 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
8378 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8379 PrintDylibCommand(Dl, Command.Ptr);
8380 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8381 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8382 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8383 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8384 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8385 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8386 MachO::linkedit_data_command Ld =
8387 Obj->getLinkeditDataLoadCommand(Command);
8388 PrintLinkEditDataCommand(Ld, Buf.size());
8390 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8392 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8393 // TODO: get and print the raw bytes of the load command.
8395 // TODO: print all the other kinds of load commands.
8399 static void getAndPrintMachHeader(const MachOObjectFile *Obj,
8400 uint32_t &filetype, uint32_t &cputype,
8402 if (Obj->is64Bit()) {
8403 MachO::mach_header_64 H_64;
8404 H_64 = Obj->getHeader64();
8405 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8406 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8407 filetype = H_64.filetype;
8408 cputype = H_64.cputype;
8410 MachO::mach_header H;
8411 H = Obj->getHeader();
8412 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8413 H.sizeofcmds, H.flags, verbose);
8414 filetype = H.filetype;
8415 cputype = H.cputype;
8419 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8420 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
8421 uint32_t filetype = 0;
8422 uint32_t cputype = 0;
8423 getAndPrintMachHeader(file, filetype, cputype, !NonVerbose);
8424 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
8427 //===----------------------------------------------------------------------===//
8428 // export trie dumping
8429 //===----------------------------------------------------------------------===//
8431 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
8432 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8433 uint64_t Flags = Entry.flags();
8434 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8435 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8436 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8437 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8438 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8439 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8440 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8442 outs() << "[re-export] ";
8444 outs() << format("0x%08llX ",
8445 Entry.address()); // FIXME:add in base address
8446 outs() << Entry.name();
8447 if (WeakDef || ThreadLocal || Resolver || Abs) {
8448 bool NeedsComma = false;
8451 outs() << "weak_def";
8457 outs() << "per-thread";
8463 outs() << "absolute";
8469 outs() << format("resolver=0x%08llX", Entry.other());
8475 StringRef DylibName = "unknown";
8476 int Ordinal = Entry.other() - 1;
8477 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8478 if (Entry.otherName().empty())
8479 outs() << " (from " << DylibName << ")";
8481 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
8487 //===----------------------------------------------------------------------===//
8488 // rebase table dumping
8489 //===----------------------------------------------------------------------===//
8494 SegInfo(const object::MachOObjectFile *Obj);
8496 StringRef segmentName(uint32_t SegIndex);
8497 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8498 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
8501 struct SectionInfo {
8504 StringRef SectionName;
8505 StringRef SegmentName;
8506 uint64_t OffsetInSegment;
8507 uint64_t SegmentStartAddress;
8508 uint32_t SegmentIndex;
8510 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8511 SmallVector<SectionInfo, 32> Sections;
8515 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8516 // Build table of sections so segIndex/offset pairs can be translated.
8517 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
8518 StringRef CurSegName;
8519 uint64_t CurSegAddress;
8520 for (const SectionRef &Section : Obj->sections()) {
8522 error(Section.getName(Info.SectionName));
8523 Info.Address = Section.getAddress();
8524 Info.Size = Section.getSize();
8526 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8527 if (!Info.SegmentName.equals(CurSegName)) {
8529 CurSegName = Info.SegmentName;
8530 CurSegAddress = Info.Address;
8532 Info.SegmentIndex = CurSegIndex - 1;
8533 Info.OffsetInSegment = Info.Address - CurSegAddress;
8534 Info.SegmentStartAddress = CurSegAddress;
8535 Sections.push_back(Info);
8539 StringRef SegInfo::segmentName(uint32_t SegIndex) {
8540 for (const SectionInfo &SI : Sections) {
8541 if (SI.SegmentIndex == SegIndex)
8542 return SI.SegmentName;
8544 llvm_unreachable("invalid segIndex");
8547 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8548 uint64_t OffsetInSeg) {
8549 for (const SectionInfo &SI : Sections) {
8550 if (SI.SegmentIndex != SegIndex)
8552 if (SI.OffsetInSegment > OffsetInSeg)
8554 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8558 llvm_unreachable("segIndex and offset not in any section");
8561 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8562 return findSection(SegIndex, OffsetInSeg).SectionName;
8565 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8566 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8567 return SI.SegmentStartAddress + OffsetInSeg;
8570 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8571 // Build table of sections so names can used in final output.
8572 SegInfo sectionTable(Obj);
8574 outs() << "segment section address type\n";
8575 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8576 uint32_t SegIndex = Entry.segmentIndex();
8577 uint64_t OffsetInSeg = Entry.segmentOffset();
8578 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8579 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8580 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8582 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
8583 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8584 SegmentName.str().c_str(), SectionName.str().c_str(),
8585 Address, Entry.typeName().str().c_str());
8589 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8590 StringRef DylibName;
8592 case MachO::BIND_SPECIAL_DYLIB_SELF:
8593 return "this-image";
8594 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8595 return "main-executable";
8596 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8597 return "flat-namespace";
8600 std::error_code EC =
8601 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
8603 return "<<bad library ordinal>>";
8607 return "<<unknown special ordinal>>";
8610 //===----------------------------------------------------------------------===//
8611 // bind table dumping
8612 //===----------------------------------------------------------------------===//
8614 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8615 // Build table of sections so names can used in final output.
8616 SegInfo sectionTable(Obj);
8618 outs() << "segment section address type "
8619 "addend dylib symbol\n";
8620 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8621 uint32_t SegIndex = Entry.segmentIndex();
8622 uint64_t OffsetInSeg = Entry.segmentOffset();
8623 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8624 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8625 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8627 // Table lines look like:
8628 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
8630 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
8631 Attr = " (weak_import)";
8632 outs() << left_justify(SegmentName, 8) << " "
8633 << left_justify(SectionName, 18) << " "
8634 << format_hex(Address, 10, true) << " "
8635 << left_justify(Entry.typeName(), 8) << " "
8636 << format_decimal(Entry.addend(), 8) << " "
8637 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8638 << Entry.symbolName() << Attr << "\n";
8642 //===----------------------------------------------------------------------===//
8643 // lazy bind table dumping
8644 //===----------------------------------------------------------------------===//
8646 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8647 // Build table of sections so names can used in final output.
8648 SegInfo sectionTable(Obj);
8650 outs() << "segment section address "
8652 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8653 uint32_t SegIndex = Entry.segmentIndex();
8654 uint64_t OffsetInSeg = Entry.segmentOffset();
8655 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8656 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8657 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8659 // Table lines look like:
8660 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
8661 outs() << left_justify(SegmentName, 8) << " "
8662 << left_justify(SectionName, 18) << " "
8663 << format_hex(Address, 10, true) << " "
8664 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8665 << Entry.symbolName() << "\n";
8669 //===----------------------------------------------------------------------===//
8670 // weak bind table dumping
8671 //===----------------------------------------------------------------------===//
8673 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8674 // Build table of sections so names can used in final output.
8675 SegInfo sectionTable(Obj);
8677 outs() << "segment section address "
8678 "type addend symbol\n";
8679 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8680 // Strong symbols don't have a location to update.
8681 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
8682 outs() << " strong "
8683 << Entry.symbolName() << "\n";
8686 uint32_t SegIndex = Entry.segmentIndex();
8687 uint64_t OffsetInSeg = Entry.segmentOffset();
8688 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8689 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8690 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8692 // Table lines look like:
8693 // __DATA __data 0x00001000 pointer 0 _foo
8694 outs() << left_justify(SegmentName, 8) << " "
8695 << left_justify(SectionName, 18) << " "
8696 << format_hex(Address, 10, true) << " "
8697 << left_justify(Entry.typeName(), 8) << " "
8698 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8703 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
8704 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8705 // information for that address. If the address is found its binding symbol
8706 // name is returned. If not nullptr is returned.
8707 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8708 struct DisassembleInfo *info) {
8709 if (info->bindtable == nullptr) {
8710 info->bindtable = new (BindTable);
8711 SegInfo sectionTable(info->O);
8712 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8713 uint32_t SegIndex = Entry.segmentIndex();
8714 uint64_t OffsetInSeg = Entry.segmentOffset();
8715 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8716 const char *SymbolName = nullptr;
8717 StringRef name = Entry.symbolName();
8719 SymbolName = name.data();
8720 info->bindtable->push_back(std::make_pair(Address, SymbolName));
8723 for (bind_table_iterator BI = info->bindtable->begin(),
8724 BE = info->bindtable->end();
8726 uint64_t Address = BI->first;
8727 if (ReferenceValue == Address) {
8728 const char *SymbolName = BI->second;