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 Hi = (O->isLittleEndian()) ? l1 : l0;
670 Lo = (O->isLittleEndian()) ? l0 : l1;
672 // Hi is the high word, so this is equivalent to if(isfinite(d))
673 if ((Hi & 0x7ff00000) != 0x7ff00000)
674 outs() << format(" (%.16e)\n", d);
676 if (Hi == 0x7ff00000 && Lo == 0)
677 outs() << " (+Infinity)\n";
678 else if (Hi == 0xfff00000 && Lo == 0)
679 outs() << " (-Infinity)\n";
680 else if ((Hi & 0x00080000) == 0x00080000)
681 outs() << " (non-signaling Not-a-Number)\n";
683 outs() << " (signaling Not-a-Number)\n";
687 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
688 uint32_t sect_size, uint64_t sect_addr,
689 bool print_addresses) {
690 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
691 if (print_addresses) {
693 outs() << format("%016" PRIx64, sect_addr + i) << " ";
695 outs() << format("%08" PRIx64, sect_addr + i) << " ";
698 memcpy(&d, sect + i, sizeof(double));
699 if (O->isLittleEndian() != sys::IsLittleEndianHost)
700 sys::swapByteOrder(d);
702 memcpy(&l0, sect + i, sizeof(uint32_t));
703 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
704 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
705 sys::swapByteOrder(l0);
706 sys::swapByteOrder(l1);
708 DumpLiteral8(O, l0, l1, d);
712 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
713 outs() << format("0x%08" PRIx32, l0) << " ";
714 outs() << format("0x%08" PRIx32, l1) << " ";
715 outs() << format("0x%08" PRIx32, l2) << " ";
716 outs() << format("0x%08" PRIx32, l3) << "\n";
719 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
720 uint32_t sect_size, uint64_t sect_addr,
721 bool print_addresses) {
722 for (uint32_t i = 0; i < sect_size; i += 16) {
723 if (print_addresses) {
725 outs() << format("%016" PRIx64, sect_addr + i) << " ";
727 outs() << format("%08" PRIx64, sect_addr + i) << " ";
729 uint32_t l0, l1, l2, l3;
730 memcpy(&l0, sect + i, sizeof(uint32_t));
731 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
732 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
733 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
734 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
735 sys::swapByteOrder(l0);
736 sys::swapByteOrder(l1);
737 sys::swapByteOrder(l2);
738 sys::swapByteOrder(l3);
740 DumpLiteral16(l0, l1, l2, l3);
744 static void DumpLiteralPointerSection(MachOObjectFile *O,
745 const SectionRef &Section,
746 const char *sect, uint32_t sect_size,
748 bool print_addresses) {
749 // Collect the literal sections in this Mach-O file.
750 std::vector<SectionRef> LiteralSections;
751 for (const SectionRef &Section : O->sections()) {
752 DataRefImpl Ref = Section.getRawDataRefImpl();
753 uint32_t section_type;
755 const MachO::section_64 Sec = O->getSection64(Ref);
756 section_type = Sec.flags & MachO::SECTION_TYPE;
758 const MachO::section Sec = O->getSection(Ref);
759 section_type = Sec.flags & MachO::SECTION_TYPE;
761 if (section_type == MachO::S_CSTRING_LITERALS ||
762 section_type == MachO::S_4BYTE_LITERALS ||
763 section_type == MachO::S_8BYTE_LITERALS ||
764 section_type == MachO::S_16BYTE_LITERALS)
765 LiteralSections.push_back(Section);
768 // Set the size of the literal pointer.
769 uint32_t lp_size = O->is64Bit() ? 8 : 4;
771 // Collect the external relocation symbols for the literal pointers.
772 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
773 for (const RelocationRef &Reloc : Section.relocations()) {
775 MachO::any_relocation_info RE;
776 bool isExtern = false;
777 Rel = Reloc.getRawDataRefImpl();
778 RE = O->getRelocation(Rel);
779 isExtern = O->getPlainRelocationExternal(RE);
781 uint64_t RelocOffset = Reloc.getOffset();
782 symbol_iterator RelocSym = Reloc.getSymbol();
783 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
786 array_pod_sort(Relocs.begin(), Relocs.end());
788 // Dump each literal pointer.
789 for (uint32_t i = 0; i < sect_size; i += lp_size) {
790 if (print_addresses) {
792 outs() << format("%016" PRIx64, sect_addr + i) << " ";
794 outs() << format("%08" PRIx64, sect_addr + i) << " ";
798 memcpy(&lp, sect + i, sizeof(uint64_t));
799 if (O->isLittleEndian() != sys::IsLittleEndianHost)
800 sys::swapByteOrder(lp);
803 memcpy(&li, sect + i, sizeof(uint32_t));
804 if (O->isLittleEndian() != sys::IsLittleEndianHost)
805 sys::swapByteOrder(li);
809 // First look for an external relocation entry for this literal pointer.
810 auto Reloc = std::find_if(
811 Relocs.begin(), Relocs.end(),
812 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
813 if (Reloc != Relocs.end()) {
814 symbol_iterator RelocSym = Reloc->second;
815 ErrorOr<StringRef> SymName = RelocSym->getName();
816 if (std::error_code EC = SymName.getError())
817 report_fatal_error(EC.message());
818 outs() << "external relocation entry for symbol:" << *SymName << "\n";
822 // For local references see what the section the literal pointer points to.
823 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
824 [&](const SectionRef &R) {
825 return lp >= R.getAddress() &&
826 lp < R.getAddress() + R.getSize();
828 if (Sect == LiteralSections.end()) {
829 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
833 uint64_t SectAddress = Sect->getAddress();
834 uint64_t SectSize = Sect->getSize();
837 Sect->getName(SectName);
838 DataRefImpl Ref = Sect->getRawDataRefImpl();
839 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
840 outs() << SegmentName << ":" << SectName << ":";
842 uint32_t section_type;
844 const MachO::section_64 Sec = O->getSection64(Ref);
845 section_type = Sec.flags & MachO::SECTION_TYPE;
847 const MachO::section Sec = O->getSection(Ref);
848 section_type = Sec.flags & MachO::SECTION_TYPE;
852 Sect->getContents(BytesStr);
853 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
855 switch (section_type) {
856 case MachO::S_CSTRING_LITERALS:
857 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
859 DumpCstringChar(Contents[i]);
863 case MachO::S_4BYTE_LITERALS:
865 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
867 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
868 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
869 sys::swapByteOrder(f);
870 sys::swapByteOrder(l);
874 case MachO::S_8BYTE_LITERALS: {
876 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
878 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
879 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
881 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
882 sys::swapByteOrder(f);
883 sys::swapByteOrder(l0);
884 sys::swapByteOrder(l1);
886 DumpLiteral8(O, l0, l1, d);
889 case MachO::S_16BYTE_LITERALS: {
890 uint32_t l0, l1, l2, l3;
891 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
892 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
894 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
896 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
898 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
899 sys::swapByteOrder(l0);
900 sys::swapByteOrder(l1);
901 sys::swapByteOrder(l2);
902 sys::swapByteOrder(l3);
904 DumpLiteral16(l0, l1, l2, l3);
911 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
912 uint32_t sect_size, uint64_t sect_addr,
913 SymbolAddressMap *AddrMap,
917 stride = sizeof(uint64_t);
919 stride = sizeof(uint32_t);
920 for (uint32_t i = 0; i < sect_size; i += stride) {
921 const char *SymbolName = nullptr;
923 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
924 uint64_t pointer_value;
925 memcpy(&pointer_value, sect + i, stride);
926 if (O->isLittleEndian() != sys::IsLittleEndianHost)
927 sys::swapByteOrder(pointer_value);
928 outs() << format("0x%016" PRIx64, pointer_value);
930 SymbolName = GuessSymbolName(pointer_value, AddrMap);
932 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
933 uint32_t pointer_value;
934 memcpy(&pointer_value, sect + i, stride);
935 if (O->isLittleEndian() != sys::IsLittleEndianHost)
936 sys::swapByteOrder(pointer_value);
937 outs() << format("0x%08" PRIx32, pointer_value);
939 SymbolName = GuessSymbolName(pointer_value, AddrMap);
942 outs() << " " << SymbolName;
947 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
948 uint32_t size, uint64_t addr) {
949 uint32_t cputype = O->getHeader().cputype;
950 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
952 for (uint32_t i = 0; i < size; i += j, addr += j) {
954 outs() << format("%016" PRIx64, addr) << "\t";
956 outs() << format("%08" PRIx64, addr) << "\t";
957 for (j = 0; j < 16 && i + j < size; j++) {
958 uint8_t byte_word = *(sect + i + j);
959 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
965 for (uint32_t i = 0; i < size; i += j, addr += j) {
967 outs() << format("%016" PRIx64, addr) << "\t";
969 outs() << format("%08" PRIx64, sect) << "\t";
970 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
971 j += sizeof(int32_t)) {
972 if (i + j + sizeof(int32_t) < size) {
974 memcpy(&long_word, sect + i + j, sizeof(int32_t));
975 if (O->isLittleEndian() != sys::IsLittleEndianHost)
976 sys::swapByteOrder(long_word);
977 outs() << format("%08" PRIx32, long_word) << " ";
979 for (uint32_t k = 0; i + j + k < size; k++) {
980 uint8_t byte_word = *(sect + i + j);
981 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
990 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
991 StringRef DisSegName, StringRef DisSectName);
992 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
993 uint32_t size, uint32_t addr);
995 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
997 SymbolAddressMap AddrMap;
999 CreateSymbolAddressMap(O, &AddrMap);
1001 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1002 StringRef DumpSection = FilterSections[i];
1003 std::pair<StringRef, StringRef> DumpSegSectName;
1004 DumpSegSectName = DumpSection.split(',');
1005 StringRef DumpSegName, DumpSectName;
1006 if (DumpSegSectName.second.size()) {
1007 DumpSegName = DumpSegSectName.first;
1008 DumpSectName = DumpSegSectName.second;
1011 DumpSectName = DumpSegSectName.first;
1013 for (const SectionRef &Section : O->sections()) {
1015 Section.getName(SectName);
1016 DataRefImpl Ref = Section.getRawDataRefImpl();
1017 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1018 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1019 (SectName == DumpSectName)) {
1021 uint32_t section_flags;
1023 const MachO::section_64 Sec = O->getSection64(Ref);
1024 section_flags = Sec.flags;
1027 const MachO::section Sec = O->getSection(Ref);
1028 section_flags = Sec.flags;
1030 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1033 Section.getContents(BytesStr);
1034 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1035 uint32_t sect_size = BytesStr.size();
1036 uint64_t sect_addr = Section.getAddress();
1038 outs() << "Contents of (" << SegName << "," << SectName
1042 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1043 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1044 DisassembleMachO(Filename, O, SegName, SectName);
1047 if (SegName == "__TEXT" && SectName == "__info_plist") {
1051 if (SegName == "__OBJC" && SectName == "__protocol") {
1052 DumpProtocolSection(O, sect, sect_size, sect_addr);
1055 switch (section_type) {
1056 case MachO::S_REGULAR:
1057 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1059 case MachO::S_ZEROFILL:
1060 outs() << "zerofill section and has no contents in the file\n";
1062 case MachO::S_CSTRING_LITERALS:
1063 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1065 case MachO::S_4BYTE_LITERALS:
1066 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1068 case MachO::S_8BYTE_LITERALS:
1069 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1071 case MachO::S_16BYTE_LITERALS:
1072 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1074 case MachO::S_LITERAL_POINTERS:
1075 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1078 case MachO::S_MOD_INIT_FUNC_POINTERS:
1079 case MachO::S_MOD_TERM_FUNC_POINTERS:
1080 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1084 outs() << "Unknown section type ("
1085 << format("0x%08" PRIx32, section_type) << ")\n";
1086 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1090 if (section_type == MachO::S_ZEROFILL)
1091 outs() << "zerofill section and has no contents in the file\n";
1093 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1100 static void DumpInfoPlistSectionContents(StringRef Filename,
1101 MachOObjectFile *O) {
1102 for (const SectionRef &Section : O->sections()) {
1104 Section.getName(SectName);
1105 DataRefImpl Ref = Section.getRawDataRefImpl();
1106 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1107 if (SegName == "__TEXT" && SectName == "__info_plist") {
1108 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1110 Section.getContents(BytesStr);
1111 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1118 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1119 // and if it is and there is a list of architecture flags is specified then
1120 // check to make sure this Mach-O file is one of those architectures or all
1121 // architectures were specified. If not then an error is generated and this
1122 // routine returns false. Else it returns true.
1123 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1124 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1125 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1126 bool ArchFound = false;
1127 MachO::mach_header H;
1128 MachO::mach_header_64 H_64;
1130 if (MachO->is64Bit()) {
1131 H_64 = MachO->MachOObjectFile::getHeader64();
1132 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1134 H = MachO->MachOObjectFile::getHeader();
1135 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1138 for (i = 0; i < ArchFlags.size(); ++i) {
1139 if (ArchFlags[i] == T.getArchName())
1144 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1145 << "architecture: " + ArchFlags[i] + "\n";
1152 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1154 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1155 // archive member and or in a slice of a universal file. It prints the
1156 // the file name and header info and then processes it according to the
1157 // command line options.
1158 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1159 StringRef ArchiveMemberName = StringRef(),
1160 StringRef ArchitectureName = StringRef()) {
1161 // If we are doing some processing here on the Mach-O file print the header
1162 // info. And don't print it otherwise like in the case of printing the
1163 // UniversalHeaders or ArchiveHeaders.
1164 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
1165 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1166 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
1168 if (!ArchiveMemberName.empty())
1169 outs() << '(' << ArchiveMemberName << ')';
1170 if (!ArchitectureName.empty())
1171 outs() << " (architecture " << ArchitectureName << ")";
1176 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1177 if (IndirectSymbols)
1178 PrintIndirectSymbols(MachOOF, !NonVerbose);
1180 PrintDataInCodeTable(MachOOF, !NonVerbose);
1182 PrintLinkOptHints(MachOOF);
1184 PrintRelocations(MachOOF);
1186 PrintSectionHeaders(MachOOF);
1187 if (SectionContents)
1188 PrintSectionContents(MachOOF);
1189 if (FilterSections.size() != 0)
1190 DumpSectionContents(Filename, MachOOF, !NonVerbose);
1192 DumpInfoPlistSectionContents(Filename, MachOOF);
1194 PrintDylibs(MachOOF, false);
1196 PrintDylibs(MachOOF, true);
1198 PrintSymbolTable(MachOOF);
1200 printMachOUnwindInfo(MachOOF);
1202 printMachOFileHeader(MachOOF);
1204 printObjcMetaData(MachOOF, !NonVerbose);
1206 printExportsTrie(MachOOF);
1208 printRebaseTable(MachOOF);
1210 printBindTable(MachOOF);
1212 printLazyBindTable(MachOOF);
1214 printWeakBindTable(MachOOF);
1217 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1218 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1219 outs() << " cputype (" << cputype << ")\n";
1220 outs() << " cpusubtype (" << cpusubtype << ")\n";
1223 // printCPUType() helps print_fat_headers by printing the cputype and
1224 // pusubtype (symbolically for the one's it knows about).
1225 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1227 case MachO::CPU_TYPE_I386:
1228 switch (cpusubtype) {
1229 case MachO::CPU_SUBTYPE_I386_ALL:
1230 outs() << " cputype CPU_TYPE_I386\n";
1231 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1234 printUnknownCPUType(cputype, cpusubtype);
1238 case MachO::CPU_TYPE_X86_64:
1239 switch (cpusubtype) {
1240 case MachO::CPU_SUBTYPE_X86_64_ALL:
1241 outs() << " cputype CPU_TYPE_X86_64\n";
1242 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1244 case MachO::CPU_SUBTYPE_X86_64_H:
1245 outs() << " cputype CPU_TYPE_X86_64\n";
1246 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1249 printUnknownCPUType(cputype, cpusubtype);
1253 case MachO::CPU_TYPE_ARM:
1254 switch (cpusubtype) {
1255 case MachO::CPU_SUBTYPE_ARM_ALL:
1256 outs() << " cputype CPU_TYPE_ARM\n";
1257 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1259 case MachO::CPU_SUBTYPE_ARM_V4T:
1260 outs() << " cputype CPU_TYPE_ARM\n";
1261 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1263 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1264 outs() << " cputype CPU_TYPE_ARM\n";
1265 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1267 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1268 outs() << " cputype CPU_TYPE_ARM\n";
1269 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1271 case MachO::CPU_SUBTYPE_ARM_V6:
1272 outs() << " cputype CPU_TYPE_ARM\n";
1273 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1275 case MachO::CPU_SUBTYPE_ARM_V6M:
1276 outs() << " cputype CPU_TYPE_ARM\n";
1277 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1279 case MachO::CPU_SUBTYPE_ARM_V7:
1280 outs() << " cputype CPU_TYPE_ARM\n";
1281 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1283 case MachO::CPU_SUBTYPE_ARM_V7EM:
1284 outs() << " cputype CPU_TYPE_ARM\n";
1285 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1287 case MachO::CPU_SUBTYPE_ARM_V7K:
1288 outs() << " cputype CPU_TYPE_ARM\n";
1289 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1291 case MachO::CPU_SUBTYPE_ARM_V7M:
1292 outs() << " cputype CPU_TYPE_ARM\n";
1293 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1295 case MachO::CPU_SUBTYPE_ARM_V7S:
1296 outs() << " cputype CPU_TYPE_ARM\n";
1297 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1300 printUnknownCPUType(cputype, cpusubtype);
1304 case MachO::CPU_TYPE_ARM64:
1305 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1306 case MachO::CPU_SUBTYPE_ARM64_ALL:
1307 outs() << " cputype CPU_TYPE_ARM64\n";
1308 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1311 printUnknownCPUType(cputype, cpusubtype);
1316 printUnknownCPUType(cputype, cpusubtype);
1321 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1323 outs() << "Fat headers\n";
1325 outs() << "fat_magic FAT_MAGIC\n";
1327 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1329 uint32_t nfat_arch = UB->getNumberOfObjects();
1330 StringRef Buf = UB->getData();
1331 uint64_t size = Buf.size();
1332 uint64_t big_size = sizeof(struct MachO::fat_header) +
1333 nfat_arch * sizeof(struct MachO::fat_arch);
1334 outs() << "nfat_arch " << UB->getNumberOfObjects();
1336 outs() << " (malformed, contains zero architecture types)\n";
1337 else if (big_size > size)
1338 outs() << " (malformed, architectures past end of file)\n";
1342 for (uint32_t i = 0; i < nfat_arch; ++i) {
1343 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1344 uint32_t cputype = OFA.getCPUType();
1345 uint32_t cpusubtype = OFA.getCPUSubType();
1346 outs() << "architecture ";
1347 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1348 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1349 uint32_t other_cputype = other_OFA.getCPUType();
1350 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1351 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1352 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1353 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1354 outs() << "(illegal duplicate architecture) ";
1359 outs() << OFA.getArchTypeName() << "\n";
1360 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1362 outs() << i << "\n";
1363 outs() << " cputype " << cputype << "\n";
1364 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1368 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1369 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1371 outs() << " capabilities "
1372 << format("0x%" PRIx32,
1373 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1374 outs() << " offset " << OFA.getOffset();
1375 if (OFA.getOffset() > size)
1376 outs() << " (past end of file)";
1377 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1378 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1380 outs() << " size " << OFA.getSize();
1381 big_size = OFA.getOffset() + OFA.getSize();
1382 if (big_size > size)
1383 outs() << " (past end of file)";
1385 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1390 static void printArchiveChild(const Archive::Child &C, bool verbose,
1391 bool print_offset) {
1393 outs() << C.getChildOffset() << "\t";
1394 sys::fs::perms Mode = C.getAccessMode();
1396 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1397 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1399 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1400 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1401 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1402 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1403 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1404 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1405 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1406 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1407 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1409 outs() << format("0%o ", Mode);
1412 unsigned UID = C.getUID();
1413 outs() << format("%3d/", UID);
1414 unsigned GID = C.getGID();
1415 outs() << format("%-3d ", GID);
1416 ErrorOr<uint64_t> Size = C.getRawSize();
1417 if (std::error_code EC = Size.getError())
1418 report_fatal_error(EC.message());
1419 outs() << format("%5" PRId64, Size.get()) << " ";
1421 StringRef RawLastModified = C.getRawLastModified();
1424 if (RawLastModified.getAsInteger(10, Seconds))
1425 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1427 // Since cime(3) returns a 26 character string of the form:
1428 // "Sun Sep 16 01:03:52 1973\n\0"
1429 // just print 24 characters.
1431 outs() << format("%.24s ", ctime(&t));
1434 outs() << RawLastModified << " ";
1438 ErrorOr<StringRef> NameOrErr = C.getName();
1439 if (NameOrErr.getError()) {
1440 StringRef RawName = C.getRawName();
1441 outs() << RawName << "\n";
1443 StringRef Name = NameOrErr.get();
1444 outs() << Name << "\n";
1447 StringRef RawName = C.getRawName();
1448 outs() << RawName << "\n";
1452 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1453 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1455 if (std::error_code EC = I->getError())
1456 report_fatal_error(EC.message());
1457 const Archive::Child &C = **I;
1458 printArchiveChild(C, verbose, print_offset);
1462 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1463 // -arch flags selecting just those slices as specified by them and also parses
1464 // archive files. Then for each individual Mach-O file ProcessMachO() is
1465 // called to process the file based on the command line options.
1466 void llvm::ParseInputMachO(StringRef Filename) {
1467 // Check for -arch all and verifiy the -arch flags are valid.
1468 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1469 if (ArchFlags[i] == "all") {
1472 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1473 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1474 "'for the -arch option\n";
1480 // Attempt to open the binary.
1481 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1482 if (std::error_code EC = BinaryOrErr.getError()) {
1483 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
1486 Binary &Bin = *BinaryOrErr.get().getBinary();
1488 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1489 outs() << "Archive : " << Filename << "\n";
1491 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
1492 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1494 if (std::error_code EC = I->getError())
1495 report_error(Filename, EC);
1497 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1498 if (ChildOrErr.getError())
1500 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1501 if (!checkMachOAndArchFlags(O, Filename))
1503 ProcessMachO(Filename, O, O->getFileName());
1508 if (UniversalHeaders) {
1509 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1510 printMachOUniversalHeaders(UB, !NonVerbose);
1512 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1513 // If we have a list of architecture flags specified dump only those.
1514 if (!ArchAll && ArchFlags.size() != 0) {
1515 // Look for a slice in the universal binary that matches each ArchFlag.
1517 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1519 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1520 E = UB->end_objects();
1522 if (ArchFlags[i] == I->getArchTypeName()) {
1524 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1525 I->getAsObjectFile();
1526 std::string ArchitectureName = "";
1527 if (ArchFlags.size() > 1)
1528 ArchitectureName = I->getArchTypeName();
1530 ObjectFile &O = *ObjOrErr.get();
1531 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1532 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1533 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1534 I->getAsArchive()) {
1535 std::unique_ptr<Archive> &A = *AOrErr;
1536 outs() << "Archive : " << Filename;
1537 if (!ArchitectureName.empty())
1538 outs() << " (architecture " << ArchitectureName << ")";
1541 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1542 for (Archive::child_iterator AI = A->child_begin(),
1543 AE = A->child_end();
1545 if (std::error_code EC = AI->getError())
1546 report_error(Filename, EC);
1547 auto &C = AI->get();
1548 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1549 if (ChildOrErr.getError())
1551 if (MachOObjectFile *O =
1552 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1553 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1559 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1560 << "architecture: " + ArchFlags[i] + "\n";
1566 // No architecture flags were specified so if this contains a slice that
1567 // matches the host architecture dump only that.
1569 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1570 E = UB->end_objects();
1572 if (MachOObjectFile::getHostArch().getArchName() ==
1573 I->getArchTypeName()) {
1574 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1575 std::string ArchiveName;
1576 ArchiveName.clear();
1578 ObjectFile &O = *ObjOrErr.get();
1579 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1580 ProcessMachO(Filename, MachOOF);
1581 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1582 I->getAsArchive()) {
1583 std::unique_ptr<Archive> &A = *AOrErr;
1584 outs() << "Archive : " << Filename << "\n";
1586 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1587 for (Archive::child_iterator AI = A->child_begin(),
1588 AE = A->child_end();
1590 if (std::error_code EC = AI->getError())
1591 report_error(Filename, EC);
1592 auto &C = AI->get();
1593 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1594 if (ChildOrErr.getError())
1596 if (MachOObjectFile *O =
1597 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1598 ProcessMachO(Filename, O, O->getFileName());
1605 // Either all architectures have been specified or none have been specified
1606 // and this does not contain the host architecture so dump all the slices.
1607 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1608 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1609 E = UB->end_objects();
1611 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1612 std::string ArchitectureName = "";
1613 if (moreThanOneArch)
1614 ArchitectureName = I->getArchTypeName();
1616 ObjectFile &Obj = *ObjOrErr.get();
1617 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1618 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1619 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1620 std::unique_ptr<Archive> &A = *AOrErr;
1621 outs() << "Archive : " << Filename;
1622 if (!ArchitectureName.empty())
1623 outs() << " (architecture " << ArchitectureName << ")";
1626 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1627 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1629 if (std::error_code EC = AI->getError())
1630 report_error(Filename, EC);
1631 auto &C = AI->get();
1632 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1633 if (ChildOrErr.getError())
1635 if (MachOObjectFile *O =
1636 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1637 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1638 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1646 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1647 if (!checkMachOAndArchFlags(O, Filename))
1649 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1650 ProcessMachO(Filename, MachOOF);
1652 errs() << "llvm-objdump: '" << Filename << "': "
1653 << "Object is not a Mach-O file type.\n";
1655 errs() << "llvm-objdump: '" << Filename << "': "
1656 << "Unrecognized file type.\n";
1659 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1660 typedef std::vector<BindInfoEntry> BindTable;
1661 typedef BindTable::iterator bind_table_iterator;
1663 // The block of info used by the Symbolizer call backs.
1664 struct DisassembleInfo {
1668 SymbolAddressMap *AddrMap;
1669 std::vector<SectionRef> *Sections;
1670 const char *class_name;
1671 const char *selector_name;
1673 char *demangled_name;
1676 BindTable *bindtable;
1680 // SymbolizerGetOpInfo() is the operand information call back function.
1681 // This is called to get the symbolic information for operand(s) of an
1682 // instruction when it is being done. This routine does this from
1683 // the relocation information, symbol table, etc. That block of information
1684 // is a pointer to the struct DisassembleInfo that was passed when the
1685 // disassembler context was created and passed to back to here when
1686 // called back by the disassembler for instruction operands that could have
1687 // relocation information. The address of the instruction containing operand is
1688 // at the Pc parameter. The immediate value the operand has is passed in
1689 // op_info->Value and is at Offset past the start of the instruction and has a
1690 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1691 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1692 // names and addends of the symbolic expression to add for the operand. The
1693 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1694 // information is returned then this function returns 1 else it returns 0.
1695 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1696 uint64_t Size, int TagType, void *TagBuf) {
1697 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1698 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1699 uint64_t value = op_info->Value;
1701 // Make sure all fields returned are zero if we don't set them.
1702 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1703 op_info->Value = value;
1705 // If the TagType is not the value 1 which it code knows about or if no
1706 // verbose symbolic information is wanted then just return 0, indicating no
1707 // information is being returned.
1708 if (TagType != 1 || !info->verbose)
1711 unsigned int Arch = info->O->getArch();
1712 if (Arch == Triple::x86) {
1713 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1715 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1717 // Search the external relocation entries of a fully linked image
1718 // (if any) for an entry that matches this segment offset.
1719 // uint32_t seg_offset = (Pc + Offset);
1722 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1723 // for an entry for this section offset.
1724 uint32_t sect_addr = info->S.getAddress();
1725 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1726 bool reloc_found = false;
1728 MachO::any_relocation_info RE;
1729 bool isExtern = false;
1731 bool r_scattered = false;
1732 uint32_t r_value, pair_r_value, r_type;
1733 for (const RelocationRef &Reloc : info->S.relocations()) {
1734 uint64_t RelocOffset = Reloc.getOffset();
1735 if (RelocOffset == sect_offset) {
1736 Rel = Reloc.getRawDataRefImpl();
1737 RE = info->O->getRelocation(Rel);
1738 r_type = info->O->getAnyRelocationType(RE);
1739 r_scattered = info->O->isRelocationScattered(RE);
1741 r_value = info->O->getScatteredRelocationValue(RE);
1742 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1743 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1744 DataRefImpl RelNext = Rel;
1745 info->O->moveRelocationNext(RelNext);
1746 MachO::any_relocation_info RENext;
1747 RENext = info->O->getRelocation(RelNext);
1748 if (info->O->isRelocationScattered(RENext))
1749 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1754 isExtern = info->O->getPlainRelocationExternal(RE);
1756 symbol_iterator RelocSym = Reloc.getSymbol();
1764 if (reloc_found && isExtern) {
1765 ErrorOr<StringRef> SymName = Symbol.getName();
1766 if (std::error_code EC = SymName.getError())
1767 report_fatal_error(EC.message());
1768 const char *name = SymName->data();
1769 op_info->AddSymbol.Present = 1;
1770 op_info->AddSymbol.Name = name;
1771 // For i386 extern relocation entries the value in the instruction is
1772 // the offset from the symbol, and value is already set in op_info->Value.
1775 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1776 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1777 const char *add = GuessSymbolName(r_value, info->AddrMap);
1778 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1779 uint32_t offset = value - (r_value - pair_r_value);
1780 op_info->AddSymbol.Present = 1;
1782 op_info->AddSymbol.Name = add;
1784 op_info->AddSymbol.Value = r_value;
1785 op_info->SubtractSymbol.Present = 1;
1787 op_info->SubtractSymbol.Name = sub;
1789 op_info->SubtractSymbol.Value = pair_r_value;
1790 op_info->Value = offset;
1795 if (Arch == Triple::x86_64) {
1796 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1798 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1800 // Search the external relocation entries of a fully linked image
1801 // (if any) for an entry that matches this segment offset.
1802 // uint64_t seg_offset = (Pc + Offset);
1805 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1806 // for an entry for this section offset.
1807 uint64_t sect_addr = info->S.getAddress();
1808 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1809 bool reloc_found = false;
1811 MachO::any_relocation_info RE;
1812 bool isExtern = false;
1814 for (const RelocationRef &Reloc : info->S.relocations()) {
1815 uint64_t RelocOffset = Reloc.getOffset();
1816 if (RelocOffset == sect_offset) {
1817 Rel = Reloc.getRawDataRefImpl();
1818 RE = info->O->getRelocation(Rel);
1819 // NOTE: Scattered relocations don't exist on x86_64.
1820 isExtern = info->O->getPlainRelocationExternal(RE);
1822 symbol_iterator RelocSym = Reloc.getSymbol();
1829 if (reloc_found && isExtern) {
1830 // The Value passed in will be adjusted by the Pc if the instruction
1831 // adds the Pc. But for x86_64 external relocation entries the Value
1832 // is the offset from the external symbol.
1833 if (info->O->getAnyRelocationPCRel(RE))
1834 op_info->Value -= Pc + Offset + Size;
1835 ErrorOr<StringRef> SymName = Symbol.getName();
1836 if (std::error_code EC = SymName.getError())
1837 report_fatal_error(EC.message());
1838 const char *name = SymName->data();
1839 unsigned Type = info->O->getAnyRelocationType(RE);
1840 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1841 DataRefImpl RelNext = Rel;
1842 info->O->moveRelocationNext(RelNext);
1843 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1844 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1845 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1846 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1847 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1848 op_info->SubtractSymbol.Present = 1;
1849 op_info->SubtractSymbol.Name = name;
1850 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1851 Symbol = *RelocSymNext;
1852 ErrorOr<StringRef> SymNameNext = Symbol.getName();
1853 if (std::error_code EC = SymNameNext.getError())
1854 report_fatal_error(EC.message());
1855 name = SymNameNext->data();
1858 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1859 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1860 op_info->AddSymbol.Present = 1;
1861 op_info->AddSymbol.Name = name;
1866 if (Arch == Triple::arm) {
1867 if (Offset != 0 || (Size != 4 && Size != 2))
1869 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1871 // Search the external relocation entries of a fully linked image
1872 // (if any) for an entry that matches this segment offset.
1873 // uint32_t seg_offset = (Pc + Offset);
1876 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1877 // for an entry for this section offset.
1878 uint32_t sect_addr = info->S.getAddress();
1879 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1881 MachO::any_relocation_info RE;
1882 bool isExtern = false;
1884 bool r_scattered = false;
1885 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1887 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1888 [&](const RelocationRef &Reloc) {
1889 uint64_t RelocOffset = Reloc.getOffset();
1890 return RelocOffset == sect_offset;
1893 if (Reloc == info->S.relocations().end())
1896 Rel = Reloc->getRawDataRefImpl();
1897 RE = info->O->getRelocation(Rel);
1898 r_length = info->O->getAnyRelocationLength(RE);
1899 r_scattered = info->O->isRelocationScattered(RE);
1901 r_value = info->O->getScatteredRelocationValue(RE);
1902 r_type = info->O->getScatteredRelocationType(RE);
1904 r_type = info->O->getAnyRelocationType(RE);
1905 isExtern = info->O->getPlainRelocationExternal(RE);
1907 symbol_iterator RelocSym = Reloc->getSymbol();
1911 if (r_type == MachO::ARM_RELOC_HALF ||
1912 r_type == MachO::ARM_RELOC_SECTDIFF ||
1913 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1914 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1915 DataRefImpl RelNext = Rel;
1916 info->O->moveRelocationNext(RelNext);
1917 MachO::any_relocation_info RENext;
1918 RENext = info->O->getRelocation(RelNext);
1919 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1920 if (info->O->isRelocationScattered(RENext))
1921 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1925 ErrorOr<StringRef> SymName = Symbol.getName();
1926 if (std::error_code EC = SymName.getError())
1927 report_fatal_error(EC.message());
1928 const char *name = SymName->data();
1929 op_info->AddSymbol.Present = 1;
1930 op_info->AddSymbol.Name = name;
1932 case MachO::ARM_RELOC_HALF:
1933 if ((r_length & 0x1) == 1) {
1934 op_info->Value = value << 16 | other_half;
1935 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1937 op_info->Value = other_half << 16 | value;
1938 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1946 // If we have a branch that is not an external relocation entry then
1947 // return 0 so the code in tryAddingSymbolicOperand() can use the
1948 // SymbolLookUp call back with the branch target address to look up the
1949 // symbol and possiblity add an annotation for a symbol stub.
1950 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1951 r_type == MachO::ARM_THUMB_RELOC_BR22))
1954 uint32_t offset = 0;
1955 if (r_type == MachO::ARM_RELOC_HALF ||
1956 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1957 if ((r_length & 0x1) == 1)
1958 value = value << 16 | other_half;
1960 value = other_half << 16 | value;
1962 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1963 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1964 offset = value - r_value;
1968 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1969 if ((r_length & 0x1) == 1)
1970 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1972 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1973 const char *add = GuessSymbolName(r_value, info->AddrMap);
1974 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1975 int32_t offset = value - (r_value - pair_r_value);
1976 op_info->AddSymbol.Present = 1;
1978 op_info->AddSymbol.Name = add;
1980 op_info->AddSymbol.Value = r_value;
1981 op_info->SubtractSymbol.Present = 1;
1983 op_info->SubtractSymbol.Name = sub;
1985 op_info->SubtractSymbol.Value = pair_r_value;
1986 op_info->Value = offset;
1990 op_info->AddSymbol.Present = 1;
1991 op_info->Value = offset;
1992 if (r_type == MachO::ARM_RELOC_HALF) {
1993 if ((r_length & 0x1) == 1)
1994 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1996 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1998 const char *add = GuessSymbolName(value, info->AddrMap);
1999 if (add != nullptr) {
2000 op_info->AddSymbol.Name = add;
2003 op_info->AddSymbol.Value = value;
2006 if (Arch == Triple::aarch64) {
2007 if (Offset != 0 || Size != 4)
2009 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2011 // Search the external relocation entries of a fully linked image
2012 // (if any) for an entry that matches this segment offset.
2013 // uint64_t seg_offset = (Pc + Offset);
2016 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2017 // for an entry for this section offset.
2018 uint64_t sect_addr = info->S.getAddress();
2019 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2021 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2022 [&](const RelocationRef &Reloc) {
2023 uint64_t RelocOffset = Reloc.getOffset();
2024 return RelocOffset == sect_offset;
2027 if (Reloc == info->S.relocations().end())
2030 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2031 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2032 uint32_t r_type = info->O->getAnyRelocationType(RE);
2033 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2034 DataRefImpl RelNext = Rel;
2035 info->O->moveRelocationNext(RelNext);
2036 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2038 value = info->O->getPlainRelocationSymbolNum(RENext);
2039 op_info->Value = value;
2042 // NOTE: Scattered relocations don't exist on arm64.
2043 if (!info->O->getPlainRelocationExternal(RE))
2045 ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
2046 if (std::error_code EC = SymName.getError())
2047 report_fatal_error(EC.message());
2048 const char *name = SymName->data();
2049 op_info->AddSymbol.Present = 1;
2050 op_info->AddSymbol.Name = name;
2053 case MachO::ARM64_RELOC_PAGE21:
2055 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2057 case MachO::ARM64_RELOC_PAGEOFF12:
2059 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2061 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2063 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2065 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2067 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2069 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2070 /* @tvlppage is not implemented in llvm-mc */
2071 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2073 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2074 /* @tvlppageoff is not implemented in llvm-mc */
2075 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2078 case MachO::ARM64_RELOC_BRANCH26:
2079 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2087 // GuessCstringPointer is passed the address of what might be a pointer to a
2088 // literal string in a cstring section. If that address is in a cstring section
2089 // it returns a pointer to that string. Else it returns nullptr.
2090 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2091 struct DisassembleInfo *info) {
2092 for (const auto &Load : info->O->load_commands()) {
2093 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2094 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2095 for (unsigned J = 0; J < Seg.nsects; ++J) {
2096 MachO::section_64 Sec = info->O->getSection64(Load, J);
2097 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2098 if (section_type == MachO::S_CSTRING_LITERALS &&
2099 ReferenceValue >= Sec.addr &&
2100 ReferenceValue < Sec.addr + Sec.size) {
2101 uint64_t sect_offset = ReferenceValue - Sec.addr;
2102 uint64_t object_offset = Sec.offset + sect_offset;
2103 StringRef MachOContents = info->O->getData();
2104 uint64_t object_size = MachOContents.size();
2105 const char *object_addr = (const char *)MachOContents.data();
2106 if (object_offset < object_size) {
2107 const char *name = object_addr + object_offset;
2114 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2115 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2116 for (unsigned J = 0; J < Seg.nsects; ++J) {
2117 MachO::section Sec = info->O->getSection(Load, J);
2118 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2119 if (section_type == MachO::S_CSTRING_LITERALS &&
2120 ReferenceValue >= Sec.addr &&
2121 ReferenceValue < Sec.addr + Sec.size) {
2122 uint64_t sect_offset = ReferenceValue - Sec.addr;
2123 uint64_t object_offset = Sec.offset + sect_offset;
2124 StringRef MachOContents = info->O->getData();
2125 uint64_t object_size = MachOContents.size();
2126 const char *object_addr = (const char *)MachOContents.data();
2127 if (object_offset < object_size) {
2128 const char *name = object_addr + object_offset;
2140 // GuessIndirectSymbol returns the name of the indirect symbol for the
2141 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2142 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2143 // symbol name being referenced by the stub or pointer.
2144 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2145 struct DisassembleInfo *info) {
2146 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2147 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2148 for (const auto &Load : info->O->load_commands()) {
2149 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2150 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2151 for (unsigned J = 0; J < Seg.nsects; ++J) {
2152 MachO::section_64 Sec = info->O->getSection64(Load, J);
2153 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2154 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2155 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2156 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2157 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2158 section_type == MachO::S_SYMBOL_STUBS) &&
2159 ReferenceValue >= Sec.addr &&
2160 ReferenceValue < Sec.addr + Sec.size) {
2162 if (section_type == MachO::S_SYMBOL_STUBS)
2163 stride = Sec.reserved2;
2168 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2169 if (index < Dysymtab.nindirectsyms) {
2170 uint32_t indirect_symbol =
2171 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2172 if (indirect_symbol < Symtab.nsyms) {
2173 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2174 SymbolRef Symbol = *Sym;
2175 ErrorOr<StringRef> SymName = Symbol.getName();
2176 if (std::error_code EC = SymName.getError())
2177 report_fatal_error(EC.message());
2178 const char *name = SymName->data();
2184 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2185 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2186 for (unsigned J = 0; J < Seg.nsects; ++J) {
2187 MachO::section Sec = info->O->getSection(Load, J);
2188 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2189 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2190 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2191 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2192 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2193 section_type == MachO::S_SYMBOL_STUBS) &&
2194 ReferenceValue >= Sec.addr &&
2195 ReferenceValue < Sec.addr + Sec.size) {
2197 if (section_type == MachO::S_SYMBOL_STUBS)
2198 stride = Sec.reserved2;
2203 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2204 if (index < Dysymtab.nindirectsyms) {
2205 uint32_t indirect_symbol =
2206 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2207 if (indirect_symbol < Symtab.nsyms) {
2208 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2209 SymbolRef Symbol = *Sym;
2210 ErrorOr<StringRef> SymName = Symbol.getName();
2211 if (std::error_code EC = SymName.getError())
2212 report_fatal_error(EC.message());
2213 const char *name = SymName->data();
2224 // method_reference() is called passing it the ReferenceName that might be
2225 // a reference it to an Objective-C method call. If so then it allocates and
2226 // assembles a method call string with the values last seen and saved in
2227 // the DisassembleInfo's class_name and selector_name fields. This is saved
2228 // into the method field of the info and any previous string is free'ed.
2229 // Then the class_name field in the info is set to nullptr. The method call
2230 // string is set into ReferenceName and ReferenceType is set to
2231 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2232 // then both ReferenceType and ReferenceName are left unchanged.
2233 static void method_reference(struct DisassembleInfo *info,
2234 uint64_t *ReferenceType,
2235 const char **ReferenceName) {
2236 unsigned int Arch = info->O->getArch();
2237 if (*ReferenceName != nullptr) {
2238 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2239 if (info->selector_name != nullptr) {
2240 if (info->method != nullptr)
2242 if (info->class_name != nullptr) {
2243 info->method = (char *)malloc(5 + strlen(info->class_name) +
2244 strlen(info->selector_name));
2245 if (info->method != nullptr) {
2246 strcpy(info->method, "+[");
2247 strcat(info->method, info->class_name);
2248 strcat(info->method, " ");
2249 strcat(info->method, info->selector_name);
2250 strcat(info->method, "]");
2251 *ReferenceName = info->method;
2252 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2255 info->method = (char *)malloc(9 + strlen(info->selector_name));
2256 if (info->method != nullptr) {
2257 if (Arch == Triple::x86_64)
2258 strcpy(info->method, "-[%rdi ");
2259 else if (Arch == Triple::aarch64)
2260 strcpy(info->method, "-[x0 ");
2262 strcpy(info->method, "-[r? ");
2263 strcat(info->method, info->selector_name);
2264 strcat(info->method, "]");
2265 *ReferenceName = info->method;
2266 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2269 info->class_name = nullptr;
2271 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2272 if (info->selector_name != nullptr) {
2273 if (info->method != nullptr)
2275 info->method = (char *)malloc(17 + strlen(info->selector_name));
2276 if (info->method != nullptr) {
2277 if (Arch == Triple::x86_64)
2278 strcpy(info->method, "-[[%rdi super] ");
2279 else if (Arch == Triple::aarch64)
2280 strcpy(info->method, "-[[x0 super] ");
2282 strcpy(info->method, "-[[r? super] ");
2283 strcat(info->method, info->selector_name);
2284 strcat(info->method, "]");
2285 *ReferenceName = info->method;
2286 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2288 info->class_name = nullptr;
2294 // GuessPointerPointer() is passed the address of what might be a pointer to
2295 // a reference to an Objective-C class, selector, message ref or cfstring.
2296 // If so the value of the pointer is returned and one of the booleans are set
2297 // to true. If not zero is returned and all the booleans are set to false.
2298 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2299 struct DisassembleInfo *info,
2300 bool &classref, bool &selref, bool &msgref,
2306 for (const auto &Load : info->O->load_commands()) {
2307 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2308 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2309 for (unsigned J = 0; J < Seg.nsects; ++J) {
2310 MachO::section_64 Sec = info->O->getSection64(Load, J);
2311 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2312 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2313 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2314 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2315 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2316 ReferenceValue >= Sec.addr &&
2317 ReferenceValue < Sec.addr + Sec.size) {
2318 uint64_t sect_offset = ReferenceValue - Sec.addr;
2319 uint64_t object_offset = Sec.offset + sect_offset;
2320 StringRef MachOContents = info->O->getData();
2321 uint64_t object_size = MachOContents.size();
2322 const char *object_addr = (const char *)MachOContents.data();
2323 if (object_offset < object_size) {
2324 uint64_t pointer_value;
2325 memcpy(&pointer_value, object_addr + object_offset,
2327 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2328 sys::swapByteOrder(pointer_value);
2329 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2331 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2332 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2334 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2335 ReferenceValue + 8 < Sec.addr + Sec.size) {
2337 memcpy(&pointer_value, object_addr + object_offset + 8,
2339 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2340 sys::swapByteOrder(pointer_value);
2341 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2343 return pointer_value;
2350 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2355 // get_pointer_64 returns a pointer to the bytes in the object file at the
2356 // Address from a section in the Mach-O file. And indirectly returns the
2357 // offset into the section, number of bytes left in the section past the offset
2358 // and which section is was being referenced. If the Address is not in a
2359 // section nullptr is returned.
2360 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2361 uint32_t &left, SectionRef &S,
2362 DisassembleInfo *info,
2363 bool objc_only = false) {
2367 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2368 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2369 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2374 ((*(info->Sections))[SectIdx]).getName(SectName);
2375 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2376 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2377 if (SegName != "__OBJC" && SectName != "__cstring")
2380 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2381 S = (*(info->Sections))[SectIdx];
2382 offset = Address - SectAddress;
2383 left = SectSize - offset;
2384 StringRef SectContents;
2385 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2386 return SectContents.data() + offset;
2392 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2393 uint32_t &left, SectionRef &S,
2394 DisassembleInfo *info,
2395 bool objc_only = false) {
2396 return get_pointer_64(Address, offset, left, S, info, objc_only);
2399 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2400 // the symbol indirectly through n_value. Based on the relocation information
2401 // for the specified section offset in the specified section reference.
2402 // If no relocation information is found and a non-zero ReferenceValue for the
2403 // symbol is passed, look up that address in the info's AddrMap.
2404 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2405 DisassembleInfo *info, uint64_t &n_value,
2406 uint64_t ReferenceValue = 0) {
2411 // See if there is an external relocation entry at the sect_offset.
2412 bool reloc_found = false;
2414 MachO::any_relocation_info RE;
2415 bool isExtern = false;
2417 for (const RelocationRef &Reloc : S.relocations()) {
2418 uint64_t RelocOffset = Reloc.getOffset();
2419 if (RelocOffset == sect_offset) {
2420 Rel = Reloc.getRawDataRefImpl();
2421 RE = info->O->getRelocation(Rel);
2422 if (info->O->isRelocationScattered(RE))
2424 isExtern = info->O->getPlainRelocationExternal(RE);
2426 symbol_iterator RelocSym = Reloc.getSymbol();
2433 // If there is an external relocation entry for a symbol in this section
2434 // at this section_offset then use that symbol's value for the n_value
2435 // and return its name.
2436 const char *SymbolName = nullptr;
2437 if (reloc_found && isExtern) {
2438 n_value = Symbol.getValue();
2439 ErrorOr<StringRef> NameOrError = Symbol.getName();
2440 if (std::error_code EC = NameOrError.getError())
2441 report_fatal_error(EC.message());
2442 StringRef Name = *NameOrError;
2443 if (!Name.empty()) {
2444 SymbolName = Name.data();
2449 // TODO: For fully linked images, look through the external relocation
2450 // entries off the dynamic symtab command. For these the r_offset is from the
2451 // start of the first writeable segment in the Mach-O file. So the offset
2452 // to this section from that segment is passed to this routine by the caller,
2453 // as the database_offset. Which is the difference of the section's starting
2454 // address and the first writable segment.
2456 // NOTE: need add passing the database_offset to this routine.
2458 // We did not find an external relocation entry so look up the ReferenceValue
2459 // as an address of a symbol and if found return that symbol's name.
2460 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2465 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2466 DisassembleInfo *info,
2467 uint32_t ReferenceValue) {
2469 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2472 // These are structs in the Objective-C meta data and read to produce the
2473 // comments for disassembly. While these are part of the ABI they are no
2474 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2476 // The cfstring object in a 64-bit Mach-O file.
2477 struct cfstring64_t {
2478 uint64_t isa; // class64_t * (64-bit pointer)
2479 uint64_t flags; // flag bits
2480 uint64_t characters; // char * (64-bit pointer)
2481 uint64_t length; // number of non-NULL characters in above
2484 // The class object in a 64-bit Mach-O file.
2486 uint64_t isa; // class64_t * (64-bit pointer)
2487 uint64_t superclass; // class64_t * (64-bit pointer)
2488 uint64_t cache; // Cache (64-bit pointer)
2489 uint64_t vtable; // IMP * (64-bit pointer)
2490 uint64_t data; // class_ro64_t * (64-bit pointer)
2494 uint32_t isa; /* class32_t * (32-bit pointer) */
2495 uint32_t superclass; /* class32_t * (32-bit pointer) */
2496 uint32_t cache; /* Cache (32-bit pointer) */
2497 uint32_t vtable; /* IMP * (32-bit pointer) */
2498 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2501 struct class_ro64_t {
2503 uint32_t instanceStart;
2504 uint32_t instanceSize;
2506 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2507 uint64_t name; // const char * (64-bit pointer)
2508 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2509 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2510 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2511 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2512 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2515 struct class_ro32_t {
2517 uint32_t instanceStart;
2518 uint32_t instanceSize;
2519 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2520 uint32_t name; /* const char * (32-bit pointer) */
2521 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2522 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2523 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2524 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2525 uint32_t baseProperties; /* const struct objc_property_list *
2529 /* Values for class_ro{64,32}_t->flags */
2530 #define RO_META (1 << 0)
2531 #define RO_ROOT (1 << 1)
2532 #define RO_HAS_CXX_STRUCTORS (1 << 2)
2534 struct method_list64_t {
2537 /* struct method64_t first; These structures follow inline */
2540 struct method_list32_t {
2543 /* struct method32_t first; These structures follow inline */
2547 uint64_t name; /* SEL (64-bit pointer) */
2548 uint64_t types; /* const char * (64-bit pointer) */
2549 uint64_t imp; /* IMP (64-bit pointer) */
2553 uint32_t name; /* SEL (32-bit pointer) */
2554 uint32_t types; /* const char * (32-bit pointer) */
2555 uint32_t imp; /* IMP (32-bit pointer) */
2558 struct protocol_list64_t {
2559 uint64_t count; /* uintptr_t (a 64-bit value) */
2560 /* struct protocol64_t * list[0]; These pointers follow inline */
2563 struct protocol_list32_t {
2564 uint32_t count; /* uintptr_t (a 32-bit value) */
2565 /* struct protocol32_t * list[0]; These pointers follow inline */
2568 struct protocol64_t {
2569 uint64_t isa; /* id * (64-bit pointer) */
2570 uint64_t name; /* const char * (64-bit pointer) */
2571 uint64_t protocols; /* struct protocol_list64_t *
2573 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2574 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2575 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2576 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2577 uint64_t instanceProperties; /* struct objc_property_list *
2581 struct protocol32_t {
2582 uint32_t isa; /* id * (32-bit pointer) */
2583 uint32_t name; /* const char * (32-bit pointer) */
2584 uint32_t protocols; /* struct protocol_list_t *
2586 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2587 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2588 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2589 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2590 uint32_t instanceProperties; /* struct objc_property_list *
2594 struct ivar_list64_t {
2597 /* struct ivar64_t first; These structures follow inline */
2600 struct ivar_list32_t {
2603 /* struct ivar32_t first; These structures follow inline */
2607 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2608 uint64_t name; /* const char * (64-bit pointer) */
2609 uint64_t type; /* const char * (64-bit pointer) */
2615 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2616 uint32_t name; /* const char * (32-bit pointer) */
2617 uint32_t type; /* const char * (32-bit pointer) */
2622 struct objc_property_list64 {
2625 /* struct objc_property64 first; These structures follow inline */
2628 struct objc_property_list32 {
2631 /* struct objc_property32 first; These structures follow inline */
2634 struct objc_property64 {
2635 uint64_t name; /* const char * (64-bit pointer) */
2636 uint64_t attributes; /* const char * (64-bit pointer) */
2639 struct objc_property32 {
2640 uint32_t name; /* const char * (32-bit pointer) */
2641 uint32_t attributes; /* const char * (32-bit pointer) */
2644 struct category64_t {
2645 uint64_t name; /* const char * (64-bit pointer) */
2646 uint64_t cls; /* struct class_t * (64-bit pointer) */
2647 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2648 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2649 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2650 uint64_t instanceProperties; /* struct objc_property_list *
2654 struct category32_t {
2655 uint32_t name; /* const char * (32-bit pointer) */
2656 uint32_t cls; /* struct class_t * (32-bit pointer) */
2657 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2658 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2659 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2660 uint32_t instanceProperties; /* struct objc_property_list *
2664 struct objc_image_info64 {
2668 struct objc_image_info32 {
2672 struct imageInfo_t {
2676 /* masks for objc_image_info.flags */
2677 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2678 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2680 struct message_ref64 {
2681 uint64_t imp; /* IMP (64-bit pointer) */
2682 uint64_t sel; /* SEL (64-bit pointer) */
2685 struct message_ref32 {
2686 uint32_t imp; /* IMP (32-bit pointer) */
2687 uint32_t sel; /* SEL (32-bit pointer) */
2690 // Objective-C 1 (32-bit only) meta data structs.
2692 struct objc_module_t {
2695 uint32_t name; /* char * (32-bit pointer) */
2696 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2699 struct objc_symtab_t {
2700 uint32_t sel_ref_cnt;
2701 uint32_t refs; /* SEL * (32-bit pointer) */
2702 uint16_t cls_def_cnt;
2703 uint16_t cat_def_cnt;
2704 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2707 struct objc_class_t {
2708 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2709 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2710 uint32_t name; /* const char * (32-bit pointer) */
2713 int32_t instance_size;
2714 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2715 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2716 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2717 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2720 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2721 // class is not a metaclass
2722 #define CLS_CLASS 0x1
2723 // class is a metaclass
2724 #define CLS_META 0x2
2726 struct objc_category_t {
2727 uint32_t category_name; /* char * (32-bit pointer) */
2728 uint32_t class_name; /* char * (32-bit pointer) */
2729 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2730 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2731 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2734 struct objc_ivar_t {
2735 uint32_t ivar_name; /* char * (32-bit pointer) */
2736 uint32_t ivar_type; /* char * (32-bit pointer) */
2737 int32_t ivar_offset;
2740 struct objc_ivar_list_t {
2742 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2745 struct objc_method_list_t {
2746 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2747 int32_t method_count;
2748 // struct objc_method_t method_list[1]; /* variable length structure */
2751 struct objc_method_t {
2752 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2753 uint32_t method_types; /* char * (32-bit pointer) */
2754 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2758 struct objc_protocol_list_t {
2759 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2761 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2762 // (32-bit pointer) */
2765 struct objc_protocol_t {
2766 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2767 uint32_t protocol_name; /* char * (32-bit pointer) */
2768 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2769 uint32_t instance_methods; /* struct objc_method_description_list *
2771 uint32_t class_methods; /* struct objc_method_description_list *
2775 struct objc_method_description_list_t {
2777 // struct objc_method_description_t list[1];
2780 struct objc_method_description_t {
2781 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2782 uint32_t types; /* char * (32-bit pointer) */
2785 inline void swapStruct(struct cfstring64_t &cfs) {
2786 sys::swapByteOrder(cfs.isa);
2787 sys::swapByteOrder(cfs.flags);
2788 sys::swapByteOrder(cfs.characters);
2789 sys::swapByteOrder(cfs.length);
2792 inline void swapStruct(struct class64_t &c) {
2793 sys::swapByteOrder(c.isa);
2794 sys::swapByteOrder(c.superclass);
2795 sys::swapByteOrder(c.cache);
2796 sys::swapByteOrder(c.vtable);
2797 sys::swapByteOrder(c.data);
2800 inline void swapStruct(struct class32_t &c) {
2801 sys::swapByteOrder(c.isa);
2802 sys::swapByteOrder(c.superclass);
2803 sys::swapByteOrder(c.cache);
2804 sys::swapByteOrder(c.vtable);
2805 sys::swapByteOrder(c.data);
2808 inline void swapStruct(struct class_ro64_t &cro) {
2809 sys::swapByteOrder(cro.flags);
2810 sys::swapByteOrder(cro.instanceStart);
2811 sys::swapByteOrder(cro.instanceSize);
2812 sys::swapByteOrder(cro.reserved);
2813 sys::swapByteOrder(cro.ivarLayout);
2814 sys::swapByteOrder(cro.name);
2815 sys::swapByteOrder(cro.baseMethods);
2816 sys::swapByteOrder(cro.baseProtocols);
2817 sys::swapByteOrder(cro.ivars);
2818 sys::swapByteOrder(cro.weakIvarLayout);
2819 sys::swapByteOrder(cro.baseProperties);
2822 inline void swapStruct(struct class_ro32_t &cro) {
2823 sys::swapByteOrder(cro.flags);
2824 sys::swapByteOrder(cro.instanceStart);
2825 sys::swapByteOrder(cro.instanceSize);
2826 sys::swapByteOrder(cro.ivarLayout);
2827 sys::swapByteOrder(cro.name);
2828 sys::swapByteOrder(cro.baseMethods);
2829 sys::swapByteOrder(cro.baseProtocols);
2830 sys::swapByteOrder(cro.ivars);
2831 sys::swapByteOrder(cro.weakIvarLayout);
2832 sys::swapByteOrder(cro.baseProperties);
2835 inline void swapStruct(struct method_list64_t &ml) {
2836 sys::swapByteOrder(ml.entsize);
2837 sys::swapByteOrder(ml.count);
2840 inline void swapStruct(struct method_list32_t &ml) {
2841 sys::swapByteOrder(ml.entsize);
2842 sys::swapByteOrder(ml.count);
2845 inline void swapStruct(struct method64_t &m) {
2846 sys::swapByteOrder(m.name);
2847 sys::swapByteOrder(m.types);
2848 sys::swapByteOrder(m.imp);
2851 inline void swapStruct(struct method32_t &m) {
2852 sys::swapByteOrder(m.name);
2853 sys::swapByteOrder(m.types);
2854 sys::swapByteOrder(m.imp);
2857 inline void swapStruct(struct protocol_list64_t &pl) {
2858 sys::swapByteOrder(pl.count);
2861 inline void swapStruct(struct protocol_list32_t &pl) {
2862 sys::swapByteOrder(pl.count);
2865 inline void swapStruct(struct protocol64_t &p) {
2866 sys::swapByteOrder(p.isa);
2867 sys::swapByteOrder(p.name);
2868 sys::swapByteOrder(p.protocols);
2869 sys::swapByteOrder(p.instanceMethods);
2870 sys::swapByteOrder(p.classMethods);
2871 sys::swapByteOrder(p.optionalInstanceMethods);
2872 sys::swapByteOrder(p.optionalClassMethods);
2873 sys::swapByteOrder(p.instanceProperties);
2876 inline void swapStruct(struct protocol32_t &p) {
2877 sys::swapByteOrder(p.isa);
2878 sys::swapByteOrder(p.name);
2879 sys::swapByteOrder(p.protocols);
2880 sys::swapByteOrder(p.instanceMethods);
2881 sys::swapByteOrder(p.classMethods);
2882 sys::swapByteOrder(p.optionalInstanceMethods);
2883 sys::swapByteOrder(p.optionalClassMethods);
2884 sys::swapByteOrder(p.instanceProperties);
2887 inline void swapStruct(struct ivar_list64_t &il) {
2888 sys::swapByteOrder(il.entsize);
2889 sys::swapByteOrder(il.count);
2892 inline void swapStruct(struct ivar_list32_t &il) {
2893 sys::swapByteOrder(il.entsize);
2894 sys::swapByteOrder(il.count);
2897 inline void swapStruct(struct ivar64_t &i) {
2898 sys::swapByteOrder(i.offset);
2899 sys::swapByteOrder(i.name);
2900 sys::swapByteOrder(i.type);
2901 sys::swapByteOrder(i.alignment);
2902 sys::swapByteOrder(i.size);
2905 inline void swapStruct(struct ivar32_t &i) {
2906 sys::swapByteOrder(i.offset);
2907 sys::swapByteOrder(i.name);
2908 sys::swapByteOrder(i.type);
2909 sys::swapByteOrder(i.alignment);
2910 sys::swapByteOrder(i.size);
2913 inline void swapStruct(struct objc_property_list64 &pl) {
2914 sys::swapByteOrder(pl.entsize);
2915 sys::swapByteOrder(pl.count);
2918 inline void swapStruct(struct objc_property_list32 &pl) {
2919 sys::swapByteOrder(pl.entsize);
2920 sys::swapByteOrder(pl.count);
2923 inline void swapStruct(struct objc_property64 &op) {
2924 sys::swapByteOrder(op.name);
2925 sys::swapByteOrder(op.attributes);
2928 inline void swapStruct(struct objc_property32 &op) {
2929 sys::swapByteOrder(op.name);
2930 sys::swapByteOrder(op.attributes);
2933 inline void swapStruct(struct category64_t &c) {
2934 sys::swapByteOrder(c.name);
2935 sys::swapByteOrder(c.cls);
2936 sys::swapByteOrder(c.instanceMethods);
2937 sys::swapByteOrder(c.classMethods);
2938 sys::swapByteOrder(c.protocols);
2939 sys::swapByteOrder(c.instanceProperties);
2942 inline void swapStruct(struct category32_t &c) {
2943 sys::swapByteOrder(c.name);
2944 sys::swapByteOrder(c.cls);
2945 sys::swapByteOrder(c.instanceMethods);
2946 sys::swapByteOrder(c.classMethods);
2947 sys::swapByteOrder(c.protocols);
2948 sys::swapByteOrder(c.instanceProperties);
2951 inline void swapStruct(struct objc_image_info64 &o) {
2952 sys::swapByteOrder(o.version);
2953 sys::swapByteOrder(o.flags);
2956 inline void swapStruct(struct objc_image_info32 &o) {
2957 sys::swapByteOrder(o.version);
2958 sys::swapByteOrder(o.flags);
2961 inline void swapStruct(struct imageInfo_t &o) {
2962 sys::swapByteOrder(o.version);
2963 sys::swapByteOrder(o.flags);
2966 inline void swapStruct(struct message_ref64 &mr) {
2967 sys::swapByteOrder(mr.imp);
2968 sys::swapByteOrder(mr.sel);
2971 inline void swapStruct(struct message_ref32 &mr) {
2972 sys::swapByteOrder(mr.imp);
2973 sys::swapByteOrder(mr.sel);
2976 inline void swapStruct(struct objc_module_t &module) {
2977 sys::swapByteOrder(module.version);
2978 sys::swapByteOrder(module.size);
2979 sys::swapByteOrder(module.name);
2980 sys::swapByteOrder(module.symtab);
2983 inline void swapStruct(struct objc_symtab_t &symtab) {
2984 sys::swapByteOrder(symtab.sel_ref_cnt);
2985 sys::swapByteOrder(symtab.refs);
2986 sys::swapByteOrder(symtab.cls_def_cnt);
2987 sys::swapByteOrder(symtab.cat_def_cnt);
2990 inline void swapStruct(struct objc_class_t &objc_class) {
2991 sys::swapByteOrder(objc_class.isa);
2992 sys::swapByteOrder(objc_class.super_class);
2993 sys::swapByteOrder(objc_class.name);
2994 sys::swapByteOrder(objc_class.version);
2995 sys::swapByteOrder(objc_class.info);
2996 sys::swapByteOrder(objc_class.instance_size);
2997 sys::swapByteOrder(objc_class.ivars);
2998 sys::swapByteOrder(objc_class.methodLists);
2999 sys::swapByteOrder(objc_class.cache);
3000 sys::swapByteOrder(objc_class.protocols);
3003 inline void swapStruct(struct objc_category_t &objc_category) {
3004 sys::swapByteOrder(objc_category.category_name);
3005 sys::swapByteOrder(objc_category.class_name);
3006 sys::swapByteOrder(objc_category.instance_methods);
3007 sys::swapByteOrder(objc_category.class_methods);
3008 sys::swapByteOrder(objc_category.protocols);
3011 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3012 sys::swapByteOrder(objc_ivar_list.ivar_count);
3015 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3016 sys::swapByteOrder(objc_ivar.ivar_name);
3017 sys::swapByteOrder(objc_ivar.ivar_type);
3018 sys::swapByteOrder(objc_ivar.ivar_offset);
3021 inline void swapStruct(struct objc_method_list_t &method_list) {
3022 sys::swapByteOrder(method_list.obsolete);
3023 sys::swapByteOrder(method_list.method_count);
3026 inline void swapStruct(struct objc_method_t &method) {
3027 sys::swapByteOrder(method.method_name);
3028 sys::swapByteOrder(method.method_types);
3029 sys::swapByteOrder(method.method_imp);
3032 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3033 sys::swapByteOrder(protocol_list.next);
3034 sys::swapByteOrder(protocol_list.count);
3037 inline void swapStruct(struct objc_protocol_t &protocol) {
3038 sys::swapByteOrder(protocol.isa);
3039 sys::swapByteOrder(protocol.protocol_name);
3040 sys::swapByteOrder(protocol.protocol_list);
3041 sys::swapByteOrder(protocol.instance_methods);
3042 sys::swapByteOrder(protocol.class_methods);
3045 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3046 sys::swapByteOrder(mdl.count);
3049 inline void swapStruct(struct objc_method_description_t &md) {
3050 sys::swapByteOrder(md.name);
3051 sys::swapByteOrder(md.types);
3054 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3055 struct DisassembleInfo *info);
3057 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3058 // to an Objective-C class and returns the class name. It is also passed the
3059 // address of the pointer, so when the pointer is zero as it can be in an .o
3060 // file, that is used to look for an external relocation entry with a symbol
3062 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3063 uint64_t ReferenceValue,
3064 struct DisassembleInfo *info) {
3066 uint32_t offset, left;
3069 // The pointer_value can be 0 in an object file and have a relocation
3070 // entry for the class symbol at the ReferenceValue (the address of the
3072 if (pointer_value == 0) {
3073 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3074 if (r == nullptr || left < sizeof(uint64_t))
3077 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3078 if (symbol_name == nullptr)
3080 const char *class_name = strrchr(symbol_name, '$');
3081 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3082 return class_name + 2;
3087 // The case were the pointer_value is non-zero and points to a class defined
3088 // in this Mach-O file.
3089 r = get_pointer_64(pointer_value, offset, left, S, info);
3090 if (r == nullptr || left < sizeof(struct class64_t))
3093 memcpy(&c, r, sizeof(struct class64_t));
3094 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3098 r = get_pointer_64(c.data, offset, left, S, info);
3099 if (r == nullptr || left < sizeof(struct class_ro64_t))
3101 struct class_ro64_t cro;
3102 memcpy(&cro, r, sizeof(struct class_ro64_t));
3103 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3107 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3111 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3112 // pointer to a cfstring and returns its name or nullptr.
3113 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3114 struct DisassembleInfo *info) {
3115 const char *r, *name;
3116 uint32_t offset, left;
3118 struct cfstring64_t cfs;
3119 uint64_t cfs_characters;
3121 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3122 if (r == nullptr || left < sizeof(struct cfstring64_t))
3124 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3125 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3127 if (cfs.characters == 0) {
3129 const char *symbol_name = get_symbol_64(
3130 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3131 if (symbol_name == nullptr)
3133 cfs_characters = n_value;
3135 cfs_characters = cfs.characters;
3136 name = get_pointer_64(cfs_characters, offset, left, S, info);
3141 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
3142 // of a pointer to an Objective-C selector reference when the pointer value is
3143 // zero as in a .o file and is likely to have a external relocation entry with
3144 // who's symbol's n_value is the real pointer to the selector name. If that is
3145 // the case the real pointer to the selector name is returned else 0 is
3147 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3148 struct DisassembleInfo *info) {
3149 uint32_t offset, left;
3152 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3153 if (r == nullptr || left < sizeof(uint64_t))
3156 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3157 if (symbol_name == nullptr)
3162 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3163 const char *sectname) {
3164 for (const SectionRef &Section : O->sections()) {
3166 Section.getName(SectName);
3167 DataRefImpl Ref = Section.getRawDataRefImpl();
3168 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3169 if (SegName == segname && SectName == sectname)
3172 return SectionRef();
3176 walk_pointer_list_64(const char *listname, const SectionRef S,
3177 MachOObjectFile *O, struct DisassembleInfo *info,
3178 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3179 if (S == SectionRef())
3183 S.getName(SectName);
3184 DataRefImpl Ref = S.getRawDataRefImpl();
3185 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3186 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3189 S.getContents(BytesStr);
3190 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3192 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3193 uint32_t left = S.getSize() - i;
3194 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3196 memcpy(&p, Contents + i, size);
3197 if (i + sizeof(uint64_t) > S.getSize())
3198 outs() << listname << " list pointer extends past end of (" << SegName
3199 << "," << SectName << ") section\n";
3200 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3202 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3203 sys::swapByteOrder(p);
3205 uint64_t n_value = 0;
3206 const char *name = get_symbol_64(i, S, info, n_value, p);
3207 if (name == nullptr)
3208 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3211 outs() << format("0x%" PRIx64, n_value);
3213 outs() << " + " << format("0x%" PRIx64, p);
3215 outs() << format("0x%" PRIx64, p);
3216 if (name != nullptr)
3217 outs() << " " << name;
3227 walk_pointer_list_32(const char *listname, const SectionRef S,
3228 MachOObjectFile *O, struct DisassembleInfo *info,
3229 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3230 if (S == SectionRef())
3234 S.getName(SectName);
3235 DataRefImpl Ref = S.getRawDataRefImpl();
3236 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3237 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3240 S.getContents(BytesStr);
3241 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3243 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3244 uint32_t left = S.getSize() - i;
3245 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3247 memcpy(&p, Contents + i, size);
3248 if (i + sizeof(uint32_t) > S.getSize())
3249 outs() << listname << " list pointer extends past end of (" << SegName
3250 << "," << SectName << ") section\n";
3251 uint32_t Address = S.getAddress() + i;
3252 outs() << format("%08" PRIx32, Address) << " ";
3254 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3255 sys::swapByteOrder(p);
3256 outs() << format("0x%" PRIx32, p);
3258 const char *name = get_symbol_32(i, S, info, p);
3259 if (name != nullptr)
3260 outs() << " " << name;
3268 static void print_layout_map(const char *layout_map, uint32_t left) {
3269 if (layout_map == nullptr)
3271 outs() << " layout map: ";
3273 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3276 } while (*layout_map != '\0' && left != 0);
3280 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3281 uint32_t offset, left;
3283 const char *layout_map;
3287 layout_map = get_pointer_64(p, offset, left, S, info);
3288 print_layout_map(layout_map, left);
3291 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3292 uint32_t offset, left;
3294 const char *layout_map;
3298 layout_map = get_pointer_32(p, offset, left, S, info);
3299 print_layout_map(layout_map, left);
3302 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3303 const char *indent) {
3304 struct method_list64_t ml;
3305 struct method64_t m;
3307 uint32_t offset, xoffset, left, i;
3309 const char *name, *sym_name;
3312 r = get_pointer_64(p, offset, left, S, info);
3315 memset(&ml, '\0', sizeof(struct method_list64_t));
3316 if (left < sizeof(struct method_list64_t)) {
3317 memcpy(&ml, r, left);
3318 outs() << " (method_list_t entends past the end of the section)\n";
3320 memcpy(&ml, r, sizeof(struct method_list64_t));
3321 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3323 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3324 outs() << indent << "\t\t count " << ml.count << "\n";
3326 p += sizeof(struct method_list64_t);
3327 offset += sizeof(struct method_list64_t);
3328 for (i = 0; i < ml.count; i++) {
3329 r = get_pointer_64(p, offset, left, S, info);
3332 memset(&m, '\0', sizeof(struct method64_t));
3333 if (left < sizeof(struct method64_t)) {
3334 memcpy(&m, r, left);
3335 outs() << indent << " (method_t extends past the end of the section)\n";
3337 memcpy(&m, r, sizeof(struct method64_t));
3338 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3341 outs() << indent << "\t\t name ";
3342 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3343 info, n_value, m.name);
3345 if (info->verbose && sym_name != nullptr)
3348 outs() << format("0x%" PRIx64, n_value);
3350 outs() << " + " << format("0x%" PRIx64, m.name);
3352 outs() << format("0x%" PRIx64, m.name);
3353 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3354 if (name != nullptr)
3355 outs() << format(" %.*s", left, name);
3358 outs() << indent << "\t\t types ";
3359 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3360 info, n_value, m.types);
3362 if (info->verbose && sym_name != nullptr)
3365 outs() << format("0x%" PRIx64, n_value);
3367 outs() << " + " << format("0x%" PRIx64, m.types);
3369 outs() << format("0x%" PRIx64, m.types);
3370 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3371 if (name != nullptr)
3372 outs() << format(" %.*s", left, name);
3375 outs() << indent << "\t\t imp ";
3376 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3378 if (info->verbose && name == nullptr) {
3380 outs() << format("0x%" PRIx64, n_value) << " ";
3382 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3384 outs() << format("0x%" PRIx64, m.imp) << " ";
3386 if (name != nullptr)
3390 p += sizeof(struct method64_t);
3391 offset += sizeof(struct method64_t);
3395 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3396 const char *indent) {
3397 struct method_list32_t ml;
3398 struct method32_t m;
3399 const char *r, *name;
3400 uint32_t offset, xoffset, left, i;
3403 r = get_pointer_32(p, offset, left, S, info);
3406 memset(&ml, '\0', sizeof(struct method_list32_t));
3407 if (left < sizeof(struct method_list32_t)) {
3408 memcpy(&ml, r, left);
3409 outs() << " (method_list_t entends past the end of the section)\n";
3411 memcpy(&ml, r, sizeof(struct method_list32_t));
3412 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3414 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3415 outs() << indent << "\t\t count " << ml.count << "\n";
3417 p += sizeof(struct method_list32_t);
3418 offset += sizeof(struct method_list32_t);
3419 for (i = 0; i < ml.count; i++) {
3420 r = get_pointer_32(p, offset, left, S, info);
3423 memset(&m, '\0', sizeof(struct method32_t));
3424 if (left < sizeof(struct method32_t)) {
3425 memcpy(&ml, r, left);
3426 outs() << indent << " (method_t entends past the end of the section)\n";
3428 memcpy(&m, r, sizeof(struct method32_t));
3429 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3432 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3433 name = get_pointer_32(m.name, xoffset, left, xS, info);
3434 if (name != nullptr)
3435 outs() << format(" %.*s", left, name);
3438 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3439 name = get_pointer_32(m.types, xoffset, left, xS, info);
3440 if (name != nullptr)
3441 outs() << format(" %.*s", left, name);
3444 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3445 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3447 if (name != nullptr)
3448 outs() << " " << name;
3451 p += sizeof(struct method32_t);
3452 offset += sizeof(struct method32_t);
3456 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3457 uint32_t offset, left, xleft;
3459 struct objc_method_list_t method_list;
3460 struct objc_method_t method;
3461 const char *r, *methods, *name, *SymbolName;
3464 r = get_pointer_32(p, offset, left, S, info, true);
3469 if (left > sizeof(struct objc_method_list_t)) {
3470 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3472 outs() << "\t\t objc_method_list extends past end of the section\n";
3473 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3474 memcpy(&method_list, r, left);
3476 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3477 swapStruct(method_list);
3479 outs() << "\t\t obsolete "
3480 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3481 outs() << "\t\t method_count " << method_list.method_count << "\n";
3483 methods = r + sizeof(struct objc_method_list_t);
3484 for (i = 0; i < method_list.method_count; i++) {
3485 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3486 outs() << "\t\t remaining method's extend past the of the section\n";
3489 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3490 sizeof(struct objc_method_t));
3491 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3494 outs() << "\t\t method_name "
3495 << format("0x%08" PRIx32, method.method_name);
3496 if (info->verbose) {
3497 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3498 if (name != nullptr)
3499 outs() << format(" %.*s", xleft, name);
3501 outs() << " (not in an __OBJC section)";
3505 outs() << "\t\t method_types "
3506 << format("0x%08" PRIx32, method.method_types);
3507 if (info->verbose) {
3508 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3509 if (name != nullptr)
3510 outs() << format(" %.*s", xleft, name);
3512 outs() << " (not in an __OBJC section)";
3516 outs() << "\t\t method_imp "
3517 << format("0x%08" PRIx32, method.method_imp) << " ";
3518 if (info->verbose) {
3519 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3520 if (SymbolName != nullptr)
3521 outs() << SymbolName;
3528 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3529 struct protocol_list64_t pl;
3530 uint64_t q, n_value;
3531 struct protocol64_t pc;
3533 uint32_t offset, xoffset, left, i;
3535 const char *name, *sym_name;
3537 r = get_pointer_64(p, offset, left, S, info);
3540 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3541 if (left < sizeof(struct protocol_list64_t)) {
3542 memcpy(&pl, r, left);
3543 outs() << " (protocol_list_t entends past the end of the section)\n";
3545 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3546 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3548 outs() << " count " << pl.count << "\n";
3550 p += sizeof(struct protocol_list64_t);
3551 offset += sizeof(struct protocol_list64_t);
3552 for (i = 0; i < pl.count; i++) {
3553 r = get_pointer_64(p, offset, left, S, info);
3557 if (left < sizeof(uint64_t)) {
3558 memcpy(&q, r, left);
3559 outs() << " (protocol_t * entends past the end of the section)\n";
3561 memcpy(&q, r, sizeof(uint64_t));
3562 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3563 sys::swapByteOrder(q);
3565 outs() << "\t\t list[" << i << "] ";
3566 sym_name = get_symbol_64(offset, S, info, n_value, q);
3568 if (info->verbose && sym_name != nullptr)
3571 outs() << format("0x%" PRIx64, n_value);
3573 outs() << " + " << format("0x%" PRIx64, q);
3575 outs() << format("0x%" PRIx64, q);
3576 outs() << " (struct protocol_t *)\n";
3578 r = get_pointer_64(q + n_value, offset, left, S, info);
3581 memset(&pc, '\0', sizeof(struct protocol64_t));
3582 if (left < sizeof(struct protocol64_t)) {
3583 memcpy(&pc, r, left);
3584 outs() << " (protocol_t entends past the end of the section)\n";
3586 memcpy(&pc, r, sizeof(struct protocol64_t));
3587 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3590 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3592 outs() << "\t\t\t name ";
3593 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3594 info, n_value, pc.name);
3596 if (info->verbose && sym_name != nullptr)
3599 outs() << format("0x%" PRIx64, n_value);
3601 outs() << " + " << format("0x%" PRIx64, pc.name);
3603 outs() << format("0x%" PRIx64, pc.name);
3604 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3605 if (name != nullptr)
3606 outs() << format(" %.*s", left, name);
3609 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3611 outs() << "\t\t instanceMethods ";
3613 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3614 S, info, n_value, pc.instanceMethods);
3616 if (info->verbose && sym_name != nullptr)
3619 outs() << format("0x%" PRIx64, n_value);
3620 if (pc.instanceMethods != 0)
3621 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3623 outs() << format("0x%" PRIx64, pc.instanceMethods);
3624 outs() << " (struct method_list_t *)\n";
3625 if (pc.instanceMethods + n_value != 0)
3626 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3628 outs() << "\t\t classMethods ";
3630 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3631 info, n_value, pc.classMethods);
3633 if (info->verbose && sym_name != nullptr)
3636 outs() << format("0x%" PRIx64, n_value);
3637 if (pc.classMethods != 0)
3638 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3640 outs() << format("0x%" PRIx64, pc.classMethods);
3641 outs() << " (struct method_list_t *)\n";
3642 if (pc.classMethods + n_value != 0)
3643 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3645 outs() << "\t optionalInstanceMethods "
3646 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3647 outs() << "\t optionalClassMethods "
3648 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3649 outs() << "\t instanceProperties "
3650 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3652 p += sizeof(uint64_t);
3653 offset += sizeof(uint64_t);
3657 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3658 struct protocol_list32_t pl;
3660 struct protocol32_t pc;
3662 uint32_t offset, xoffset, left, i;
3666 r = get_pointer_32(p, offset, left, S, info);
3669 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3670 if (left < sizeof(struct protocol_list32_t)) {
3671 memcpy(&pl, r, left);
3672 outs() << " (protocol_list_t entends past the end of the section)\n";
3674 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3675 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3677 outs() << " count " << pl.count << "\n";
3679 p += sizeof(struct protocol_list32_t);
3680 offset += sizeof(struct protocol_list32_t);
3681 for (i = 0; i < pl.count; i++) {
3682 r = get_pointer_32(p, offset, left, S, info);
3686 if (left < sizeof(uint32_t)) {
3687 memcpy(&q, r, left);
3688 outs() << " (protocol_t * entends past the end of the section)\n";
3690 memcpy(&q, r, sizeof(uint32_t));
3691 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3692 sys::swapByteOrder(q);
3693 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3694 << " (struct protocol_t *)\n";
3695 r = get_pointer_32(q, offset, left, S, info);
3698 memset(&pc, '\0', sizeof(struct protocol32_t));
3699 if (left < sizeof(struct protocol32_t)) {
3700 memcpy(&pc, r, left);
3701 outs() << " (protocol_t entends past the end of the section)\n";
3703 memcpy(&pc, r, sizeof(struct protocol32_t));
3704 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3706 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3707 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3708 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3709 if (name != nullptr)
3710 outs() << format(" %.*s", left, name);
3712 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3713 outs() << "\t\t instanceMethods "
3714 << format("0x%" PRIx32, pc.instanceMethods)
3715 << " (struct method_list_t *)\n";
3716 if (pc.instanceMethods != 0)
3717 print_method_list32_t(pc.instanceMethods, info, "\t");
3718 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3719 << " (struct method_list_t *)\n";
3720 if (pc.classMethods != 0)
3721 print_method_list32_t(pc.classMethods, info, "\t");
3722 outs() << "\t optionalInstanceMethods "
3723 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3724 outs() << "\t optionalClassMethods "
3725 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3726 outs() << "\t instanceProperties "
3727 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3728 p += sizeof(uint32_t);
3729 offset += sizeof(uint32_t);
3733 static void print_indent(uint32_t indent) {
3734 for (uint32_t i = 0; i < indent;) {
3735 if (indent - i >= 8) {
3739 for (uint32_t j = i; j < indent; j++)
3746 static bool print_method_description_list(uint32_t p, uint32_t indent,
3747 struct DisassembleInfo *info) {
3748 uint32_t offset, left, xleft;
3750 struct objc_method_description_list_t mdl;
3751 struct objc_method_description_t md;
3752 const char *r, *list, *name;
3755 r = get_pointer_32(p, offset, left, S, info, true);
3760 if (left > sizeof(struct objc_method_description_list_t)) {
3761 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3763 print_indent(indent);
3764 outs() << " objc_method_description_list extends past end of the section\n";
3765 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3766 memcpy(&mdl, r, left);
3768 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3771 print_indent(indent);
3772 outs() << " count " << mdl.count << "\n";
3774 list = r + sizeof(struct objc_method_description_list_t);
3775 for (i = 0; i < mdl.count; i++) {
3776 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3777 print_indent(indent);
3778 outs() << " remaining list entries extend past the of the section\n";
3781 print_indent(indent);
3782 outs() << " list[" << i << "]\n";
3783 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3784 sizeof(struct objc_method_description_t));
3785 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3788 print_indent(indent);
3789 outs() << " name " << format("0x%08" PRIx32, md.name);
3790 if (info->verbose) {
3791 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3792 if (name != nullptr)
3793 outs() << format(" %.*s", xleft, name);
3795 outs() << " (not in an __OBJC section)";
3799 print_indent(indent);
3800 outs() << " types " << format("0x%08" PRIx32, md.types);
3801 if (info->verbose) {
3802 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3803 if (name != nullptr)
3804 outs() << format(" %.*s", xleft, name);
3806 outs() << " (not in an __OBJC section)";
3813 static bool print_protocol_list(uint32_t p, uint32_t indent,
3814 struct DisassembleInfo *info);
3816 static bool print_protocol(uint32_t p, uint32_t indent,
3817 struct DisassembleInfo *info) {
3818 uint32_t offset, left;
3820 struct objc_protocol_t protocol;
3821 const char *r, *name;
3823 r = get_pointer_32(p, offset, left, S, info, true);
3828 if (left >= sizeof(struct objc_protocol_t)) {
3829 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3831 print_indent(indent);
3832 outs() << " Protocol extends past end of the section\n";
3833 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3834 memcpy(&protocol, r, left);
3836 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3837 swapStruct(protocol);
3839 print_indent(indent);
3840 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3843 print_indent(indent);
3844 outs() << " protocol_name "
3845 << format("0x%08" PRIx32, protocol.protocol_name);
3846 if (info->verbose) {
3847 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3848 if (name != nullptr)
3849 outs() << format(" %.*s", left, name);
3851 outs() << " (not in an __OBJC section)";
3855 print_indent(indent);
3856 outs() << " protocol_list "
3857 << format("0x%08" PRIx32, protocol.protocol_list);
3858 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3859 outs() << " (not in an __OBJC section)\n";
3861 print_indent(indent);
3862 outs() << " instance_methods "
3863 << format("0x%08" PRIx32, protocol.instance_methods);
3864 if (print_method_description_list(protocol.instance_methods, indent, info))
3865 outs() << " (not in an __OBJC section)\n";
3867 print_indent(indent);
3868 outs() << " class_methods "
3869 << format("0x%08" PRIx32, protocol.class_methods);
3870 if (print_method_description_list(protocol.class_methods, indent, info))
3871 outs() << " (not in an __OBJC section)\n";
3876 static bool print_protocol_list(uint32_t p, uint32_t indent,
3877 struct DisassembleInfo *info) {
3878 uint32_t offset, left, l;
3880 struct objc_protocol_list_t protocol_list;
3881 const char *r, *list;
3884 r = get_pointer_32(p, offset, left, S, info, true);
3889 if (left > sizeof(struct objc_protocol_list_t)) {
3890 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3892 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3893 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3894 memcpy(&protocol_list, r, left);
3896 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3897 swapStruct(protocol_list);
3899 print_indent(indent);
3900 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3902 print_indent(indent);
3903 outs() << " count " << protocol_list.count << "\n";
3905 list = r + sizeof(struct objc_protocol_list_t);
3906 for (i = 0; i < protocol_list.count; i++) {
3907 if ((i + 1) * sizeof(uint32_t) > left) {
3908 outs() << "\t\t remaining list entries extend past the of the section\n";
3911 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3912 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3913 sys::swapByteOrder(l);
3915 print_indent(indent);
3916 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3917 if (print_protocol(l, indent, info))
3918 outs() << "(not in an __OBJC section)\n";
3923 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3924 struct ivar_list64_t il;
3927 uint32_t offset, xoffset, left, j;
3929 const char *name, *sym_name, *ivar_offset_p;
3930 uint64_t ivar_offset, n_value;
3932 r = get_pointer_64(p, offset, left, S, info);
3935 memset(&il, '\0', sizeof(struct ivar_list64_t));
3936 if (left < sizeof(struct ivar_list64_t)) {
3937 memcpy(&il, r, left);
3938 outs() << " (ivar_list_t entends past the end of the section)\n";
3940 memcpy(&il, r, sizeof(struct ivar_list64_t));
3941 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3943 outs() << " entsize " << il.entsize << "\n";
3944 outs() << " count " << il.count << "\n";
3946 p += sizeof(struct ivar_list64_t);
3947 offset += sizeof(struct ivar_list64_t);
3948 for (j = 0; j < il.count; j++) {
3949 r = get_pointer_64(p, offset, left, S, info);
3952 memset(&i, '\0', sizeof(struct ivar64_t));
3953 if (left < sizeof(struct ivar64_t)) {
3954 memcpy(&i, r, left);
3955 outs() << " (ivar_t entends past the end of the section)\n";
3957 memcpy(&i, r, sizeof(struct ivar64_t));
3958 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3961 outs() << "\t\t\t offset ";
3962 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3963 info, n_value, i.offset);
3965 if (info->verbose && sym_name != nullptr)
3968 outs() << format("0x%" PRIx64, n_value);
3970 outs() << " + " << format("0x%" PRIx64, i.offset);
3972 outs() << format("0x%" PRIx64, i.offset);
3973 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3974 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3975 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3976 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3977 sys::swapByteOrder(ivar_offset);
3978 outs() << " " << ivar_offset << "\n";
3982 outs() << "\t\t\t name ";
3983 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
3986 if (info->verbose && sym_name != nullptr)
3989 outs() << format("0x%" PRIx64, n_value);
3991 outs() << " + " << format("0x%" PRIx64, i.name);
3993 outs() << format("0x%" PRIx64, i.name);
3994 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
3995 if (name != nullptr)
3996 outs() << format(" %.*s", left, name);
3999 outs() << "\t\t\t type ";
4000 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4002 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4004 if (info->verbose && sym_name != nullptr)
4007 outs() << format("0x%" PRIx64, n_value);
4009 outs() << " + " << format("0x%" PRIx64, i.type);
4011 outs() << format("0x%" PRIx64, i.type);
4012 if (name != nullptr)
4013 outs() << format(" %.*s", left, name);
4016 outs() << "\t\t\talignment " << i.alignment << "\n";
4017 outs() << "\t\t\t size " << i.size << "\n";
4019 p += sizeof(struct ivar64_t);
4020 offset += sizeof(struct ivar64_t);
4024 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4025 struct ivar_list32_t il;
4028 uint32_t offset, xoffset, left, j;
4030 const char *name, *ivar_offset_p;
4031 uint32_t ivar_offset;
4033 r = get_pointer_32(p, offset, left, S, info);
4036 memset(&il, '\0', sizeof(struct ivar_list32_t));
4037 if (left < sizeof(struct ivar_list32_t)) {
4038 memcpy(&il, r, left);
4039 outs() << " (ivar_list_t entends past the end of the section)\n";
4041 memcpy(&il, r, sizeof(struct ivar_list32_t));
4042 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4044 outs() << " entsize " << il.entsize << "\n";
4045 outs() << " count " << il.count << "\n";
4047 p += sizeof(struct ivar_list32_t);
4048 offset += sizeof(struct ivar_list32_t);
4049 for (j = 0; j < il.count; j++) {
4050 r = get_pointer_32(p, offset, left, S, info);
4053 memset(&i, '\0', sizeof(struct ivar32_t));
4054 if (left < sizeof(struct ivar32_t)) {
4055 memcpy(&i, r, left);
4056 outs() << " (ivar_t entends past the end of the section)\n";
4058 memcpy(&i, r, sizeof(struct ivar32_t));
4059 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4062 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4063 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4064 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4065 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4066 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4067 sys::swapByteOrder(ivar_offset);
4068 outs() << " " << ivar_offset << "\n";
4072 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4073 name = get_pointer_32(i.name, xoffset, left, xS, info);
4074 if (name != nullptr)
4075 outs() << format(" %.*s", left, name);
4078 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4079 name = get_pointer_32(i.type, xoffset, left, xS, info);
4080 if (name != nullptr)
4081 outs() << format(" %.*s", left, name);
4084 outs() << "\t\t\talignment " << i.alignment << "\n";
4085 outs() << "\t\t\t size " << i.size << "\n";
4087 p += sizeof(struct ivar32_t);
4088 offset += sizeof(struct ivar32_t);
4092 static void print_objc_property_list64(uint64_t p,
4093 struct DisassembleInfo *info) {
4094 struct objc_property_list64 opl;
4095 struct objc_property64 op;
4097 uint32_t offset, xoffset, left, j;
4099 const char *name, *sym_name;
4102 r = get_pointer_64(p, offset, left, S, info);
4105 memset(&opl, '\0', sizeof(struct objc_property_list64));
4106 if (left < sizeof(struct objc_property_list64)) {
4107 memcpy(&opl, r, left);
4108 outs() << " (objc_property_list entends past the end of the section)\n";
4110 memcpy(&opl, r, sizeof(struct objc_property_list64));
4111 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4113 outs() << " entsize " << opl.entsize << "\n";
4114 outs() << " count " << opl.count << "\n";
4116 p += sizeof(struct objc_property_list64);
4117 offset += sizeof(struct objc_property_list64);
4118 for (j = 0; j < opl.count; j++) {
4119 r = get_pointer_64(p, offset, left, S, info);
4122 memset(&op, '\0', sizeof(struct objc_property64));
4123 if (left < sizeof(struct objc_property64)) {
4124 memcpy(&op, r, left);
4125 outs() << " (objc_property entends past the end of the section)\n";
4127 memcpy(&op, r, sizeof(struct objc_property64));
4128 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4131 outs() << "\t\t\t name ";
4132 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4133 info, n_value, op.name);
4135 if (info->verbose && sym_name != nullptr)
4138 outs() << format("0x%" PRIx64, n_value);
4140 outs() << " + " << format("0x%" PRIx64, op.name);
4142 outs() << format("0x%" PRIx64, op.name);
4143 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4144 if (name != nullptr)
4145 outs() << format(" %.*s", left, name);
4148 outs() << "\t\t\tattributes ";
4150 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4151 info, n_value, op.attributes);
4153 if (info->verbose && sym_name != nullptr)
4156 outs() << format("0x%" PRIx64, n_value);
4157 if (op.attributes != 0)
4158 outs() << " + " << format("0x%" PRIx64, op.attributes);
4160 outs() << format("0x%" PRIx64, op.attributes);
4161 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4162 if (name != nullptr)
4163 outs() << format(" %.*s", left, name);
4166 p += sizeof(struct objc_property64);
4167 offset += sizeof(struct objc_property64);
4171 static void print_objc_property_list32(uint32_t p,
4172 struct DisassembleInfo *info) {
4173 struct objc_property_list32 opl;
4174 struct objc_property32 op;
4176 uint32_t offset, xoffset, left, j;
4180 r = get_pointer_32(p, offset, left, S, info);
4183 memset(&opl, '\0', sizeof(struct objc_property_list32));
4184 if (left < sizeof(struct objc_property_list32)) {
4185 memcpy(&opl, r, left);
4186 outs() << " (objc_property_list entends past the end of the section)\n";
4188 memcpy(&opl, r, sizeof(struct objc_property_list32));
4189 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4191 outs() << " entsize " << opl.entsize << "\n";
4192 outs() << " count " << opl.count << "\n";
4194 p += sizeof(struct objc_property_list32);
4195 offset += sizeof(struct objc_property_list32);
4196 for (j = 0; j < opl.count; j++) {
4197 r = get_pointer_32(p, offset, left, S, info);
4200 memset(&op, '\0', sizeof(struct objc_property32));
4201 if (left < sizeof(struct objc_property32)) {
4202 memcpy(&op, r, left);
4203 outs() << " (objc_property entends past the end of the section)\n";
4205 memcpy(&op, r, sizeof(struct objc_property32));
4206 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4209 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4210 name = get_pointer_32(op.name, xoffset, left, xS, info);
4211 if (name != nullptr)
4212 outs() << format(" %.*s", left, name);
4215 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4216 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4217 if (name != nullptr)
4218 outs() << format(" %.*s", left, name);
4221 p += sizeof(struct objc_property32);
4222 offset += sizeof(struct objc_property32);
4226 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
4227 bool &is_meta_class) {
4228 struct class_ro64_t cro;
4230 uint32_t offset, xoffset, left;
4232 const char *name, *sym_name;
4235 r = get_pointer_64(p, offset, left, S, info);
4236 if (r == nullptr || left < sizeof(struct class_ro64_t))
4238 memset(&cro, '\0', sizeof(struct class_ro64_t));
4239 if (left < sizeof(struct class_ro64_t)) {
4240 memcpy(&cro, r, left);
4241 outs() << " (class_ro_t entends past the end of the section)\n";
4243 memcpy(&cro, r, sizeof(struct class_ro64_t));
4244 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4246 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4247 if (cro.flags & RO_META)
4248 outs() << " RO_META";
4249 if (cro.flags & RO_ROOT)
4250 outs() << " RO_ROOT";
4251 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4252 outs() << " RO_HAS_CXX_STRUCTORS";
4254 outs() << " instanceStart " << cro.instanceStart << "\n";
4255 outs() << " instanceSize " << cro.instanceSize << "\n";
4256 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4258 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4260 print_layout_map64(cro.ivarLayout, info);
4263 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4264 info, n_value, cro.name);
4266 if (info->verbose && sym_name != nullptr)
4269 outs() << format("0x%" PRIx64, n_value);
4271 outs() << " + " << format("0x%" PRIx64, cro.name);
4273 outs() << format("0x%" PRIx64, cro.name);
4274 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4275 if (name != nullptr)
4276 outs() << format(" %.*s", left, name);
4279 outs() << " baseMethods ";
4280 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4281 S, info, n_value, cro.baseMethods);
4283 if (info->verbose && sym_name != nullptr)
4286 outs() << format("0x%" PRIx64, n_value);
4287 if (cro.baseMethods != 0)
4288 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4290 outs() << format("0x%" PRIx64, cro.baseMethods);
4291 outs() << " (struct method_list_t *)\n";
4292 if (cro.baseMethods + n_value != 0)
4293 print_method_list64_t(cro.baseMethods + n_value, info, "");
4295 outs() << " baseProtocols ";
4297 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4298 info, n_value, cro.baseProtocols);
4300 if (info->verbose && sym_name != nullptr)
4303 outs() << format("0x%" PRIx64, n_value);
4304 if (cro.baseProtocols != 0)
4305 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4307 outs() << format("0x%" PRIx64, cro.baseProtocols);
4309 if (cro.baseProtocols + n_value != 0)
4310 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4312 outs() << " ivars ";
4313 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
4314 info, n_value, cro.ivars);
4316 if (info->verbose && sym_name != nullptr)
4319 outs() << format("0x%" PRIx64, n_value);
4321 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4323 outs() << format("0x%" PRIx64, cro.ivars);
4325 if (cro.ivars + n_value != 0)
4326 print_ivar_list64_t(cro.ivars + n_value, info);
4328 outs() << " weakIvarLayout ";
4330 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4331 info, n_value, cro.weakIvarLayout);
4333 if (info->verbose && sym_name != nullptr)
4336 outs() << format("0x%" PRIx64, n_value);
4337 if (cro.weakIvarLayout != 0)
4338 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4340 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4342 print_layout_map64(cro.weakIvarLayout + n_value, info);
4344 outs() << " baseProperties ";
4346 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4347 info, n_value, cro.baseProperties);
4349 if (info->verbose && sym_name != nullptr)
4352 outs() << format("0x%" PRIx64, n_value);
4353 if (cro.baseProperties != 0)
4354 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4356 outs() << format("0x%" PRIx64, cro.baseProperties);
4358 if (cro.baseProperties + n_value != 0)
4359 print_objc_property_list64(cro.baseProperties + n_value, info);
4361 is_meta_class = (cro.flags & RO_META) != 0;
4365 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
4366 bool &is_meta_class) {
4367 struct class_ro32_t cro;
4369 uint32_t offset, xoffset, left;
4373 r = get_pointer_32(p, offset, left, S, info);
4376 memset(&cro, '\0', sizeof(struct class_ro32_t));
4377 if (left < sizeof(struct class_ro32_t)) {
4378 memcpy(&cro, r, left);
4379 outs() << " (class_ro_t entends past the end of the section)\n";
4381 memcpy(&cro, r, sizeof(struct class_ro32_t));
4382 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4384 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4385 if (cro.flags & RO_META)
4386 outs() << " RO_META";
4387 if (cro.flags & RO_ROOT)
4388 outs() << " RO_ROOT";
4389 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4390 outs() << " RO_HAS_CXX_STRUCTORS";
4392 outs() << " instanceStart " << cro.instanceStart << "\n";
4393 outs() << " instanceSize " << cro.instanceSize << "\n";
4394 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4396 print_layout_map32(cro.ivarLayout, info);
4398 outs() << " name " << format("0x%" PRIx32, cro.name);
4399 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4400 if (name != nullptr)
4401 outs() << format(" %.*s", left, name);
4404 outs() << " baseMethods "
4405 << format("0x%" PRIx32, cro.baseMethods)
4406 << " (struct method_list_t *)\n";
4407 if (cro.baseMethods != 0)
4408 print_method_list32_t(cro.baseMethods, info, "");
4410 outs() << " baseProtocols "
4411 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4412 if (cro.baseProtocols != 0)
4413 print_protocol_list32_t(cro.baseProtocols, info);
4414 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4417 print_ivar_list32_t(cro.ivars, info);
4418 outs() << " weakIvarLayout "
4419 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4420 print_layout_map32(cro.weakIvarLayout, info);
4421 outs() << " baseProperties "
4422 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4423 if (cro.baseProperties != 0)
4424 print_objc_property_list32(cro.baseProperties, info);
4425 is_meta_class = (cro.flags & RO_META) != 0;
4429 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4432 uint32_t offset, left;
4435 uint64_t isa_n_value, n_value;
4437 r = get_pointer_64(p, offset, left, S, info);
4438 if (r == nullptr || left < sizeof(struct class64_t))
4440 memset(&c, '\0', sizeof(struct class64_t));
4441 if (left < sizeof(struct class64_t)) {
4442 memcpy(&c, r, left);
4443 outs() << " (class_t entends past the end of the section)\n";
4445 memcpy(&c, r, sizeof(struct class64_t));
4446 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4449 outs() << " isa " << format("0x%" PRIx64, c.isa);
4450 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4451 isa_n_value, c.isa);
4452 if (name != nullptr)
4453 outs() << " " << name;
4456 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4457 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4458 n_value, c.superclass);
4459 if (name != nullptr)
4460 outs() << " " << name;
4463 outs() << " cache " << format("0x%" PRIx64, c.cache);
4464 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4466 if (name != nullptr)
4467 outs() << " " << name;
4470 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4471 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4473 if (name != nullptr)
4474 outs() << " " << name;
4477 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4481 if (info->verbose && name != nullptr)
4484 outs() << format("0x%" PRIx64, n_value);
4486 outs() << " + " << format("0x%" PRIx64, c.data);
4488 outs() << format("0x%" PRIx64, c.data);
4489 outs() << " (struct class_ro_t *)";
4491 // This is a Swift class if some of the low bits of the pointer are set.
4492 if ((c.data + n_value) & 0x7)
4493 outs() << " Swift class";
4496 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4499 if (!is_meta_class &&
4500 c.isa + isa_n_value != p &&
4501 c.isa + isa_n_value != 0 &&
4502 info->depth < 100) {
4504 outs() << "Meta Class\n";
4505 print_class64_t(c.isa + isa_n_value, info);
4509 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4512 uint32_t offset, left;
4516 r = get_pointer_32(p, offset, left, S, info);
4519 memset(&c, '\0', sizeof(struct class32_t));
4520 if (left < sizeof(struct class32_t)) {
4521 memcpy(&c, r, left);
4522 outs() << " (class_t entends past the end of the section)\n";
4524 memcpy(&c, r, sizeof(struct class32_t));
4525 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4528 outs() << " isa " << format("0x%" PRIx32, c.isa);
4530 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4531 if (name != nullptr)
4532 outs() << " " << name;
4535 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4536 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4538 if (name != nullptr)
4539 outs() << " " << name;
4542 outs() << " cache " << format("0x%" PRIx32, c.cache);
4543 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4545 if (name != nullptr)
4546 outs() << " " << name;
4549 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4550 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4552 if (name != nullptr)
4553 outs() << " " << name;
4557 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4558 outs() << " data " << format("0x%" PRIx32, c.data)
4559 << " (struct class_ro_t *)";
4561 // This is a Swift class if some of the low bits of the pointer are set.
4563 outs() << " Swift class";
4566 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4569 if (!is_meta_class) {
4570 outs() << "Meta Class\n";
4571 print_class32_t(c.isa, info);
4575 static void print_objc_class_t(struct objc_class_t *objc_class,
4576 struct DisassembleInfo *info) {
4577 uint32_t offset, left, xleft;
4578 const char *name, *p, *ivar_list;
4581 struct objc_ivar_list_t objc_ivar_list;
4582 struct objc_ivar_t ivar;
4584 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4585 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4586 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4587 if (name != nullptr)
4588 outs() << format(" %.*s", left, name);
4590 outs() << " (not in an __OBJC section)";
4594 outs() << "\t super_class "
4595 << format("0x%08" PRIx32, objc_class->super_class);
4596 if (info->verbose) {
4597 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4598 if (name != nullptr)
4599 outs() << format(" %.*s", left, name);
4601 outs() << " (not in an __OBJC section)";
4605 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4606 if (info->verbose) {
4607 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4608 if (name != nullptr)
4609 outs() << format(" %.*s", left, name);
4611 outs() << " (not in an __OBJC section)";
4615 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4618 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4619 if (info->verbose) {
4620 if (CLS_GETINFO(objc_class, CLS_CLASS))
4621 outs() << " CLS_CLASS";
4622 else if (CLS_GETINFO(objc_class, CLS_META))
4623 outs() << " CLS_META";
4627 outs() << "\t instance_size "
4628 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4630 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4631 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4633 if (left > sizeof(struct objc_ivar_list_t)) {
4635 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4637 outs() << " (entends past the end of the section)\n";
4638 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4639 memcpy(&objc_ivar_list, p, left);
4641 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4642 swapStruct(objc_ivar_list);
4643 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4644 ivar_list = p + sizeof(struct objc_ivar_list_t);
4645 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4646 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4647 outs() << "\t\t remaining ivar's extend past the of the section\n";
4650 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4651 sizeof(struct objc_ivar_t));
4652 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4655 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4656 if (info->verbose) {
4657 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4658 if (name != nullptr)
4659 outs() << format(" %.*s", xleft, name);
4661 outs() << " (not in an __OBJC section)";
4665 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4666 if (info->verbose) {
4667 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4668 if (name != nullptr)
4669 outs() << format(" %.*s", xleft, name);
4671 outs() << " (not in an __OBJC section)";
4675 outs() << "\t\t ivar_offset "
4676 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4679 outs() << " (not in an __OBJC section)\n";
4682 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4683 if (print_method_list(objc_class->methodLists, info))
4684 outs() << " (not in an __OBJC section)\n";
4686 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4689 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4690 if (print_protocol_list(objc_class->protocols, 16, info))
4691 outs() << " (not in an __OBJC section)\n";
4694 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4695 struct DisassembleInfo *info) {
4696 uint32_t offset, left;
4700 outs() << "\t category name "
4701 << format("0x%08" PRIx32, objc_category->category_name);
4702 if (info->verbose) {
4703 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4705 if (name != nullptr)
4706 outs() << format(" %.*s", left, name);
4708 outs() << " (not in an __OBJC section)";
4712 outs() << "\t\t class name "
4713 << format("0x%08" PRIx32, objc_category->class_name);
4714 if (info->verbose) {
4716 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4717 if (name != nullptr)
4718 outs() << format(" %.*s", left, name);
4720 outs() << " (not in an __OBJC section)";
4724 outs() << "\t instance methods "
4725 << format("0x%08" PRIx32, objc_category->instance_methods);
4726 if (print_method_list(objc_category->instance_methods, info))
4727 outs() << " (not in an __OBJC section)\n";
4729 outs() << "\t class methods "
4730 << format("0x%08" PRIx32, objc_category->class_methods);
4731 if (print_method_list(objc_category->class_methods, info))
4732 outs() << " (not in an __OBJC section)\n";
4735 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4736 struct category64_t c;
4738 uint32_t offset, xoffset, left;
4740 const char *name, *sym_name;
4743 r = get_pointer_64(p, offset, left, S, info);
4746 memset(&c, '\0', sizeof(struct category64_t));
4747 if (left < sizeof(struct category64_t)) {
4748 memcpy(&c, r, left);
4749 outs() << " (category_t entends past the end of the section)\n";
4751 memcpy(&c, r, sizeof(struct category64_t));
4752 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4756 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4757 info, n_value, c.name);
4759 if (info->verbose && sym_name != nullptr)
4762 outs() << format("0x%" PRIx64, n_value);
4764 outs() << " + " << format("0x%" PRIx64, c.name);
4766 outs() << format("0x%" PRIx64, c.name);
4767 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4768 if (name != nullptr)
4769 outs() << format(" %.*s", left, name);
4773 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4776 if (info->verbose && sym_name != nullptr)
4779 outs() << format("0x%" PRIx64, n_value);
4781 outs() << " + " << format("0x%" PRIx64, c.cls);
4783 outs() << format("0x%" PRIx64, c.cls);
4785 if (c.cls + n_value != 0)
4786 print_class64_t(c.cls + n_value, info);
4788 outs() << " instanceMethods ";
4790 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4791 info, n_value, c.instanceMethods);
4793 if (info->verbose && sym_name != nullptr)
4796 outs() << format("0x%" PRIx64, n_value);
4797 if (c.instanceMethods != 0)
4798 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4800 outs() << format("0x%" PRIx64, c.instanceMethods);
4802 if (c.instanceMethods + n_value != 0)
4803 print_method_list64_t(c.instanceMethods + n_value, info, "");
4805 outs() << " classMethods ";
4806 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4807 S, info, n_value, c.classMethods);
4809 if (info->verbose && sym_name != nullptr)
4812 outs() << format("0x%" PRIx64, n_value);
4813 if (c.classMethods != 0)
4814 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4816 outs() << format("0x%" PRIx64, c.classMethods);
4818 if (c.classMethods + n_value != 0)
4819 print_method_list64_t(c.classMethods + n_value, info, "");
4821 outs() << " protocols ";
4822 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4823 info, n_value, c.protocols);
4825 if (info->verbose && sym_name != nullptr)
4828 outs() << format("0x%" PRIx64, n_value);
4829 if (c.protocols != 0)
4830 outs() << " + " << format("0x%" PRIx64, c.protocols);
4832 outs() << format("0x%" PRIx64, c.protocols);
4834 if (c.protocols + n_value != 0)
4835 print_protocol_list64_t(c.protocols + n_value, info);
4837 outs() << "instanceProperties ";
4839 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4840 S, info, n_value, c.instanceProperties);
4842 if (info->verbose && sym_name != nullptr)
4845 outs() << format("0x%" PRIx64, n_value);
4846 if (c.instanceProperties != 0)
4847 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4849 outs() << format("0x%" PRIx64, c.instanceProperties);
4851 if (c.instanceProperties + n_value != 0)
4852 print_objc_property_list64(c.instanceProperties + n_value, info);
4855 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4856 struct category32_t c;
4858 uint32_t offset, left;
4862 r = get_pointer_32(p, offset, left, S, info);
4865 memset(&c, '\0', sizeof(struct category32_t));
4866 if (left < sizeof(struct category32_t)) {
4867 memcpy(&c, r, left);
4868 outs() << " (category_t entends past the end of the section)\n";
4870 memcpy(&c, r, sizeof(struct category32_t));
4871 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4874 outs() << " name " << format("0x%" PRIx32, c.name);
4875 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4878 outs() << " " << name;
4881 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4883 print_class32_t(c.cls, info);
4884 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4886 if (c.instanceMethods != 0)
4887 print_method_list32_t(c.instanceMethods, info, "");
4888 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4890 if (c.classMethods != 0)
4891 print_method_list32_t(c.classMethods, info, "");
4892 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4893 if (c.protocols != 0)
4894 print_protocol_list32_t(c.protocols, info);
4895 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4897 if (c.instanceProperties != 0)
4898 print_objc_property_list32(c.instanceProperties, info);
4901 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4902 uint32_t i, left, offset, xoffset;
4903 uint64_t p, n_value;
4904 struct message_ref64 mr;
4905 const char *name, *sym_name;
4909 if (S == SectionRef())
4913 S.getName(SectName);
4914 DataRefImpl Ref = S.getRawDataRefImpl();
4915 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4916 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4918 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4919 p = S.getAddress() + i;
4920 r = get_pointer_64(p, offset, left, S, info);
4923 memset(&mr, '\0', sizeof(struct message_ref64));
4924 if (left < sizeof(struct message_ref64)) {
4925 memcpy(&mr, r, left);
4926 outs() << " (message_ref entends past the end of the section)\n";
4928 memcpy(&mr, r, sizeof(struct message_ref64));
4929 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4933 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4936 outs() << format("0x%" PRIx64, n_value) << " ";
4938 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4940 outs() << format("0x%" PRIx64, mr.imp) << " ";
4941 if (name != nullptr)
4942 outs() << " " << name;
4946 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4947 info, n_value, mr.sel);
4949 if (info->verbose && sym_name != nullptr)
4952 outs() << format("0x%" PRIx64, n_value);
4954 outs() << " + " << format("0x%" PRIx64, mr.sel);
4956 outs() << format("0x%" PRIx64, mr.sel);
4957 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4958 if (name != nullptr)
4959 outs() << format(" %.*s", left, name);
4962 offset += sizeof(struct message_ref64);
4966 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
4967 uint32_t i, left, offset, xoffset, p;
4968 struct message_ref32 mr;
4969 const char *name, *r;
4972 if (S == SectionRef())
4976 S.getName(SectName);
4977 DataRefImpl Ref = S.getRawDataRefImpl();
4978 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4979 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4981 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4982 p = S.getAddress() + i;
4983 r = get_pointer_32(p, offset, left, S, info);
4986 memset(&mr, '\0', sizeof(struct message_ref32));
4987 if (left < sizeof(struct message_ref32)) {
4988 memcpy(&mr, r, left);
4989 outs() << " (message_ref entends past the end of the section)\n";
4991 memcpy(&mr, r, sizeof(struct message_ref32));
4992 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4995 outs() << " imp " << format("0x%" PRIx32, mr.imp);
4996 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
4998 if (name != nullptr)
4999 outs() << " " << name;
5002 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5003 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5004 if (name != nullptr)
5005 outs() << " " << name;
5008 offset += sizeof(struct message_ref32);
5012 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5013 uint32_t left, offset, swift_version;
5015 struct objc_image_info64 o;
5018 if (S == SectionRef())
5022 S.getName(SectName);
5023 DataRefImpl Ref = S.getRawDataRefImpl();
5024 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5025 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5027 r = get_pointer_64(p, offset, left, S, info);
5030 memset(&o, '\0', sizeof(struct objc_image_info64));
5031 if (left < sizeof(struct objc_image_info64)) {
5032 memcpy(&o, r, left);
5033 outs() << " (objc_image_info entends past the end of the section)\n";
5035 memcpy(&o, r, sizeof(struct objc_image_info64));
5036 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5038 outs() << " version " << o.version << "\n";
5039 outs() << " flags " << format("0x%" PRIx32, o.flags);
5040 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5041 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5042 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5043 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5044 swift_version = (o.flags >> 8) & 0xff;
5045 if (swift_version != 0) {
5046 if (swift_version == 1)
5047 outs() << " Swift 1.0";
5048 else if (swift_version == 2)
5049 outs() << " Swift 1.1";
5051 outs() << " unknown future Swift version (" << swift_version << ")";
5056 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5057 uint32_t left, offset, swift_version, p;
5058 struct objc_image_info32 o;
5062 S.getName(SectName);
5063 DataRefImpl Ref = S.getRawDataRefImpl();
5064 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5065 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5067 r = get_pointer_32(p, offset, left, S, info);
5070 memset(&o, '\0', sizeof(struct objc_image_info32));
5071 if (left < sizeof(struct objc_image_info32)) {
5072 memcpy(&o, r, left);
5073 outs() << " (objc_image_info entends past the end of the section)\n";
5075 memcpy(&o, r, sizeof(struct objc_image_info32));
5076 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5078 outs() << " version " << o.version << "\n";
5079 outs() << " flags " << format("0x%" PRIx32, o.flags);
5080 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5081 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5082 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5083 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5084 swift_version = (o.flags >> 8) & 0xff;
5085 if (swift_version != 0) {
5086 if (swift_version == 1)
5087 outs() << " Swift 1.0";
5088 else if (swift_version == 2)
5089 outs() << " Swift 1.1";
5091 outs() << " unknown future Swift version (" << swift_version << ")";
5096 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5097 uint32_t left, offset, p;
5098 struct imageInfo_t o;
5102 S.getName(SectName);
5103 DataRefImpl Ref = S.getRawDataRefImpl();
5104 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5105 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5107 r = get_pointer_32(p, offset, left, S, info);
5110 memset(&o, '\0', sizeof(struct imageInfo_t));
5111 if (left < sizeof(struct imageInfo_t)) {
5112 memcpy(&o, r, left);
5113 outs() << " (imageInfo entends past the end of the section)\n";
5115 memcpy(&o, r, sizeof(struct imageInfo_t));
5116 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5118 outs() << " version " << o.version << "\n";
5119 outs() << " flags " << format("0x%" PRIx32, o.flags);
5125 outs() << " GC-only";
5131 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5132 SymbolAddressMap AddrMap;
5134 CreateSymbolAddressMap(O, &AddrMap);
5136 std::vector<SectionRef> Sections;
5137 for (const SectionRef &Section : O->sections()) {
5139 Section.getName(SectName);
5140 Sections.push_back(Section);
5143 struct DisassembleInfo info;
5144 // Set up the block of info used by the Symbolizer call backs.
5145 info.verbose = verbose;
5147 info.AddrMap = &AddrMap;
5148 info.Sections = &Sections;
5149 info.class_name = nullptr;
5150 info.selector_name = nullptr;
5151 info.method = nullptr;
5152 info.demangled_name = nullptr;
5153 info.bindtable = nullptr;
5158 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5159 if (CL == SectionRef())
5160 CL = get_section(O, "__DATA", "__objc_classlist");
5162 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5164 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5165 if (CR == SectionRef())
5166 CR = get_section(O, "__DATA", "__objc_classrefs");
5168 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5170 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5171 if (SR == SectionRef())
5172 SR = get_section(O, "__DATA", "__objc_superrefs");
5174 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5176 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5177 if (CA == SectionRef())
5178 CA = get_section(O, "__DATA", "__objc_catlist");
5180 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5182 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5183 if (PL == SectionRef())
5184 PL = get_section(O, "__DATA", "__objc_protolist");
5186 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5188 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5189 if (MR == SectionRef())
5190 MR = get_section(O, "__DATA", "__objc_msgrefs");
5192 print_message_refs64(MR, &info);
5194 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5195 if (II == SectionRef())
5196 II = get_section(O, "__DATA", "__objc_imageinfo");
5198 print_image_info64(II, &info);
5200 if (info.bindtable != nullptr)
5201 delete info.bindtable;
5204 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5205 SymbolAddressMap AddrMap;
5207 CreateSymbolAddressMap(O, &AddrMap);
5209 std::vector<SectionRef> Sections;
5210 for (const SectionRef &Section : O->sections()) {
5212 Section.getName(SectName);
5213 Sections.push_back(Section);
5216 struct DisassembleInfo info;
5217 // Set up the block of info used by the Symbolizer call backs.
5218 info.verbose = verbose;
5220 info.AddrMap = &AddrMap;
5221 info.Sections = &Sections;
5222 info.class_name = nullptr;
5223 info.selector_name = nullptr;
5224 info.method = nullptr;
5225 info.demangled_name = nullptr;
5226 info.bindtable = nullptr;
5230 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5231 if (CL != SectionRef()) {
5233 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5235 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5237 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5240 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5241 if (CR != SectionRef()) {
5243 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5245 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5247 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5250 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5251 if (SR != SectionRef()) {
5253 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5255 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5257 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5260 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5261 if (CA != SectionRef()) {
5263 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5265 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5267 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5270 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5271 if (PL != SectionRef()) {
5273 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5275 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5277 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5280 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5281 if (MR != SectionRef()) {
5283 print_message_refs32(MR, &info);
5285 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5287 print_message_refs32(MR, &info);
5290 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5291 if (II != SectionRef()) {
5293 print_image_info32(II, &info);
5295 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5297 print_image_info32(II, &info);
5301 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5302 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5303 const char *r, *name, *defs;
5304 struct objc_module_t module;
5306 struct objc_symtab_t symtab;
5307 struct objc_class_t objc_class;
5308 struct objc_category_t objc_category;
5310 outs() << "Objective-C segment\n";
5311 S = get_section(O, "__OBJC", "__module_info");
5312 if (S == SectionRef())
5315 SymbolAddressMap AddrMap;
5317 CreateSymbolAddressMap(O, &AddrMap);
5319 std::vector<SectionRef> Sections;
5320 for (const SectionRef &Section : O->sections()) {
5322 Section.getName(SectName);
5323 Sections.push_back(Section);
5326 struct DisassembleInfo info;
5327 // Set up the block of info used by the Symbolizer call backs.
5328 info.verbose = verbose;
5330 info.AddrMap = &AddrMap;
5331 info.Sections = &Sections;
5332 info.class_name = nullptr;
5333 info.selector_name = nullptr;
5334 info.method = nullptr;
5335 info.demangled_name = nullptr;
5336 info.bindtable = nullptr;
5340 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5341 p = S.getAddress() + i;
5342 r = get_pointer_32(p, offset, left, S, &info, true);
5345 memset(&module, '\0', sizeof(struct objc_module_t));
5346 if (left < sizeof(struct objc_module_t)) {
5347 memcpy(&module, r, left);
5348 outs() << " (module extends past end of __module_info section)\n";
5350 memcpy(&module, r, sizeof(struct objc_module_t));
5351 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5354 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5355 outs() << " version " << module.version << "\n";
5356 outs() << " size " << module.size << "\n";
5358 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5359 if (name != nullptr)
5360 outs() << format("%.*s", left, name);
5362 outs() << format("0x%08" PRIx32, module.name)
5363 << "(not in an __OBJC section)";
5366 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5367 if (module.symtab == 0 || r == nullptr) {
5368 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5369 << " (not in an __OBJC section)\n";
5372 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5373 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5376 if (left < sizeof(struct objc_symtab_t)) {
5377 memcpy(&symtab, r, left);
5378 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5380 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5381 if (left > sizeof(struct objc_symtab_t)) {
5382 defs_left = left - sizeof(struct objc_symtab_t);
5383 defs = r + sizeof(struct objc_symtab_t);
5386 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5389 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5390 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5391 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5393 outs() << " (not in an __OBJC section)";
5395 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5396 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5397 if (symtab.cls_def_cnt > 0)
5398 outs() << "\tClass Definitions\n";
5399 for (j = 0; j < symtab.cls_def_cnt; j++) {
5400 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5401 outs() << "\t(remaining class defs entries entends past the end of the "
5405 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5406 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5407 sys::swapByteOrder(def);
5409 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5410 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5412 if (left > sizeof(struct objc_class_t)) {
5414 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5416 outs() << " (entends past the end of the section)\n";
5417 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5418 memcpy(&objc_class, r, left);
5420 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5421 swapStruct(objc_class);
5422 print_objc_class_t(&objc_class, &info);
5424 outs() << "(not in an __OBJC section)\n";
5427 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5428 outs() << "\tMeta Class";
5429 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5431 if (left > sizeof(struct objc_class_t)) {
5433 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5435 outs() << " (entends past the end of the section)\n";
5436 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5437 memcpy(&objc_class, r, left);
5439 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5440 swapStruct(objc_class);
5441 print_objc_class_t(&objc_class, &info);
5443 outs() << "(not in an __OBJC section)\n";
5447 if (symtab.cat_def_cnt > 0)
5448 outs() << "\tCategory Definitions\n";
5449 for (j = 0; j < symtab.cat_def_cnt; j++) {
5450 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5451 outs() << "\t(remaining category defs entries entends past the end of "
5452 << "the section)\n";
5455 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5457 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5458 sys::swapByteOrder(def);
5460 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5461 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5462 << format("0x%08" PRIx32, def);
5464 if (left > sizeof(struct objc_category_t)) {
5466 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5468 outs() << " (entends past the end of the section)\n";
5469 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5470 memcpy(&objc_category, r, left);
5472 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5473 swapStruct(objc_category);
5474 print_objc_objc_category_t(&objc_category, &info);
5476 outs() << "(not in an __OBJC section)\n";
5480 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5481 if (II != SectionRef())
5482 print_image_info(II, &info);
5487 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5488 uint32_t size, uint32_t addr) {
5489 SymbolAddressMap AddrMap;
5490 CreateSymbolAddressMap(O, &AddrMap);
5492 std::vector<SectionRef> Sections;
5493 for (const SectionRef &Section : O->sections()) {
5495 Section.getName(SectName);
5496 Sections.push_back(Section);
5499 struct DisassembleInfo info;
5500 // Set up the block of info used by the Symbolizer call backs.
5501 info.verbose = true;
5503 info.AddrMap = &AddrMap;
5504 info.Sections = &Sections;
5505 info.class_name = nullptr;
5506 info.selector_name = nullptr;
5507 info.method = nullptr;
5508 info.demangled_name = nullptr;
5509 info.bindtable = nullptr;
5514 struct objc_protocol_t protocol;
5515 uint32_t left, paddr;
5516 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5517 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5518 left = size - (p - sect);
5519 if (left < sizeof(struct objc_protocol_t)) {
5520 outs() << "Protocol extends past end of __protocol section\n";
5521 memcpy(&protocol, p, left);
5523 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5524 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5525 swapStruct(protocol);
5526 paddr = addr + (p - sect);
5527 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5528 if (print_protocol(paddr, 0, &info))
5529 outs() << "(not in an __OBJC section)\n";
5533 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5535 printObjc2_64bit_MetaData(O, verbose);
5537 MachO::mach_header H;
5539 if (H.cputype == MachO::CPU_TYPE_ARM)
5540 printObjc2_32bit_MetaData(O, verbose);
5542 // This is the 32-bit non-arm cputype case. Which is normally
5543 // the first Objective-C ABI. But it may be the case of a
5544 // binary for the iOS simulator which is the second Objective-C
5545 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5546 // and return false.
5547 if (!printObjc1_32bit_MetaData(O, verbose))
5548 printObjc2_32bit_MetaData(O, verbose);
5553 // GuessLiteralPointer returns a string which for the item in the Mach-O file
5554 // for the address passed in as ReferenceValue for printing as a comment with
5555 // the instruction and also returns the corresponding type of that item
5556 // indirectly through ReferenceType.
5558 // If ReferenceValue is an address of literal cstring then a pointer to the
5559 // cstring is returned and ReferenceType is set to
5560 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5562 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5563 // Class ref that name is returned and the ReferenceType is set accordingly.
5565 // Lastly, literals which are Symbol address in a literal pool are looked for
5566 // and if found the symbol name is returned and ReferenceType is set to
5567 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5569 // If there is no item in the Mach-O file for the address passed in as
5570 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
5571 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5572 uint64_t ReferencePC,
5573 uint64_t *ReferenceType,
5574 struct DisassembleInfo *info) {
5575 // First see if there is an external relocation entry at the ReferencePC.
5576 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
5577 uint64_t sect_addr = info->S.getAddress();
5578 uint64_t sect_offset = ReferencePC - sect_addr;
5579 bool reloc_found = false;
5581 MachO::any_relocation_info RE;
5582 bool isExtern = false;
5584 for (const RelocationRef &Reloc : info->S.relocations()) {
5585 uint64_t RelocOffset = Reloc.getOffset();
5586 if (RelocOffset == sect_offset) {
5587 Rel = Reloc.getRawDataRefImpl();
5588 RE = info->O->getRelocation(Rel);
5589 if (info->O->isRelocationScattered(RE))
5591 isExtern = info->O->getPlainRelocationExternal(RE);
5593 symbol_iterator RelocSym = Reloc.getSymbol();
5600 // If there is an external relocation entry for a symbol in a section
5601 // then used that symbol's value for the value of the reference.
5602 if (reloc_found && isExtern) {
5603 if (info->O->getAnyRelocationPCRel(RE)) {
5604 unsigned Type = info->O->getAnyRelocationType(RE);
5605 if (Type == MachO::X86_64_RELOC_SIGNED) {
5606 ReferenceValue = Symbol.getValue();
5612 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5613 // Message refs and Class refs.
5614 bool classref, selref, msgref, cfstring;
5615 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5616 selref, msgref, cfstring);
5617 if (classref && pointer_value == 0) {
5618 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5619 // And the pointer_value in that section is typically zero as it will be
5620 // set by dyld as part of the "bind information".
5621 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5622 if (name != nullptr) {
5623 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5624 const char *class_name = strrchr(name, '$');
5625 if (class_name != nullptr && class_name[1] == '_' &&
5626 class_name[2] != '\0') {
5627 info->class_name = class_name + 2;
5634 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5636 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5637 if (name != nullptr)
5638 info->class_name = name;
5640 name = "bad class ref";
5645 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5646 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5650 if (selref && pointer_value == 0)
5651 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5653 if (pointer_value != 0)
5654 ReferenceValue = pointer_value;
5656 const char *name = GuessCstringPointer(ReferenceValue, info);
5658 if (pointer_value != 0 && selref) {
5659 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5660 info->selector_name = name;
5661 } else if (pointer_value != 0 && msgref) {
5662 info->class_name = nullptr;
5663 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5664 info->selector_name = name;
5666 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5670 // Lastly look for an indirect symbol with this ReferenceValue which is in
5671 // a literal pool. If found return that symbol name.
5672 name = GuessIndirectSymbol(ReferenceValue, info);
5674 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5681 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
5682 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
5683 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5684 // is created and returns the symbol name that matches the ReferenceValue or
5685 // nullptr if none. The ReferenceType is passed in for the IN type of
5686 // reference the instruction is making from the values in defined in the header
5687 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5688 // Out type and the ReferenceName will also be set which is added as a comment
5689 // to the disassembled instruction.
5692 // If the symbol name is a C++ mangled name then the demangled name is
5693 // returned through ReferenceName and ReferenceType is set to
5694 // LLVMDisassembler_ReferenceType_DeMangled_Name .
5697 // When this is called to get a symbol name for a branch target then the
5698 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5699 // SymbolValue will be looked for in the indirect symbol table to determine if
5700 // it is an address for a symbol stub. If so then the symbol name for that
5701 // stub is returned indirectly through ReferenceName and then ReferenceType is
5702 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5704 // When this is called with an value loaded via a PC relative load then
5705 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5706 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
5707 // or an Objective-C meta data reference. If so the output ReferenceType is
5708 // set to correspond to that as well as setting the ReferenceName.
5709 static const char *SymbolizerSymbolLookUp(void *DisInfo,
5710 uint64_t ReferenceValue,
5711 uint64_t *ReferenceType,
5712 uint64_t ReferencePC,
5713 const char **ReferenceName) {
5714 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
5715 // If no verbose symbolic information is wanted then just return nullptr.
5716 if (!info->verbose) {
5717 *ReferenceName = nullptr;
5718 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5722 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
5724 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5725 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
5726 if (*ReferenceName != nullptr) {
5727 method_reference(info, ReferenceType, ReferenceName);
5728 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5729 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5732 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5733 if (info->demangled_name != nullptr)
5734 free(info->demangled_name);
5736 info->demangled_name =
5737 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5738 if (info->demangled_name != nullptr) {
5739 *ReferenceName = info->demangled_name;
5740 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5742 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5745 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5746 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5748 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5750 method_reference(info, ReferenceType, ReferenceName);
5752 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5753 // If this is arm64 and the reference is an adrp instruction save the
5754 // instruction, passed in ReferenceValue and the address of the instruction
5755 // for use later if we see and add immediate instruction.
5756 } else if (info->O->getArch() == Triple::aarch64 &&
5757 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5758 info->adrp_inst = ReferenceValue;
5759 info->adrp_addr = ReferencePC;
5760 SymbolName = nullptr;
5761 *ReferenceName = nullptr;
5762 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5763 // If this is arm64 and reference is an add immediate instruction and we
5765 // seen an adrp instruction just before it and the adrp's Xd register
5767 // this add's Xn register reconstruct the value being referenced and look to
5768 // see if it is a literal pointer. Note the add immediate instruction is
5769 // passed in ReferenceValue.
5770 } else if (info->O->getArch() == Triple::aarch64 &&
5771 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5772 ReferencePC - 4 == info->adrp_addr &&
5773 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5774 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5775 uint32_t addxri_inst;
5776 uint64_t adrp_imm, addxri_imm;
5779 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5780 if (info->adrp_inst & 0x0200000)
5781 adrp_imm |= 0xfffffffffc000000LL;
5783 addxri_inst = ReferenceValue;
5784 addxri_imm = (addxri_inst >> 10) & 0xfff;
5785 if (((addxri_inst >> 22) & 0x3) == 1)
5788 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5789 (adrp_imm << 12) + addxri_imm;
5792 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5793 if (*ReferenceName == nullptr)
5794 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5795 // If this is arm64 and the reference is a load register instruction and we
5796 // have seen an adrp instruction just before it and the adrp's Xd register
5797 // matches this add's Xn register reconstruct the value being referenced and
5798 // look to see if it is a literal pointer. Note the load register
5799 // instruction is passed in ReferenceValue.
5800 } else if (info->O->getArch() == Triple::aarch64 &&
5801 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5802 ReferencePC - 4 == info->adrp_addr &&
5803 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5804 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5805 uint32_t ldrxui_inst;
5806 uint64_t adrp_imm, ldrxui_imm;
5809 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5810 if (info->adrp_inst & 0x0200000)
5811 adrp_imm |= 0xfffffffffc000000LL;
5813 ldrxui_inst = ReferenceValue;
5814 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5816 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5817 (adrp_imm << 12) + (ldrxui_imm << 3);
5820 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5821 if (*ReferenceName == nullptr)
5822 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5824 // If this arm64 and is an load register (PC-relative) instruction the
5825 // ReferenceValue is the PC plus the immediate value.
5826 else if (info->O->getArch() == Triple::aarch64 &&
5827 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5828 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5830 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5831 if (*ReferenceName == nullptr)
5832 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5835 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5836 if (info->demangled_name != nullptr)
5837 free(info->demangled_name);
5839 info->demangled_name =
5840 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5841 if (info->demangled_name != nullptr) {
5842 *ReferenceName = info->demangled_name;
5843 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5848 *ReferenceName = nullptr;
5849 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5855 /// \brief Emits the comments that are stored in the CommentStream.
5856 /// Each comment in the CommentStream must end with a newline.
5857 static void emitComments(raw_svector_ostream &CommentStream,
5858 SmallString<128> &CommentsToEmit,
5859 formatted_raw_ostream &FormattedOS,
5860 const MCAsmInfo &MAI) {
5861 // Flush the stream before taking its content.
5862 StringRef Comments = CommentsToEmit.str();
5863 // Get the default information for printing a comment.
5864 const char *CommentBegin = MAI.getCommentString();
5865 unsigned CommentColumn = MAI.getCommentColumn();
5866 bool IsFirst = true;
5867 while (!Comments.empty()) {
5869 FormattedOS << '\n';
5870 // Emit a line of comments.
5871 FormattedOS.PadToColumn(CommentColumn);
5872 size_t Position = Comments.find('\n');
5873 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5874 // Move after the newline character.
5875 Comments = Comments.substr(Position + 1);
5878 FormattedOS.flush();
5880 // Tell the comment stream that the vector changed underneath it.
5881 CommentsToEmit.clear();
5884 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5885 StringRef DisSegName, StringRef DisSectName) {
5886 const char *McpuDefault = nullptr;
5887 const Target *ThumbTarget = nullptr;
5888 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
5890 // GetTarget prints out stuff.
5893 if (MCPU.empty() && McpuDefault)
5896 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
5897 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
5899 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
5901 // Package up features to be passed to target/subtarget
5902 std::string FeaturesStr;
5903 if (MAttrs.size()) {
5904 SubtargetFeatures Features;
5905 for (unsigned i = 0; i != MAttrs.size(); ++i)
5906 Features.AddFeature(MAttrs[i]);
5907 FeaturesStr = Features.getString();
5910 // Set up disassembler.
5911 std::unique_ptr<const MCRegisterInfo> MRI(
5912 TheTarget->createMCRegInfo(TripleName));
5913 std::unique_ptr<const MCAsmInfo> AsmInfo(
5914 TheTarget->createMCAsmInfo(*MRI, TripleName));
5915 std::unique_ptr<const MCSubtargetInfo> STI(
5916 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
5917 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
5918 std::unique_ptr<MCDisassembler> DisAsm(
5919 TheTarget->createMCDisassembler(*STI, Ctx));
5920 std::unique_ptr<MCSymbolizer> Symbolizer;
5921 struct DisassembleInfo SymbolizerInfo;
5922 std::unique_ptr<MCRelocationInfo> RelInfo(
5923 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5925 Symbolizer.reset(TheTarget->createMCSymbolizer(
5926 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5927 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
5928 DisAsm->setSymbolizer(std::move(Symbolizer));
5930 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
5931 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
5932 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
5933 // Set the display preference for hex vs. decimal immediates.
5934 IP->setPrintImmHex(PrintImmHex);
5935 // Comment stream and backing vector.
5936 SmallString<128> CommentsToEmit;
5937 raw_svector_ostream CommentStream(CommentsToEmit);
5938 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5939 // if it is done then arm64 comments for string literals don't get printed
5940 // and some constant get printed instead and not setting it causes intel
5941 // (32-bit and 64-bit) comments printed with different spacing before the
5942 // comment causing different diffs with the 'C' disassembler library API.
5943 // IP->setCommentStream(CommentStream);
5945 if (!AsmInfo || !STI || !DisAsm || !IP) {
5946 errs() << "error: couldn't initialize disassembler for target "
5947 << TripleName << '\n';
5951 // Set up thumb disassembler.
5952 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5953 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5954 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
5955 std::unique_ptr<MCDisassembler> ThumbDisAsm;
5956 std::unique_ptr<MCInstPrinter> ThumbIP;
5957 std::unique_ptr<MCContext> ThumbCtx;
5958 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5959 struct DisassembleInfo ThumbSymbolizerInfo;
5960 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
5962 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
5964 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
5966 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
5967 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
5968 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
5969 MCContext *PtrThumbCtx = ThumbCtx.get();
5971 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
5973 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
5974 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5975 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
5976 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
5978 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
5979 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
5980 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
5981 *ThumbInstrInfo, *ThumbMRI));
5982 // Set the display preference for hex vs. decimal immediates.
5983 ThumbIP->setPrintImmHex(PrintImmHex);
5986 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
5987 errs() << "error: couldn't initialize disassembler for target "
5988 << ThumbTripleName << '\n';
5992 MachO::mach_header Header = MachOOF->getHeader();
5994 // FIXME: Using the -cfg command line option, this code used to be able to
5995 // annotate relocations with the referenced symbol's name, and if this was
5996 // inside a __[cf]string section, the data it points to. This is now replaced
5997 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
5998 std::vector<SectionRef> Sections;
5999 std::vector<SymbolRef> Symbols;
6000 SmallVector<uint64_t, 8> FoundFns;
6001 uint64_t BaseSegmentAddress;
6003 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
6004 BaseSegmentAddress);
6006 // Sort the symbols by address, just in case they didn't come in that way.
6007 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
6009 // Build a data in code table that is sorted on by the address of each entry.
6010 uint64_t BaseAddress = 0;
6011 if (Header.filetype == MachO::MH_OBJECT)
6012 BaseAddress = Sections[0].getAddress();
6014 BaseAddress = BaseSegmentAddress;
6016 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
6019 DI->getOffset(Offset);
6020 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6022 array_pod_sort(Dices.begin(), Dices.end());
6025 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6027 raw_ostream &DebugOut = nulls();
6030 std::unique_ptr<DIContext> diContext;
6031 ObjectFile *DbgObj = MachOOF;
6032 // Try to find debug info and set up the DIContext for it.
6034 // A separate DSym file path was specified, parse it as a macho file,
6035 // get the sections and supply it to the section name parsing machinery.
6036 if (!DSYMFile.empty()) {
6037 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
6038 MemoryBuffer::getFileOrSTDIN(DSYMFile);
6039 if (std::error_code EC = BufOrErr.getError()) {
6040 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
6044 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6049 // Setup the DIContext
6050 diContext.reset(new DWARFContextInMemory(*DbgObj));
6053 if (FilterSections.size() == 0)
6054 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
6056 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
6058 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6061 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
6063 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
6064 if (SegmentName != DisSegName)
6068 Sections[SectIdx].getContents(BytesStr);
6069 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6071 uint64_t SectAddress = Sections[SectIdx].getAddress();
6073 bool symbolTableWorked = false;
6075 // Create a map of symbol addresses to symbol names for use by
6076 // the SymbolizerSymbolLookUp() routine.
6077 SymbolAddressMap AddrMap;
6078 bool DisSymNameFound = false;
6079 for (const SymbolRef &Symbol : MachOOF->symbols()) {
6080 SymbolRef::Type ST = Symbol.getType();
6081 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6082 ST == SymbolRef::ST_Other) {
6083 uint64_t Address = Symbol.getValue();
6084 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6085 if (std::error_code EC = SymNameOrErr.getError())
6086 report_fatal_error(EC.message());
6087 StringRef SymName = *SymNameOrErr;
6088 AddrMap[Address] = SymName;
6089 if (!DisSymName.empty() && DisSymName == SymName)
6090 DisSymNameFound = true;
6093 if (!DisSymName.empty() && !DisSymNameFound) {
6094 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6097 // Set up the block of info used by the Symbolizer call backs.
6098 SymbolizerInfo.verbose = !NoSymbolicOperands;
6099 SymbolizerInfo.O = MachOOF;
6100 SymbolizerInfo.S = Sections[SectIdx];
6101 SymbolizerInfo.AddrMap = &AddrMap;
6102 SymbolizerInfo.Sections = &Sections;
6103 SymbolizerInfo.class_name = nullptr;
6104 SymbolizerInfo.selector_name = nullptr;
6105 SymbolizerInfo.method = nullptr;
6106 SymbolizerInfo.demangled_name = nullptr;
6107 SymbolizerInfo.bindtable = nullptr;
6108 SymbolizerInfo.adrp_addr = 0;
6109 SymbolizerInfo.adrp_inst = 0;
6110 // Same for the ThumbSymbolizer
6111 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
6112 ThumbSymbolizerInfo.O = MachOOF;
6113 ThumbSymbolizerInfo.S = Sections[SectIdx];
6114 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6115 ThumbSymbolizerInfo.Sections = &Sections;
6116 ThumbSymbolizerInfo.class_name = nullptr;
6117 ThumbSymbolizerInfo.selector_name = nullptr;
6118 ThumbSymbolizerInfo.method = nullptr;
6119 ThumbSymbolizerInfo.demangled_name = nullptr;
6120 ThumbSymbolizerInfo.bindtable = nullptr;
6121 ThumbSymbolizerInfo.adrp_addr = 0;
6122 ThumbSymbolizerInfo.adrp_inst = 0;
6124 // Disassemble symbol by symbol.
6125 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
6126 ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6127 if (std::error_code EC = SymNameOrErr.getError())
6128 report_fatal_error(EC.message());
6129 StringRef SymName = *SymNameOrErr;
6131 SymbolRef::Type ST = Symbols[SymIdx].getType();
6132 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
6135 // Make sure the symbol is defined in this section.
6136 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
6140 // If we are only disassembling one symbol see if this is that symbol.
6141 if (!DisSymName.empty() && DisSymName != SymName)
6144 // Start at the address of the symbol relative to the section's address.
6145 uint64_t Start = Symbols[SymIdx].getValue();
6146 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6147 Start -= SectionAddress;
6149 // Stop disassembling either at the beginning of the next symbol or at
6150 // the end of the section.
6151 bool containsNextSym = false;
6152 uint64_t NextSym = 0;
6153 uint64_t NextSymIdx = SymIdx + 1;
6154 while (Symbols.size() > NextSymIdx) {
6155 SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
6156 if (NextSymType == SymbolRef::ST_Function) {
6158 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
6159 NextSym = Symbols[NextSymIdx].getValue();
6160 NextSym -= SectionAddress;
6166 uint64_t SectSize = Sections[SectIdx].getSize();
6167 uint64_t End = containsNextSym ? NextSym : SectSize;
6170 symbolTableWorked = true;
6172 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6174 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6176 outs() << SymName << ":\n";
6177 DILineInfo lastLine;
6178 for (uint64_t Index = Start; Index < End; Index += Size) {
6181 uint64_t PC = SectAddress + Index;
6182 if (!NoLeadingAddr) {
6183 if (FullLeadingAddr) {
6184 if (MachOOF->is64Bit())
6185 outs() << format("%016" PRIx64, PC);
6187 outs() << format("%08" PRIx64, PC);
6189 outs() << format("%8" PRIx64 ":", PC);
6195 // Check the data in code table here to see if this is data not an
6196 // instruction to be disassembled.
6198 Dice.push_back(std::make_pair(PC, DiceRef()));
6199 dice_table_iterator DTI =
6200 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6201 compareDiceTableEntries);
6202 if (DTI != Dices.end()) {
6204 DTI->second.getLength(Length);
6206 DTI->second.getKind(Kind);
6207 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
6208 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6209 (PC == (DTI->first + Length - 1)) && (Length & 1))
6214 SmallVector<char, 64> AnnotationsBytes;
6215 raw_svector_ostream Annotations(AnnotationsBytes);
6219 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
6220 PC, DebugOut, Annotations);
6222 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
6223 DebugOut, Annotations);
6225 if (!NoShowRawInsn) {
6226 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
6228 formatted_raw_ostream FormattedOS(outs());
6229 StringRef AnnotationsStr = Annotations.str();
6231 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
6233 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
6234 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
6236 // Print debug info.
6238 DILineInfo dli = diContext->getLineInfoForAddress(PC);
6239 // Print valid line info if it changed.
6240 if (dli != lastLine && dli.Line != 0)
6241 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6247 unsigned int Arch = MachOOF->getArch();
6248 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6249 outs() << format("\t.byte 0x%02x #bad opcode\n",
6250 *(Bytes.data() + Index) & 0xff);
6251 Size = 1; // skip exactly one illegible byte and move on.
6252 } else if (Arch == Triple::aarch64) {
6253 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6254 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6255 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6256 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6257 outs() << format("\t.long\t0x%08x\n", opcode);
6260 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6262 Size = 1; // skip illegible bytes
6267 if (!symbolTableWorked) {
6268 // Reading the symbol table didn't work, disassemble the whole section.
6269 uint64_t SectAddress = Sections[SectIdx].getAddress();
6270 uint64_t SectSize = Sections[SectIdx].getSize();
6272 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
6275 uint64_t PC = SectAddress + Index;
6276 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6277 DebugOut, nulls())) {
6278 if (!NoLeadingAddr) {
6279 if (FullLeadingAddr) {
6280 if (MachOOF->is64Bit())
6281 outs() << format("%016" PRIx64, PC);
6283 outs() << format("%08" PRIx64, PC);
6285 outs() << format("%8" PRIx64 ":", PC);
6288 if (!NoShowRawInsn) {
6290 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
6292 IP->printInst(&Inst, outs(), "", *STI);
6295 unsigned int Arch = MachOOF->getArch();
6296 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6297 outs() << format("\t.byte 0x%02x #bad opcode\n",
6298 *(Bytes.data() + Index) & 0xff);
6299 InstSize = 1; // skip exactly one illegible byte and move on.
6301 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6303 InstSize = 1; // skip illegible bytes
6308 // The TripleName's need to be reset if we are called again for a different
6311 ThumbTripleName = "";
6313 if (SymbolizerInfo.method != nullptr)
6314 free(SymbolizerInfo.method);
6315 if (SymbolizerInfo.demangled_name != nullptr)
6316 free(SymbolizerInfo.demangled_name);
6317 if (SymbolizerInfo.bindtable != nullptr)
6318 delete SymbolizerInfo.bindtable;
6319 if (ThumbSymbolizerInfo.method != nullptr)
6320 free(ThumbSymbolizerInfo.method);
6321 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6322 free(ThumbSymbolizerInfo.demangled_name);
6323 if (ThumbSymbolizerInfo.bindtable != nullptr)
6324 delete ThumbSymbolizerInfo.bindtable;
6328 //===----------------------------------------------------------------------===//
6329 // __compact_unwind section dumping
6330 //===----------------------------------------------------------------------===//
6334 template <typename T> static uint64_t readNext(const char *&Buf) {
6335 using llvm::support::little;
6336 using llvm::support::unaligned;
6338 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6343 struct CompactUnwindEntry {
6344 uint32_t OffsetInSection;
6346 uint64_t FunctionAddr;
6348 uint32_t CompactEncoding;
6349 uint64_t PersonalityAddr;
6352 RelocationRef FunctionReloc;
6353 RelocationRef PersonalityReloc;
6354 RelocationRef LSDAReloc;
6356 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
6357 : OffsetInSection(Offset) {
6359 read<uint64_t>(Contents.data() + Offset);
6361 read<uint32_t>(Contents.data() + Offset);
6365 template <typename UIntPtr> void read(const char *Buf) {
6366 FunctionAddr = readNext<UIntPtr>(Buf);
6367 Length = readNext<uint32_t>(Buf);
6368 CompactEncoding = readNext<uint32_t>(Buf);
6369 PersonalityAddr = readNext<UIntPtr>(Buf);
6370 LSDAAddr = readNext<UIntPtr>(Buf);
6375 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
6376 /// and data being relocated, determine the best base Name and Addend to use for
6377 /// display purposes.
6379 /// 1. An Extern relocation will directly reference a symbol (and the data is
6380 /// then already an addend), so use that.
6381 /// 2. Otherwise the data is an offset in the object file's layout; try to find
6382 // a symbol before it in the same section, and use the offset from there.
6383 /// 3. Finally, if all that fails, fall back to an offset from the start of the
6384 /// referenced section.
6385 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6386 std::map<uint64_t, SymbolRef> &Symbols,
6387 const RelocationRef &Reloc, uint64_t Addr,
6388 StringRef &Name, uint64_t &Addend) {
6389 if (Reloc.getSymbol() != Obj->symbol_end()) {
6390 ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6391 if (std::error_code EC = NameOrErr.getError())
6392 report_fatal_error(EC.message());
6398 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
6399 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
6401 uint64_t SectionAddr = RelocSection.getAddress();
6403 auto Sym = Symbols.upper_bound(Addr);
6404 if (Sym == Symbols.begin()) {
6405 // The first symbol in the object is after this reference, the best we can
6406 // do is section-relative notation.
6407 RelocSection.getName(Name);
6408 Addend = Addr - SectionAddr;
6412 // Go back one so that SymbolAddress <= Addr.
6415 section_iterator SymSection = *Sym->second.getSection();
6416 if (RelocSection == *SymSection) {
6417 // There's a valid symbol in the same section before this reference.
6418 ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6419 if (std::error_code EC = NameOrErr.getError())
6420 report_fatal_error(EC.message());
6422 Addend = Addr - Sym->first;
6426 // There is a symbol before this reference, but it's in a different
6427 // section. Probably not helpful to mention it, so use the section name.
6428 RelocSection.getName(Name);
6429 Addend = Addr - SectionAddr;
6432 static void printUnwindRelocDest(const MachOObjectFile *Obj,
6433 std::map<uint64_t, SymbolRef> &Symbols,
6434 const RelocationRef &Reloc, uint64_t Addr) {
6438 if (!Reloc.getObject())
6441 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6445 outs() << " + " << format("0x%" PRIx64, Addend);
6449 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6450 std::map<uint64_t, SymbolRef> &Symbols,
6451 const SectionRef &CompactUnwind) {
6453 assert(Obj->isLittleEndian() &&
6454 "There should not be a big-endian .o with __compact_unwind");
6456 bool Is64 = Obj->is64Bit();
6457 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6458 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6461 CompactUnwind.getContents(Contents);
6463 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6465 // First populate the initial raw offsets, encodings and so on from the entry.
6466 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6467 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6468 CompactUnwinds.push_back(Entry);
6471 // Next we need to look at the relocations to find out what objects are
6472 // actually being referred to.
6473 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
6474 uint64_t RelocAddress = Reloc.getOffset();
6476 uint32_t EntryIdx = RelocAddress / EntrySize;
6477 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6478 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6480 if (OffsetInEntry == 0)
6481 Entry.FunctionReloc = Reloc;
6482 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6483 Entry.PersonalityReloc = Reloc;
6484 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6485 Entry.LSDAReloc = Reloc;
6487 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6490 // Finally, we're ready to print the data we've gathered.
6491 outs() << "Contents of __compact_unwind section:\n";
6492 for (auto &Entry : CompactUnwinds) {
6493 outs() << " Entry at offset "
6494 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
6496 // 1. Start of the region this entry applies to.
6497 outs() << " start: " << format("0x%" PRIx64,
6498 Entry.FunctionAddr) << ' ';
6499 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
6502 // 2. Length of the region this entry applies to.
6503 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6505 // 3. The 32-bit compact encoding.
6506 outs() << " compact encoding: "
6507 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
6509 // 4. The personality function, if present.
6510 if (Entry.PersonalityReloc.getObject()) {
6511 outs() << " personality function: "
6512 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
6513 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6514 Entry.PersonalityAddr);
6518 // 5. This entry's language-specific data area.
6519 if (Entry.LSDAReloc.getObject()) {
6520 outs() << " LSDA: " << format("0x%" PRIx64,
6521 Entry.LSDAAddr) << ' ';
6522 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6528 //===----------------------------------------------------------------------===//
6529 // __unwind_info section dumping
6530 //===----------------------------------------------------------------------===//
6532 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6533 const char *Pos = PageStart;
6534 uint32_t Kind = readNext<uint32_t>(Pos);
6536 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6538 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6539 uint16_t NumEntries = readNext<uint16_t>(Pos);
6541 Pos = PageStart + EntriesStart;
6542 for (unsigned i = 0; i < NumEntries; ++i) {
6543 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6544 uint32_t Encoding = readNext<uint32_t>(Pos);
6546 outs() << " [" << i << "]: "
6547 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6549 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
6553 static void printCompressedSecondLevelUnwindPage(
6554 const char *PageStart, uint32_t FunctionBase,
6555 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6556 const char *Pos = PageStart;
6557 uint32_t Kind = readNext<uint32_t>(Pos);
6559 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6561 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6562 uint16_t NumEntries = readNext<uint16_t>(Pos);
6564 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6565 readNext<uint16_t>(Pos);
6566 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6567 PageStart + EncodingsStart);
6569 Pos = PageStart + EntriesStart;
6570 for (unsigned i = 0; i < NumEntries; ++i) {
6571 uint32_t Entry = readNext<uint32_t>(Pos);
6572 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6573 uint32_t EncodingIdx = Entry >> 24;
6576 if (EncodingIdx < CommonEncodings.size())
6577 Encoding = CommonEncodings[EncodingIdx];
6579 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6581 outs() << " [" << i << "]: "
6582 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6584 << "encoding[" << EncodingIdx
6585 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
6589 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6590 std::map<uint64_t, SymbolRef> &Symbols,
6591 const SectionRef &UnwindInfo) {
6593 assert(Obj->isLittleEndian() &&
6594 "There should not be a big-endian .o with __unwind_info");
6596 outs() << "Contents of __unwind_info section:\n";
6599 UnwindInfo.getContents(Contents);
6600 const char *Pos = Contents.data();
6602 //===----------------------------------
6604 //===----------------------------------
6606 uint32_t Version = readNext<uint32_t>(Pos);
6607 outs() << " Version: "
6608 << format("0x%" PRIx32, Version) << '\n';
6609 assert(Version == 1 && "only understand version 1");
6611 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6612 outs() << " Common encodings array section offset: "
6613 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6614 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6615 outs() << " Number of common encodings in array: "
6616 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6618 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6619 outs() << " Personality function array section offset: "
6620 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6621 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6622 outs() << " Number of personality functions in array: "
6623 << format("0x%" PRIx32, NumPersonalities) << '\n';
6625 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6626 outs() << " Index array section offset: "
6627 << format("0x%" PRIx32, IndicesStart) << '\n';
6628 uint32_t NumIndices = readNext<uint32_t>(Pos);
6629 outs() << " Number of indices in array: "
6630 << format("0x%" PRIx32, NumIndices) << '\n';
6632 //===----------------------------------
6633 // A shared list of common encodings
6634 //===----------------------------------
6636 // These occupy indices in the range [0, N] whenever an encoding is referenced
6637 // from a compressed 2nd level index table. In practice the linker only
6638 // creates ~128 of these, so that indices are available to embed encodings in
6639 // the 2nd level index.
6641 SmallVector<uint32_t, 64> CommonEncodings;
6642 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6643 Pos = Contents.data() + CommonEncodingsStart;
6644 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6645 uint32_t Encoding = readNext<uint32_t>(Pos);
6646 CommonEncodings.push_back(Encoding);
6648 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6652 //===----------------------------------
6653 // Personality functions used in this executable
6654 //===----------------------------------
6656 // There should be only a handful of these (one per source language,
6657 // roughly). Particularly since they only get 2 bits in the compact encoding.
6659 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6660 Pos = Contents.data() + PersonalitiesStart;
6661 for (unsigned i = 0; i < NumPersonalities; ++i) {
6662 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6663 outs() << " personality[" << i + 1
6664 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6667 //===----------------------------------
6668 // The level 1 index entries
6669 //===----------------------------------
6671 // These specify an approximate place to start searching for the more detailed
6672 // information, sorted by PC.
6675 uint32_t FunctionOffset;
6676 uint32_t SecondLevelPageStart;
6680 SmallVector<IndexEntry, 4> IndexEntries;
6682 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6683 Pos = Contents.data() + IndicesStart;
6684 for (unsigned i = 0; i < NumIndices; ++i) {
6687 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6688 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6689 Entry.LSDAStart = readNext<uint32_t>(Pos);
6690 IndexEntries.push_back(Entry);
6692 outs() << " [" << i << "]: "
6693 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6695 << "2nd level page offset="
6696 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
6697 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
6700 //===----------------------------------
6701 // Next come the LSDA tables
6702 //===----------------------------------
6704 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6705 // the first top-level index's LSDAOffset to the last (sentinel).
6707 outs() << " LSDA descriptors:\n";
6708 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6709 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6710 (2 * sizeof(uint32_t));
6711 for (int i = 0; i < NumLSDAs; ++i) {
6712 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6713 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6714 outs() << " [" << i << "]: "
6715 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6717 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
6720 //===----------------------------------
6721 // Finally, the 2nd level indices
6722 //===----------------------------------
6724 // Generally these are 4K in size, and have 2 possible forms:
6725 // + Regular stores up to 511 entries with disparate encodings
6726 // + Compressed stores up to 1021 entries if few enough compact encoding
6728 outs() << " Second level indices:\n";
6729 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6730 // The final sentinel top-level index has no associated 2nd level page
6731 if (IndexEntries[i].SecondLevelPageStart == 0)
6734 outs() << " Second level index[" << i << "]: "
6735 << "offset in section="
6736 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6738 << "base function offset="
6739 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6741 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
6742 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
6744 printRegularSecondLevelUnwindPage(Pos);
6746 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6749 llvm_unreachable("Do not know how to print this kind of 2nd level page");
6753 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6754 std::map<uint64_t, SymbolRef> Symbols;
6755 for (const SymbolRef &SymRef : Obj->symbols()) {
6756 // Discard any undefined or absolute symbols. They're not going to take part
6757 // in the convenience lookup for unwind info and just take up resources.
6758 section_iterator Section = *SymRef.getSection();
6759 if (Section == Obj->section_end())
6762 uint64_t Addr = SymRef.getValue();
6763 Symbols.insert(std::make_pair(Addr, SymRef));
6766 for (const SectionRef &Section : Obj->sections()) {
6768 Section.getName(SectName);
6769 if (SectName == "__compact_unwind")
6770 printMachOCompactUnwindSection(Obj, Symbols, Section);
6771 else if (SectName == "__unwind_info")
6772 printMachOUnwindInfoSection(Obj, Symbols, Section);
6773 else if (SectName == "__eh_frame")
6774 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
6778 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6779 uint32_t cpusubtype, uint32_t filetype,
6780 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6782 outs() << "Mach header\n";
6783 outs() << " magic cputype cpusubtype caps filetype ncmds "
6784 "sizeofcmds flags\n";
6786 if (magic == MachO::MH_MAGIC)
6787 outs() << " MH_MAGIC";
6788 else if (magic == MachO::MH_MAGIC_64)
6789 outs() << "MH_MAGIC_64";
6791 outs() << format(" 0x%08" PRIx32, magic);
6793 case MachO::CPU_TYPE_I386:
6795 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6796 case MachO::CPU_SUBTYPE_I386_ALL:
6800 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6804 case MachO::CPU_TYPE_X86_64:
6805 outs() << " X86_64";
6806 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6807 case MachO::CPU_SUBTYPE_X86_64_ALL:
6810 case MachO::CPU_SUBTYPE_X86_64_H:
6811 outs() << " Haswell";
6814 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6818 case MachO::CPU_TYPE_ARM:
6820 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6821 case MachO::CPU_SUBTYPE_ARM_ALL:
6824 case MachO::CPU_SUBTYPE_ARM_V4T:
6827 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6830 case MachO::CPU_SUBTYPE_ARM_XSCALE:
6831 outs() << " XSCALE";
6833 case MachO::CPU_SUBTYPE_ARM_V6:
6836 case MachO::CPU_SUBTYPE_ARM_V6M:
6839 case MachO::CPU_SUBTYPE_ARM_V7:
6842 case MachO::CPU_SUBTYPE_ARM_V7EM:
6845 case MachO::CPU_SUBTYPE_ARM_V7K:
6848 case MachO::CPU_SUBTYPE_ARM_V7M:
6851 case MachO::CPU_SUBTYPE_ARM_V7S:
6855 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6859 case MachO::CPU_TYPE_ARM64:
6861 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6862 case MachO::CPU_SUBTYPE_ARM64_ALL:
6866 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6870 case MachO::CPU_TYPE_POWERPC:
6872 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6873 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6877 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6881 case MachO::CPU_TYPE_POWERPC64:
6883 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6884 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6888 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6893 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
6896 outs() << format(" 0x%02" PRIx32,
6897 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
6900 case MachO::MH_OBJECT:
6901 outs() << " OBJECT";
6903 case MachO::MH_EXECUTE:
6904 outs() << " EXECUTE";
6906 case MachO::MH_FVMLIB:
6907 outs() << " FVMLIB";
6909 case MachO::MH_CORE:
6912 case MachO::MH_PRELOAD:
6913 outs() << " PRELOAD";
6915 case MachO::MH_DYLIB:
6918 case MachO::MH_DYLIB_STUB:
6919 outs() << " DYLIB_STUB";
6921 case MachO::MH_DYLINKER:
6922 outs() << " DYLINKER";
6924 case MachO::MH_BUNDLE:
6925 outs() << " BUNDLE";
6927 case MachO::MH_DSYM:
6930 case MachO::MH_KEXT_BUNDLE:
6931 outs() << " KEXTBUNDLE";
6934 outs() << format(" %10u", filetype);
6937 outs() << format(" %5u", ncmds);
6938 outs() << format(" %10u", sizeofcmds);
6940 if (f & MachO::MH_NOUNDEFS) {
6941 outs() << " NOUNDEFS";
6942 f &= ~MachO::MH_NOUNDEFS;
6944 if (f & MachO::MH_INCRLINK) {
6945 outs() << " INCRLINK";
6946 f &= ~MachO::MH_INCRLINK;
6948 if (f & MachO::MH_DYLDLINK) {
6949 outs() << " DYLDLINK";
6950 f &= ~MachO::MH_DYLDLINK;
6952 if (f & MachO::MH_BINDATLOAD) {
6953 outs() << " BINDATLOAD";
6954 f &= ~MachO::MH_BINDATLOAD;
6956 if (f & MachO::MH_PREBOUND) {
6957 outs() << " PREBOUND";
6958 f &= ~MachO::MH_PREBOUND;
6960 if (f & MachO::MH_SPLIT_SEGS) {
6961 outs() << " SPLIT_SEGS";
6962 f &= ~MachO::MH_SPLIT_SEGS;
6964 if (f & MachO::MH_LAZY_INIT) {
6965 outs() << " LAZY_INIT";
6966 f &= ~MachO::MH_LAZY_INIT;
6968 if (f & MachO::MH_TWOLEVEL) {
6969 outs() << " TWOLEVEL";
6970 f &= ~MachO::MH_TWOLEVEL;
6972 if (f & MachO::MH_FORCE_FLAT) {
6973 outs() << " FORCE_FLAT";
6974 f &= ~MachO::MH_FORCE_FLAT;
6976 if (f & MachO::MH_NOMULTIDEFS) {
6977 outs() << " NOMULTIDEFS";
6978 f &= ~MachO::MH_NOMULTIDEFS;
6980 if (f & MachO::MH_NOFIXPREBINDING) {
6981 outs() << " NOFIXPREBINDING";
6982 f &= ~MachO::MH_NOFIXPREBINDING;
6984 if (f & MachO::MH_PREBINDABLE) {
6985 outs() << " PREBINDABLE";
6986 f &= ~MachO::MH_PREBINDABLE;
6988 if (f & MachO::MH_ALLMODSBOUND) {
6989 outs() << " ALLMODSBOUND";
6990 f &= ~MachO::MH_ALLMODSBOUND;
6992 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
6993 outs() << " SUBSECTIONS_VIA_SYMBOLS";
6994 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
6996 if (f & MachO::MH_CANONICAL) {
6997 outs() << " CANONICAL";
6998 f &= ~MachO::MH_CANONICAL;
7000 if (f & MachO::MH_WEAK_DEFINES) {
7001 outs() << " WEAK_DEFINES";
7002 f &= ~MachO::MH_WEAK_DEFINES;
7004 if (f & MachO::MH_BINDS_TO_WEAK) {
7005 outs() << " BINDS_TO_WEAK";
7006 f &= ~MachO::MH_BINDS_TO_WEAK;
7008 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7009 outs() << " ALLOW_STACK_EXECUTION";
7010 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7012 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7013 outs() << " DEAD_STRIPPABLE_DYLIB";
7014 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7016 if (f & MachO::MH_PIE) {
7018 f &= ~MachO::MH_PIE;
7020 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7021 outs() << " NO_REEXPORTED_DYLIBS";
7022 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7024 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7025 outs() << " MH_HAS_TLV_DESCRIPTORS";
7026 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7028 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7029 outs() << " MH_NO_HEAP_EXECUTION";
7030 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7032 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7033 outs() << " APP_EXTENSION_SAFE";
7034 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7036 if (f != 0 || flags == 0)
7037 outs() << format(" 0x%08" PRIx32, f);
7039 outs() << format(" 0x%08" PRIx32, magic);
7040 outs() << format(" %7d", cputype);
7041 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7042 outs() << format(" 0x%02" PRIx32,
7043 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7044 outs() << format(" %10u", filetype);
7045 outs() << format(" %5u", ncmds);
7046 outs() << format(" %10u", sizeofcmds);
7047 outs() << format(" 0x%08" PRIx32, flags);
7052 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7053 StringRef SegName, uint64_t vmaddr,
7054 uint64_t vmsize, uint64_t fileoff,
7055 uint64_t filesize, uint32_t maxprot,
7056 uint32_t initprot, uint32_t nsects,
7057 uint32_t flags, uint32_t object_size,
7059 uint64_t expected_cmdsize;
7060 if (cmd == MachO::LC_SEGMENT) {
7061 outs() << " cmd LC_SEGMENT\n";
7062 expected_cmdsize = nsects;
7063 expected_cmdsize *= sizeof(struct MachO::section);
7064 expected_cmdsize += sizeof(struct MachO::segment_command);
7066 outs() << " cmd LC_SEGMENT_64\n";
7067 expected_cmdsize = nsects;
7068 expected_cmdsize *= sizeof(struct MachO::section_64);
7069 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7071 outs() << " cmdsize " << cmdsize;
7072 if (cmdsize != expected_cmdsize)
7073 outs() << " Inconsistent size\n";
7076 outs() << " segname " << SegName << "\n";
7077 if (cmd == MachO::LC_SEGMENT_64) {
7078 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7079 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7081 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7082 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
7084 outs() << " fileoff " << fileoff;
7085 if (fileoff > object_size)
7086 outs() << " (past end of file)\n";
7089 outs() << " filesize " << filesize;
7090 if (fileoff + filesize > object_size)
7091 outs() << " (past end of file)\n";
7096 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7097 MachO::VM_PROT_EXECUTE)) != 0)
7098 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7100 outs() << " maxprot ";
7101 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7102 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7103 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7106 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7107 MachO::VM_PROT_EXECUTE)) != 0)
7108 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7110 outs() << " initprot ";
7111 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7112 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7113 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7116 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7117 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7119 outs() << " nsects " << nsects << "\n";
7123 outs() << " (none)\n";
7125 if (flags & MachO::SG_HIGHVM) {
7126 outs() << " HIGHVM";
7127 flags &= ~MachO::SG_HIGHVM;
7129 if (flags & MachO::SG_FVMLIB) {
7130 outs() << " FVMLIB";
7131 flags &= ~MachO::SG_FVMLIB;
7133 if (flags & MachO::SG_NORELOC) {
7134 outs() << " NORELOC";
7135 flags &= ~MachO::SG_NORELOC;
7137 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7138 outs() << " PROTECTED_VERSION_1";
7139 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7142 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7147 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7151 static void PrintSection(const char *sectname, const char *segname,
7152 uint64_t addr, uint64_t size, uint32_t offset,
7153 uint32_t align, uint32_t reloff, uint32_t nreloc,
7154 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7155 uint32_t cmd, const char *sg_segname,
7156 uint32_t filetype, uint32_t object_size,
7158 outs() << "Section\n";
7159 outs() << " sectname " << format("%.16s\n", sectname);
7160 outs() << " segname " << format("%.16s", segname);
7161 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7162 outs() << " (does not match segment)\n";
7165 if (cmd == MachO::LC_SEGMENT_64) {
7166 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7167 outs() << " size " << format("0x%016" PRIx64, size);
7169 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7170 outs() << " size " << format("0x%08" PRIx64, size);
7172 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7173 outs() << " (past end of file)\n";
7176 outs() << " offset " << offset;
7177 if (offset > object_size)
7178 outs() << " (past end of file)\n";
7181 uint32_t align_shifted = 1 << align;
7182 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7183 outs() << " reloff " << reloff;
7184 if (reloff > object_size)
7185 outs() << " (past end of file)\n";
7188 outs() << " nreloc " << nreloc;
7189 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7190 outs() << " (past end of file)\n";
7193 uint32_t section_type = flags & MachO::SECTION_TYPE;
7196 if (section_type == MachO::S_REGULAR)
7197 outs() << " S_REGULAR\n";
7198 else if (section_type == MachO::S_ZEROFILL)
7199 outs() << " S_ZEROFILL\n";
7200 else if (section_type == MachO::S_CSTRING_LITERALS)
7201 outs() << " S_CSTRING_LITERALS\n";
7202 else if (section_type == MachO::S_4BYTE_LITERALS)
7203 outs() << " S_4BYTE_LITERALS\n";
7204 else if (section_type == MachO::S_8BYTE_LITERALS)
7205 outs() << " S_8BYTE_LITERALS\n";
7206 else if (section_type == MachO::S_16BYTE_LITERALS)
7207 outs() << " S_16BYTE_LITERALS\n";
7208 else if (section_type == MachO::S_LITERAL_POINTERS)
7209 outs() << " S_LITERAL_POINTERS\n";
7210 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7211 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7212 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7213 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7214 else if (section_type == MachO::S_SYMBOL_STUBS)
7215 outs() << " S_SYMBOL_STUBS\n";
7216 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7217 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7218 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7219 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7220 else if (section_type == MachO::S_COALESCED)
7221 outs() << " S_COALESCED\n";
7222 else if (section_type == MachO::S_INTERPOSING)
7223 outs() << " S_INTERPOSING\n";
7224 else if (section_type == MachO::S_DTRACE_DOF)
7225 outs() << " S_DTRACE_DOF\n";
7226 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7227 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7228 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7229 outs() << " S_THREAD_LOCAL_REGULAR\n";
7230 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7231 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7232 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7233 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7234 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7235 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7236 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7237 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7239 outs() << format("0x%08" PRIx32, section_type) << "\n";
7240 outs() << "attributes";
7241 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7242 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7243 outs() << " PURE_INSTRUCTIONS";
7244 if (section_attributes & MachO::S_ATTR_NO_TOC)
7245 outs() << " NO_TOC";
7246 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7247 outs() << " STRIP_STATIC_SYMS";
7248 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7249 outs() << " NO_DEAD_STRIP";
7250 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7251 outs() << " LIVE_SUPPORT";
7252 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7253 outs() << " SELF_MODIFYING_CODE";
7254 if (section_attributes & MachO::S_ATTR_DEBUG)
7256 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7257 outs() << " SOME_INSTRUCTIONS";
7258 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7259 outs() << " EXT_RELOC";
7260 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7261 outs() << " LOC_RELOC";
7262 if (section_attributes == 0)
7263 outs() << " (none)";
7266 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7267 outs() << " reserved1 " << reserved1;
7268 if (section_type == MachO::S_SYMBOL_STUBS ||
7269 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7270 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7271 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7272 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7273 outs() << " (index into indirect symbol table)\n";
7276 outs() << " reserved2 " << reserved2;
7277 if (section_type == MachO::S_SYMBOL_STUBS)
7278 outs() << " (size of stubs)\n";
7283 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
7284 uint32_t object_size) {
7285 outs() << " cmd LC_SYMTAB\n";
7286 outs() << " cmdsize " << st.cmdsize;
7287 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7288 outs() << " Incorrect size\n";
7291 outs() << " symoff " << st.symoff;
7292 if (st.symoff > object_size)
7293 outs() << " (past end of file)\n";
7296 outs() << " nsyms " << st.nsyms;
7299 big_size = st.nsyms;
7300 big_size *= sizeof(struct MachO::nlist_64);
7301 big_size += st.symoff;
7302 if (big_size > object_size)
7303 outs() << " (past end of file)\n";
7307 big_size = st.nsyms;
7308 big_size *= sizeof(struct MachO::nlist);
7309 big_size += st.symoff;
7310 if (big_size > object_size)
7311 outs() << " (past end of file)\n";
7315 outs() << " stroff " << st.stroff;
7316 if (st.stroff > object_size)
7317 outs() << " (past end of file)\n";
7320 outs() << " strsize " << st.strsize;
7321 big_size = st.stroff;
7322 big_size += st.strsize;
7323 if (big_size > object_size)
7324 outs() << " (past end of file)\n";
7329 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7330 uint32_t nsyms, uint32_t object_size,
7332 outs() << " cmd LC_DYSYMTAB\n";
7333 outs() << " cmdsize " << dyst.cmdsize;
7334 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7335 outs() << " Incorrect size\n";
7338 outs() << " ilocalsym " << dyst.ilocalsym;
7339 if (dyst.ilocalsym > nsyms)
7340 outs() << " (greater than the number of symbols)\n";
7343 outs() << " nlocalsym " << dyst.nlocalsym;
7345 big_size = dyst.ilocalsym;
7346 big_size += dyst.nlocalsym;
7347 if (big_size > nsyms)
7348 outs() << " (past the end of the symbol table)\n";
7351 outs() << " iextdefsym " << dyst.iextdefsym;
7352 if (dyst.iextdefsym > nsyms)
7353 outs() << " (greater than the number of symbols)\n";
7356 outs() << " nextdefsym " << dyst.nextdefsym;
7357 big_size = dyst.iextdefsym;
7358 big_size += dyst.nextdefsym;
7359 if (big_size > nsyms)
7360 outs() << " (past the end of the symbol table)\n";
7363 outs() << " iundefsym " << dyst.iundefsym;
7364 if (dyst.iundefsym > nsyms)
7365 outs() << " (greater than the number of symbols)\n";
7368 outs() << " nundefsym " << dyst.nundefsym;
7369 big_size = dyst.iundefsym;
7370 big_size += dyst.nundefsym;
7371 if (big_size > nsyms)
7372 outs() << " (past the end of the symbol table)\n";
7375 outs() << " tocoff " << dyst.tocoff;
7376 if (dyst.tocoff > object_size)
7377 outs() << " (past end of file)\n";
7380 outs() << " ntoc " << dyst.ntoc;
7381 big_size = dyst.ntoc;
7382 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7383 big_size += dyst.tocoff;
7384 if (big_size > object_size)
7385 outs() << " (past end of file)\n";
7388 outs() << " modtaboff " << dyst.modtaboff;
7389 if (dyst.modtaboff > object_size)
7390 outs() << " (past end of file)\n";
7393 outs() << " nmodtab " << dyst.nmodtab;
7396 modtabend = dyst.nmodtab;
7397 modtabend *= sizeof(struct MachO::dylib_module_64);
7398 modtabend += dyst.modtaboff;
7400 modtabend = dyst.nmodtab;
7401 modtabend *= sizeof(struct MachO::dylib_module);
7402 modtabend += dyst.modtaboff;
7404 if (modtabend > object_size)
7405 outs() << " (past end of file)\n";
7408 outs() << " extrefsymoff " << dyst.extrefsymoff;
7409 if (dyst.extrefsymoff > object_size)
7410 outs() << " (past end of file)\n";
7413 outs() << " nextrefsyms " << dyst.nextrefsyms;
7414 big_size = dyst.nextrefsyms;
7415 big_size *= sizeof(struct MachO::dylib_reference);
7416 big_size += dyst.extrefsymoff;
7417 if (big_size > object_size)
7418 outs() << " (past end of file)\n";
7421 outs() << " indirectsymoff " << dyst.indirectsymoff;
7422 if (dyst.indirectsymoff > object_size)
7423 outs() << " (past end of file)\n";
7426 outs() << " nindirectsyms " << dyst.nindirectsyms;
7427 big_size = dyst.nindirectsyms;
7428 big_size *= sizeof(uint32_t);
7429 big_size += dyst.indirectsymoff;
7430 if (big_size > object_size)
7431 outs() << " (past end of file)\n";
7434 outs() << " extreloff " << dyst.extreloff;
7435 if (dyst.extreloff > object_size)
7436 outs() << " (past end of file)\n";
7439 outs() << " nextrel " << dyst.nextrel;
7440 big_size = dyst.nextrel;
7441 big_size *= sizeof(struct MachO::relocation_info);
7442 big_size += dyst.extreloff;
7443 if (big_size > object_size)
7444 outs() << " (past end of file)\n";
7447 outs() << " locreloff " << dyst.locreloff;
7448 if (dyst.locreloff > object_size)
7449 outs() << " (past end of file)\n";
7452 outs() << " nlocrel " << dyst.nlocrel;
7453 big_size = dyst.nlocrel;
7454 big_size *= sizeof(struct MachO::relocation_info);
7455 big_size += dyst.locreloff;
7456 if (big_size > object_size)
7457 outs() << " (past end of file)\n";
7462 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7463 uint32_t object_size) {
7464 if (dc.cmd == MachO::LC_DYLD_INFO)
7465 outs() << " cmd LC_DYLD_INFO\n";
7467 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7468 outs() << " cmdsize " << dc.cmdsize;
7469 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7470 outs() << " Incorrect size\n";
7473 outs() << " rebase_off " << dc.rebase_off;
7474 if (dc.rebase_off > object_size)
7475 outs() << " (past end of file)\n";
7478 outs() << " rebase_size " << dc.rebase_size;
7480 big_size = dc.rebase_off;
7481 big_size += dc.rebase_size;
7482 if (big_size > object_size)
7483 outs() << " (past end of file)\n";
7486 outs() << " bind_off " << dc.bind_off;
7487 if (dc.bind_off > object_size)
7488 outs() << " (past end of file)\n";
7491 outs() << " bind_size " << dc.bind_size;
7492 big_size = dc.bind_off;
7493 big_size += dc.bind_size;
7494 if (big_size > object_size)
7495 outs() << " (past end of file)\n";
7498 outs() << " weak_bind_off " << dc.weak_bind_off;
7499 if (dc.weak_bind_off > object_size)
7500 outs() << " (past end of file)\n";
7503 outs() << " weak_bind_size " << dc.weak_bind_size;
7504 big_size = dc.weak_bind_off;
7505 big_size += dc.weak_bind_size;
7506 if (big_size > object_size)
7507 outs() << " (past end of file)\n";
7510 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7511 if (dc.lazy_bind_off > object_size)
7512 outs() << " (past end of file)\n";
7515 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7516 big_size = dc.lazy_bind_off;
7517 big_size += dc.lazy_bind_size;
7518 if (big_size > object_size)
7519 outs() << " (past end of file)\n";
7522 outs() << " export_off " << dc.export_off;
7523 if (dc.export_off > object_size)
7524 outs() << " (past end of file)\n";
7527 outs() << " export_size " << dc.export_size;
7528 big_size = dc.export_off;
7529 big_size += dc.export_size;
7530 if (big_size > object_size)
7531 outs() << " (past end of file)\n";
7536 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7538 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7539 outs() << " cmd LC_ID_DYLINKER\n";
7540 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7541 outs() << " cmd LC_LOAD_DYLINKER\n";
7542 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7543 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7545 outs() << " cmd ?(" << dyld.cmd << ")\n";
7546 outs() << " cmdsize " << dyld.cmdsize;
7547 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7548 outs() << " Incorrect size\n";
7551 if (dyld.name >= dyld.cmdsize)
7552 outs() << " name ?(bad offset " << dyld.name << ")\n";
7554 const char *P = (const char *)(Ptr) + dyld.name;
7555 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7559 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7560 outs() << " cmd LC_UUID\n";
7561 outs() << " cmdsize " << uuid.cmdsize;
7562 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7563 outs() << " Incorrect size\n";
7567 for (int i = 0; i < 16; ++i) {
7568 outs() << format("%02" PRIX32, uuid.uuid[i]);
7569 if (i == 3 || i == 5 || i == 7 || i == 9)
7575 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
7576 outs() << " cmd LC_RPATH\n";
7577 outs() << " cmdsize " << rpath.cmdsize;
7578 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7579 outs() << " Incorrect size\n";
7582 if (rpath.path >= rpath.cmdsize)
7583 outs() << " path ?(bad offset " << rpath.path << ")\n";
7585 const char *P = (const char *)(Ptr) + rpath.path;
7586 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7590 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
7591 StringRef LoadCmdName;
7593 case MachO::LC_VERSION_MIN_MACOSX:
7594 LoadCmdName = "LC_VERSION_MIN_MACOSX";
7596 case MachO::LC_VERSION_MIN_IPHONEOS:
7597 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
7599 case MachO::LC_VERSION_MIN_TVOS:
7600 LoadCmdName = "LC_VERSION_MIN_TVOS";
7602 case MachO::LC_VERSION_MIN_WATCHOS:
7603 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
7606 llvm_unreachable("Unknown version min load command");
7609 outs() << " cmd " << LoadCmdName << '\n';
7610 outs() << " cmdsize " << vd.cmdsize;
7611 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7612 outs() << " Incorrect size\n";
7615 outs() << " version "
7616 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7617 << MachOObjectFile::getVersionMinMinor(vd, false);
7618 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7620 outs() << "." << Update;
7623 outs() << " sdk n/a";
7626 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7627 << MachOObjectFile::getVersionMinMinor(vd, true);
7629 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7631 outs() << "." << Update;
7635 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7636 outs() << " cmd LC_SOURCE_VERSION\n";
7637 outs() << " cmdsize " << sd.cmdsize;
7638 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7639 outs() << " Incorrect size\n";
7642 uint64_t a = (sd.version >> 40) & 0xffffff;
7643 uint64_t b = (sd.version >> 30) & 0x3ff;
7644 uint64_t c = (sd.version >> 20) & 0x3ff;
7645 uint64_t d = (sd.version >> 10) & 0x3ff;
7646 uint64_t e = sd.version & 0x3ff;
7647 outs() << " version " << a << "." << b;
7649 outs() << "." << c << "." << d << "." << e;
7651 outs() << "." << c << "." << d;
7657 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7658 outs() << " cmd LC_MAIN\n";
7659 outs() << " cmdsize " << ep.cmdsize;
7660 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7661 outs() << " Incorrect size\n";
7664 outs() << " entryoff " << ep.entryoff << "\n";
7665 outs() << " stacksize " << ep.stacksize << "\n";
7668 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7669 uint32_t object_size) {
7670 outs() << " cmd LC_ENCRYPTION_INFO\n";
7671 outs() << " cmdsize " << ec.cmdsize;
7672 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7673 outs() << " Incorrect size\n";
7676 outs() << " cryptoff " << ec.cryptoff;
7677 if (ec.cryptoff > object_size)
7678 outs() << " (past end of file)\n";
7681 outs() << " cryptsize " << ec.cryptsize;
7682 if (ec.cryptsize > object_size)
7683 outs() << " (past end of file)\n";
7686 outs() << " cryptid " << ec.cryptid << "\n";
7689 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
7690 uint32_t object_size) {
7691 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7692 outs() << " cmdsize " << ec.cmdsize;
7693 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7694 outs() << " Incorrect size\n";
7697 outs() << " cryptoff " << ec.cryptoff;
7698 if (ec.cryptoff > object_size)
7699 outs() << " (past end of file)\n";
7702 outs() << " cryptsize " << ec.cryptsize;
7703 if (ec.cryptsize > object_size)
7704 outs() << " (past end of file)\n";
7707 outs() << " cryptid " << ec.cryptid << "\n";
7708 outs() << " pad " << ec.pad << "\n";
7711 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7713 outs() << " cmd LC_LINKER_OPTION\n";
7714 outs() << " cmdsize " << lo.cmdsize;
7715 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7716 outs() << " Incorrect size\n";
7719 outs() << " count " << lo.count << "\n";
7720 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7721 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7724 while (*string == '\0' && left > 0) {
7730 outs() << " string #" << i << " " << format("%.*s\n", left, string);
7731 uint32_t NullPos = StringRef(string, left).find('\0');
7732 uint32_t len = std::min(NullPos, left) + 1;
7738 outs() << " count " << lo.count << " does not match number of strings "
7742 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7744 outs() << " cmd LC_SUB_FRAMEWORK\n";
7745 outs() << " cmdsize " << sub.cmdsize;
7746 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7747 outs() << " Incorrect size\n";
7750 if (sub.umbrella < sub.cmdsize) {
7751 const char *P = Ptr + sub.umbrella;
7752 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7754 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7758 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7760 outs() << " cmd LC_SUB_UMBRELLA\n";
7761 outs() << " cmdsize " << sub.cmdsize;
7762 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7763 outs() << " Incorrect size\n";
7766 if (sub.sub_umbrella < sub.cmdsize) {
7767 const char *P = Ptr + sub.sub_umbrella;
7768 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7770 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7774 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
7776 outs() << " cmd LC_SUB_LIBRARY\n";
7777 outs() << " cmdsize " << sub.cmdsize;
7778 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7779 outs() << " Incorrect size\n";
7782 if (sub.sub_library < sub.cmdsize) {
7783 const char *P = Ptr + sub.sub_library;
7784 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7786 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7790 static void PrintSubClientCommand(MachO::sub_client_command sub,
7792 outs() << " cmd LC_SUB_CLIENT\n";
7793 outs() << " cmdsize " << sub.cmdsize;
7794 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7795 outs() << " Incorrect size\n";
7798 if (sub.client < sub.cmdsize) {
7799 const char *P = Ptr + sub.client;
7800 outs() << " client " << P << " (offset " << sub.client << ")\n";
7802 outs() << " client ?(bad offset " << sub.client << ")\n";
7806 static void PrintRoutinesCommand(MachO::routines_command r) {
7807 outs() << " cmd LC_ROUTINES\n";
7808 outs() << " cmdsize " << r.cmdsize;
7809 if (r.cmdsize != sizeof(struct MachO::routines_command))
7810 outs() << " Incorrect size\n";
7813 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7814 outs() << " init_module " << r.init_module << "\n";
7815 outs() << " reserved1 " << r.reserved1 << "\n";
7816 outs() << " reserved2 " << r.reserved2 << "\n";
7817 outs() << " reserved3 " << r.reserved3 << "\n";
7818 outs() << " reserved4 " << r.reserved4 << "\n";
7819 outs() << " reserved5 " << r.reserved5 << "\n";
7820 outs() << " reserved6 " << r.reserved6 << "\n";
7823 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7824 outs() << " cmd LC_ROUTINES_64\n";
7825 outs() << " cmdsize " << r.cmdsize;
7826 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
7827 outs() << " Incorrect size\n";
7830 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
7831 outs() << " init_module " << r.init_module << "\n";
7832 outs() << " reserved1 " << r.reserved1 << "\n";
7833 outs() << " reserved2 " << r.reserved2 << "\n";
7834 outs() << " reserved3 " << r.reserved3 << "\n";
7835 outs() << " reserved4 " << r.reserved4 << "\n";
7836 outs() << " reserved5 " << r.reserved5 << "\n";
7837 outs() << " reserved6 " << r.reserved6 << "\n";
7840 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
7841 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
7842 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
7843 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
7844 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
7845 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
7846 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
7847 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
7848 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
7849 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
7850 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
7851 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
7852 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
7853 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
7854 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
7855 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
7856 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
7857 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
7858 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
7859 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
7860 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
7861 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
7864 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
7866 outs() << "\t mmst_reg ";
7867 for (f = 0; f < 10; f++)
7868 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
7870 outs() << "\t mmst_rsrv ";
7871 for (f = 0; f < 6; f++)
7872 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
7876 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
7878 outs() << "\t xmm_reg ";
7879 for (f = 0; f < 16; f++)
7880 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
7884 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
7885 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
7886 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
7887 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
7888 outs() << " denorm " << fpu.fpu_fcw.denorm;
7889 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
7890 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
7891 outs() << " undfl " << fpu.fpu_fcw.undfl;
7892 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
7893 outs() << "\t\t pc ";
7894 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
7895 outs() << "FP_PREC_24B ";
7896 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
7897 outs() << "FP_PREC_53B ";
7898 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
7899 outs() << "FP_PREC_64B ";
7901 outs() << fpu.fpu_fcw.pc << " ";
7903 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
7904 outs() << "FP_RND_NEAR ";
7905 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
7906 outs() << "FP_RND_DOWN ";
7907 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
7908 outs() << "FP_RND_UP ";
7909 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
7910 outs() << "FP_CHOP ";
7912 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
7913 outs() << " denorm " << fpu.fpu_fsw.denorm;
7914 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
7915 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
7916 outs() << " undfl " << fpu.fpu_fsw.undfl;
7917 outs() << " precis " << fpu.fpu_fsw.precis;
7918 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
7919 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
7920 outs() << " c0 " << fpu.fpu_fsw.c0;
7921 outs() << " c1 " << fpu.fpu_fsw.c1;
7922 outs() << " c2 " << fpu.fpu_fsw.c2;
7923 outs() << " tos " << fpu.fpu_fsw.tos;
7924 outs() << " c3 " << fpu.fpu_fsw.c3;
7925 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
7926 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
7927 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
7928 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
7929 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
7930 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
7931 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
7932 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
7933 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
7934 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
7935 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
7936 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
7938 outs() << "\t fpu_stmm0:\n";
7939 Print_mmst_reg(fpu.fpu_stmm0);
7940 outs() << "\t fpu_stmm1:\n";
7941 Print_mmst_reg(fpu.fpu_stmm1);
7942 outs() << "\t fpu_stmm2:\n";
7943 Print_mmst_reg(fpu.fpu_stmm2);
7944 outs() << "\t fpu_stmm3:\n";
7945 Print_mmst_reg(fpu.fpu_stmm3);
7946 outs() << "\t fpu_stmm4:\n";
7947 Print_mmst_reg(fpu.fpu_stmm4);
7948 outs() << "\t fpu_stmm5:\n";
7949 Print_mmst_reg(fpu.fpu_stmm5);
7950 outs() << "\t fpu_stmm6:\n";
7951 Print_mmst_reg(fpu.fpu_stmm6);
7952 outs() << "\t fpu_stmm7:\n";
7953 Print_mmst_reg(fpu.fpu_stmm7);
7954 outs() << "\t fpu_xmm0:\n";
7955 Print_xmm_reg(fpu.fpu_xmm0);
7956 outs() << "\t fpu_xmm1:\n";
7957 Print_xmm_reg(fpu.fpu_xmm1);
7958 outs() << "\t fpu_xmm2:\n";
7959 Print_xmm_reg(fpu.fpu_xmm2);
7960 outs() << "\t fpu_xmm3:\n";
7961 Print_xmm_reg(fpu.fpu_xmm3);
7962 outs() << "\t fpu_xmm4:\n";
7963 Print_xmm_reg(fpu.fpu_xmm4);
7964 outs() << "\t fpu_xmm5:\n";
7965 Print_xmm_reg(fpu.fpu_xmm5);
7966 outs() << "\t fpu_xmm6:\n";
7967 Print_xmm_reg(fpu.fpu_xmm6);
7968 outs() << "\t fpu_xmm7:\n";
7969 Print_xmm_reg(fpu.fpu_xmm7);
7970 outs() << "\t fpu_xmm8:\n";
7971 Print_xmm_reg(fpu.fpu_xmm8);
7972 outs() << "\t fpu_xmm9:\n";
7973 Print_xmm_reg(fpu.fpu_xmm9);
7974 outs() << "\t fpu_xmm10:\n";
7975 Print_xmm_reg(fpu.fpu_xmm10);
7976 outs() << "\t fpu_xmm11:\n";
7977 Print_xmm_reg(fpu.fpu_xmm11);
7978 outs() << "\t fpu_xmm12:\n";
7979 Print_xmm_reg(fpu.fpu_xmm12);
7980 outs() << "\t fpu_xmm13:\n";
7981 Print_xmm_reg(fpu.fpu_xmm13);
7982 outs() << "\t fpu_xmm14:\n";
7983 Print_xmm_reg(fpu.fpu_xmm14);
7984 outs() << "\t fpu_xmm15:\n";
7985 Print_xmm_reg(fpu.fpu_xmm15);
7986 outs() << "\t fpu_rsrv4:\n";
7987 for (uint32_t f = 0; f < 6; f++) {
7989 for (uint32_t g = 0; g < 16; g++)
7990 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
7993 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
7997 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
7998 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
7999 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8000 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8003 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8004 bool isLittleEndian, uint32_t cputype) {
8005 if (t.cmd == MachO::LC_THREAD)
8006 outs() << " cmd LC_THREAD\n";
8007 else if (t.cmd == MachO::LC_UNIXTHREAD)
8008 outs() << " cmd LC_UNIXTHREAD\n";
8010 outs() << " cmd " << t.cmd << " (unknown)\n";
8011 outs() << " cmdsize " << t.cmdsize;
8012 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8013 outs() << " Incorrect size\n";
8017 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8018 const char *end = Ptr + t.cmdsize;
8019 uint32_t flavor, count, left;
8020 if (cputype == MachO::CPU_TYPE_X86_64) {
8021 while (begin < end) {
8022 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8023 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8024 begin += sizeof(uint32_t);
8029 if (isLittleEndian != sys::IsLittleEndianHost)
8030 sys::swapByteOrder(flavor);
8031 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8032 memcpy((char *)&count, begin, sizeof(uint32_t));
8033 begin += sizeof(uint32_t);
8038 if (isLittleEndian != sys::IsLittleEndianHost)
8039 sys::swapByteOrder(count);
8040 if (flavor == MachO::x86_THREAD_STATE64) {
8041 outs() << " flavor x86_THREAD_STATE64\n";
8042 if (count == MachO::x86_THREAD_STATE64_COUNT)
8043 outs() << " count x86_THREAD_STATE64_COUNT\n";
8045 outs() << " count " << count
8046 << " (not x86_THREAD_STATE64_COUNT)\n";
8047 MachO::x86_thread_state64_t cpu64;
8049 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8050 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8051 begin += sizeof(MachO::x86_thread_state64_t);
8053 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8054 memcpy(&cpu64, begin, left);
8057 if (isLittleEndian != sys::IsLittleEndianHost)
8059 Print_x86_thread_state64_t(cpu64);
8060 } else if (flavor == MachO::x86_THREAD_STATE) {
8061 outs() << " flavor x86_THREAD_STATE\n";
8062 if (count == MachO::x86_THREAD_STATE_COUNT)
8063 outs() << " count x86_THREAD_STATE_COUNT\n";
8065 outs() << " count " << count
8066 << " (not x86_THREAD_STATE_COUNT)\n";
8067 struct MachO::x86_thread_state_t ts;
8069 if (left >= sizeof(MachO::x86_thread_state_t)) {
8070 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8071 begin += sizeof(MachO::x86_thread_state_t);
8073 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8074 memcpy(&ts, begin, left);
8077 if (isLittleEndian != sys::IsLittleEndianHost)
8079 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8080 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8081 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8082 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8084 outs() << "tsh.count " << ts.tsh.count
8085 << " (not x86_THREAD_STATE64_COUNT\n";
8086 Print_x86_thread_state64_t(ts.uts.ts64);
8088 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8089 << ts.tsh.count << "\n";
8091 } else if (flavor == MachO::x86_FLOAT_STATE) {
8092 outs() << " flavor x86_FLOAT_STATE\n";
8093 if (count == MachO::x86_FLOAT_STATE_COUNT)
8094 outs() << " count x86_FLOAT_STATE_COUNT\n";
8096 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
8097 struct MachO::x86_float_state_t fs;
8099 if (left >= sizeof(MachO::x86_float_state_t)) {
8100 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8101 begin += sizeof(MachO::x86_float_state_t);
8103 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8104 memcpy(&fs, begin, left);
8107 if (isLittleEndian != sys::IsLittleEndianHost)
8109 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8110 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
8111 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
8112 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8114 outs() << "fsh.count " << fs.fsh.count
8115 << " (not x86_FLOAT_STATE64_COUNT\n";
8116 Print_x86_float_state_t(fs.ufs.fs64);
8118 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8119 << fs.fsh.count << "\n";
8121 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8122 outs() << " flavor x86_EXCEPTION_STATE\n";
8123 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8124 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8126 outs() << " count " << count
8127 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8128 struct MachO::x86_exception_state_t es;
8130 if (left >= sizeof(MachO::x86_exception_state_t)) {
8131 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8132 begin += sizeof(MachO::x86_exception_state_t);
8134 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8135 memcpy(&es, begin, left);
8138 if (isLittleEndian != sys::IsLittleEndianHost)
8140 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8141 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
8142 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
8143 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8145 outs() << "\t esh.count " << es.esh.count
8146 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8147 Print_x86_exception_state_t(es.ues.es64);
8149 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8150 << es.esh.count << "\n";
8153 outs() << " flavor " << flavor << " (unknown)\n";
8154 outs() << " count " << count << "\n";
8155 outs() << " state (unknown)\n";
8156 begin += count * sizeof(uint32_t);
8160 while (begin < end) {
8161 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8162 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8163 begin += sizeof(uint32_t);
8168 if (isLittleEndian != sys::IsLittleEndianHost)
8169 sys::swapByteOrder(flavor);
8170 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8171 memcpy((char *)&count, begin, sizeof(uint32_t));
8172 begin += sizeof(uint32_t);
8177 if (isLittleEndian != sys::IsLittleEndianHost)
8178 sys::swapByteOrder(count);
8179 outs() << " flavor " << flavor << "\n";
8180 outs() << " count " << count << "\n";
8181 outs() << " state (Unknown cputype/cpusubtype)\n";
8182 begin += count * sizeof(uint32_t);
8187 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8188 if (dl.cmd == MachO::LC_ID_DYLIB)
8189 outs() << " cmd LC_ID_DYLIB\n";
8190 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8191 outs() << " cmd LC_LOAD_DYLIB\n";
8192 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8193 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8194 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8195 outs() << " cmd LC_REEXPORT_DYLIB\n";
8196 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8197 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8198 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8199 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8201 outs() << " cmd " << dl.cmd << " (unknown)\n";
8202 outs() << " cmdsize " << dl.cmdsize;
8203 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8204 outs() << " Incorrect size\n";
8207 if (dl.dylib.name < dl.cmdsize) {
8208 const char *P = (const char *)(Ptr) + dl.dylib.name;
8209 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8211 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8213 outs() << " time stamp " << dl.dylib.timestamp << " ";
8214 time_t t = dl.dylib.timestamp;
8215 outs() << ctime(&t);
8216 outs() << " current version ";
8217 if (dl.dylib.current_version == 0xffffffff)
8220 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8221 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8222 << (dl.dylib.current_version & 0xff) << "\n";
8223 outs() << "compatibility version ";
8224 if (dl.dylib.compatibility_version == 0xffffffff)
8227 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8228 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8229 << (dl.dylib.compatibility_version & 0xff) << "\n";
8232 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8233 uint32_t object_size) {
8234 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8235 outs() << " cmd LC_FUNCTION_STARTS\n";
8236 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8237 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8238 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8239 outs() << " cmd LC_FUNCTION_STARTS\n";
8240 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8241 outs() << " cmd LC_DATA_IN_CODE\n";
8242 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8243 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8244 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8245 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8247 outs() << " cmd " << ld.cmd << " (?)\n";
8248 outs() << " cmdsize " << ld.cmdsize;
8249 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8250 outs() << " Incorrect size\n";
8253 outs() << " dataoff " << ld.dataoff;
8254 if (ld.dataoff > object_size)
8255 outs() << " (past end of file)\n";
8258 outs() << " datasize " << ld.datasize;
8259 uint64_t big_size = ld.dataoff;
8260 big_size += ld.datasize;
8261 if (big_size > object_size)
8262 outs() << " (past end of file)\n";
8267 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8268 uint32_t cputype, bool verbose) {
8269 StringRef Buf = Obj->getData();
8271 for (const auto &Command : Obj->load_commands()) {
8272 outs() << "Load command " << Index++ << "\n";
8273 if (Command.C.cmd == MachO::LC_SEGMENT) {
8274 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8275 const char *sg_segname = SLC.segname;
8276 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8277 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8278 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8280 for (unsigned j = 0; j < SLC.nsects; j++) {
8281 MachO::section S = Obj->getSection(Command, j);
8282 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8283 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8284 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8286 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8287 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8288 const char *sg_segname = SLC_64.segname;
8289 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8290 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8291 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8292 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8293 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8294 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8295 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8296 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8297 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8298 sg_segname, filetype, Buf.size(), verbose);
8300 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8301 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8302 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
8303 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8304 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8305 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8306 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8308 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8309 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8310 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8311 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8312 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8313 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8314 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8315 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8316 PrintDyldLoadCommand(Dyld, Command.Ptr);
8317 } else if (Command.C.cmd == MachO::LC_UUID) {
8318 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8319 PrintUuidLoadCommand(Uuid);
8320 } else if (Command.C.cmd == MachO::LC_RPATH) {
8321 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8322 PrintRpathLoadCommand(Rpath, Command.Ptr);
8323 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
8324 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8325 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8326 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
8327 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8328 PrintVersionMinLoadCommand(Vd);
8329 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8330 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8331 PrintSourceVersionCommand(Sd);
8332 } else if (Command.C.cmd == MachO::LC_MAIN) {
8333 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8334 PrintEntryPointCommand(Ep);
8335 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
8336 MachO::encryption_info_command Ei =
8337 Obj->getEncryptionInfoCommand(Command);
8338 PrintEncryptionInfoCommand(Ei, Buf.size());
8339 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
8340 MachO::encryption_info_command_64 Ei =
8341 Obj->getEncryptionInfoCommand64(Command);
8342 PrintEncryptionInfoCommand64(Ei, Buf.size());
8343 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
8344 MachO::linker_option_command Lo =
8345 Obj->getLinkerOptionLoadCommand(Command);
8346 PrintLinkerOptionCommand(Lo, Command.Ptr);
8347 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8348 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8349 PrintSubFrameworkCommand(Sf, Command.Ptr);
8350 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8351 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8352 PrintSubUmbrellaCommand(Sf, Command.Ptr);
8353 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8354 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8355 PrintSubLibraryCommand(Sl, Command.Ptr);
8356 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8357 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8358 PrintSubClientCommand(Sc, Command.Ptr);
8359 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8360 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8361 PrintRoutinesCommand(Rc);
8362 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8363 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8364 PrintRoutinesCommand64(Rc);
8365 } else if (Command.C.cmd == MachO::LC_THREAD ||
8366 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8367 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8368 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
8369 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8370 Command.C.cmd == MachO::LC_ID_DYLIB ||
8371 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8372 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8373 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8374 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
8375 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8376 PrintDylibCommand(Dl, Command.Ptr);
8377 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8378 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8379 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8380 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8381 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8382 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8383 MachO::linkedit_data_command Ld =
8384 Obj->getLinkeditDataLoadCommand(Command);
8385 PrintLinkEditDataCommand(Ld, Buf.size());
8387 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8389 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8390 // TODO: get and print the raw bytes of the load command.
8392 // TODO: print all the other kinds of load commands.
8396 static void getAndPrintMachHeader(const MachOObjectFile *Obj,
8397 uint32_t &filetype, uint32_t &cputype,
8399 if (Obj->is64Bit()) {
8400 MachO::mach_header_64 H_64;
8401 H_64 = Obj->getHeader64();
8402 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8403 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8404 filetype = H_64.filetype;
8405 cputype = H_64.cputype;
8407 MachO::mach_header H;
8408 H = Obj->getHeader();
8409 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8410 H.sizeofcmds, H.flags, verbose);
8411 filetype = H.filetype;
8412 cputype = H.cputype;
8416 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8417 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
8418 uint32_t filetype = 0;
8419 uint32_t cputype = 0;
8420 getAndPrintMachHeader(file, filetype, cputype, !NonVerbose);
8421 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
8424 //===----------------------------------------------------------------------===//
8425 // export trie dumping
8426 //===----------------------------------------------------------------------===//
8428 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
8429 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8430 uint64_t Flags = Entry.flags();
8431 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8432 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8433 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8434 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8435 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8436 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8437 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8439 outs() << "[re-export] ";
8441 outs() << format("0x%08llX ",
8442 Entry.address()); // FIXME:add in base address
8443 outs() << Entry.name();
8444 if (WeakDef || ThreadLocal || Resolver || Abs) {
8445 bool NeedsComma = false;
8448 outs() << "weak_def";
8454 outs() << "per-thread";
8460 outs() << "absolute";
8466 outs() << format("resolver=0x%08llX", Entry.other());
8472 StringRef DylibName = "unknown";
8473 int Ordinal = Entry.other() - 1;
8474 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8475 if (Entry.otherName().empty())
8476 outs() << " (from " << DylibName << ")";
8478 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
8484 //===----------------------------------------------------------------------===//
8485 // rebase table dumping
8486 //===----------------------------------------------------------------------===//
8491 SegInfo(const object::MachOObjectFile *Obj);
8493 StringRef segmentName(uint32_t SegIndex);
8494 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8495 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
8496 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
8499 struct SectionInfo {
8502 StringRef SectionName;
8503 StringRef SegmentName;
8504 uint64_t OffsetInSegment;
8505 uint64_t SegmentStartAddress;
8506 uint32_t SegmentIndex;
8508 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8509 SmallVector<SectionInfo, 32> Sections;
8513 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8514 // Build table of sections so segIndex/offset pairs can be translated.
8515 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
8516 StringRef CurSegName;
8517 uint64_t CurSegAddress;
8518 for (const SectionRef &Section : Obj->sections()) {
8520 error(Section.getName(Info.SectionName));
8521 Info.Address = Section.getAddress();
8522 Info.Size = Section.getSize();
8524 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8525 if (!Info.SegmentName.equals(CurSegName)) {
8527 CurSegName = Info.SegmentName;
8528 CurSegAddress = Info.Address;
8530 Info.SegmentIndex = CurSegIndex - 1;
8531 Info.OffsetInSegment = Info.Address - CurSegAddress;
8532 Info.SegmentStartAddress = CurSegAddress;
8533 Sections.push_back(Info);
8537 StringRef SegInfo::segmentName(uint32_t SegIndex) {
8538 for (const SectionInfo &SI : Sections) {
8539 if (SI.SegmentIndex == SegIndex)
8540 return SI.SegmentName;
8542 llvm_unreachable("invalid segIndex");
8545 bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
8546 uint64_t OffsetInSeg) {
8547 for (const SectionInfo &SI : Sections) {
8548 if (SI.SegmentIndex != SegIndex)
8550 if (SI.OffsetInSegment > OffsetInSeg)
8552 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8559 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8560 uint64_t OffsetInSeg) {
8561 for (const SectionInfo &SI : Sections) {
8562 if (SI.SegmentIndex != SegIndex)
8564 if (SI.OffsetInSegment > OffsetInSeg)
8566 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8570 llvm_unreachable("segIndex and offset not in any section");
8573 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8574 return findSection(SegIndex, OffsetInSeg).SectionName;
8577 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8578 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8579 return SI.SegmentStartAddress + OffsetInSeg;
8582 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8583 // Build table of sections so names can used in final output.
8584 SegInfo sectionTable(Obj);
8586 outs() << "segment section address type\n";
8587 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8588 uint32_t SegIndex = Entry.segmentIndex();
8589 uint64_t OffsetInSeg = Entry.segmentOffset();
8590 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8591 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8592 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8594 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
8595 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8596 SegmentName.str().c_str(), SectionName.str().c_str(),
8597 Address, Entry.typeName().str().c_str());
8601 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8602 StringRef DylibName;
8604 case MachO::BIND_SPECIAL_DYLIB_SELF:
8605 return "this-image";
8606 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8607 return "main-executable";
8608 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8609 return "flat-namespace";
8612 std::error_code EC =
8613 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
8615 return "<<bad library ordinal>>";
8619 return "<<unknown special ordinal>>";
8622 //===----------------------------------------------------------------------===//
8623 // bind table dumping
8624 //===----------------------------------------------------------------------===//
8626 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8627 // Build table of sections so names can used in final output.
8628 SegInfo sectionTable(Obj);
8630 outs() << "segment section address type "
8631 "addend dylib symbol\n";
8632 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8633 uint32_t SegIndex = Entry.segmentIndex();
8634 uint64_t OffsetInSeg = Entry.segmentOffset();
8635 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8636 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8637 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8639 // Table lines look like:
8640 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
8642 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
8643 Attr = " (weak_import)";
8644 outs() << left_justify(SegmentName, 8) << " "
8645 << left_justify(SectionName, 18) << " "
8646 << format_hex(Address, 10, true) << " "
8647 << left_justify(Entry.typeName(), 8) << " "
8648 << format_decimal(Entry.addend(), 8) << " "
8649 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8650 << Entry.symbolName() << Attr << "\n";
8654 //===----------------------------------------------------------------------===//
8655 // lazy bind table dumping
8656 //===----------------------------------------------------------------------===//
8658 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8659 // Build table of sections so names can used in final output.
8660 SegInfo sectionTable(Obj);
8662 outs() << "segment section address "
8664 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8665 uint32_t SegIndex = Entry.segmentIndex();
8666 uint64_t OffsetInSeg = Entry.segmentOffset();
8667 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8668 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8669 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8671 // Table lines look like:
8672 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
8673 outs() << left_justify(SegmentName, 8) << " "
8674 << left_justify(SectionName, 18) << " "
8675 << format_hex(Address, 10, true) << " "
8676 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8677 << Entry.symbolName() << "\n";
8681 //===----------------------------------------------------------------------===//
8682 // weak bind table dumping
8683 //===----------------------------------------------------------------------===//
8685 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8686 // Build table of sections so names can used in final output.
8687 SegInfo sectionTable(Obj);
8689 outs() << "segment section address "
8690 "type addend symbol\n";
8691 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8692 // Strong symbols don't have a location to update.
8693 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
8694 outs() << " strong "
8695 << Entry.symbolName() << "\n";
8698 uint32_t SegIndex = Entry.segmentIndex();
8699 uint64_t OffsetInSeg = Entry.segmentOffset();
8700 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8701 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8702 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8704 // Table lines look like:
8705 // __DATA __data 0x00001000 pointer 0 _foo
8706 outs() << left_justify(SegmentName, 8) << " "
8707 << left_justify(SectionName, 18) << " "
8708 << format_hex(Address, 10, true) << " "
8709 << left_justify(Entry.typeName(), 8) << " "
8710 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8715 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
8716 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8717 // information for that address. If the address is found its binding symbol
8718 // name is returned. If not nullptr is returned.
8719 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8720 struct DisassembleInfo *info) {
8721 if (info->bindtable == nullptr) {
8722 info->bindtable = new (BindTable);
8723 SegInfo sectionTable(info->O);
8724 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8725 uint32_t SegIndex = Entry.segmentIndex();
8726 uint64_t OffsetInSeg = Entry.segmentOffset();
8727 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8729 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8730 const char *SymbolName = nullptr;
8731 StringRef name = Entry.symbolName();
8733 SymbolName = name.data();
8734 info->bindtable->push_back(std::make_pair(Address, SymbolName));
8737 for (bind_table_iterator BI = info->bindtable->begin(),
8738 BE = info->bindtable->end();
8740 uint64_t Address = BI->first;
8741 if (ReferenceValue == Address) {
8742 const char *SymbolName = BI->second;