1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the MachO-specific dumper for llvm-objdump.
12 //===----------------------------------------------------------------------===//
14 #include "llvm-objdump.h"
15 #include "llvm-c/Disassembler.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/DebugInfo/DIContext.h"
21 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCDisassembler.h"
25 #include "llvm/MC/MCInst.h"
26 #include "llvm/MC/MCInstPrinter.h"
27 #include "llvm/MC/MCInstrDesc.h"
28 #include "llvm/MC/MCInstrInfo.h"
29 #include "llvm/MC/MCRegisterInfo.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/Object/MachO.h"
32 #include "llvm/Object/MachOUniversal.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Endian.h"
37 #include "llvm/Support/Format.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/GraphWriter.h"
40 #include "llvm/Support/LEB128.h"
41 #include "llvm/Support/MachO.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/raw_ostream.h"
48 #include <system_error>
55 using namespace object;
59 cl::desc("Print line information from debug info if available"));
61 static cl::opt<std::string> DSYMFile("dsym",
62 cl::desc("Use .dSYM file for debug info"));
64 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
65 cl::desc("Print full leading address"));
67 static cl::opt<bool> NoLeadingAddr("no-leading-addr",
68 cl::desc("Print no leading address"));
70 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
71 cl::desc("Print Mach-O universal headers "
72 "(requires -macho)"));
75 llvm::ArchiveHeaders("archive-headers",
76 cl::desc("Print archive headers for Mach-O archives "
77 "(requires -macho)"));
80 ArchiveMemberOffsets("archive-member-offsets",
81 cl::desc("Print the offset to each archive member for "
82 "Mach-O archives (requires -macho and "
83 "-archive-headers)"));
86 llvm::IndirectSymbols("indirect-symbols",
87 cl::desc("Print indirect symbol table for Mach-O "
88 "objects (requires -macho)"));
91 llvm::DataInCode("data-in-code",
92 cl::desc("Print the data in code table for Mach-O objects "
93 "(requires -macho)"));
96 llvm::LinkOptHints("link-opt-hints",
97 cl::desc("Print the linker optimization hints for "
98 "Mach-O objects (requires -macho)"));
101 llvm::InfoPlist("info-plist",
102 cl::desc("Print the info plist section as strings for "
103 "Mach-O objects (requires -macho)"));
106 llvm::DylibsUsed("dylibs-used",
107 cl::desc("Print the shared libraries used for linked "
108 "Mach-O files (requires -macho)"));
111 llvm::DylibId("dylib-id",
112 cl::desc("Print the shared library's id for the dylib Mach-O "
113 "file (requires -macho)"));
116 llvm::NonVerbose("non-verbose",
117 cl::desc("Print the info for Mach-O objects in "
118 "non-verbose or numeric form (requires -macho)"));
121 llvm::ObjcMetaData("objc-meta-data",
122 cl::desc("Print the Objective-C runtime meta data for "
123 "Mach-O files (requires -macho)"));
125 cl::opt<std::string> llvm::DisSymName(
127 cl::desc("disassemble just this symbol's instructions (requires -macho"));
129 static cl::opt<bool> NoSymbolicOperands(
130 "no-symbolic-operands",
131 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
133 static cl::list<std::string>
134 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
137 bool ArchAll = false;
139 static std::string ThumbTripleName;
141 static const Target *GetTarget(const MachOObjectFile *MachOObj,
142 const char **McpuDefault,
143 const Target **ThumbTarget) {
144 // Figure out the target triple.
145 if (TripleName.empty()) {
146 llvm::Triple TT("unknown-unknown-unknown");
147 llvm::Triple ThumbTriple = Triple();
148 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
149 TripleName = TT.str();
150 ThumbTripleName = ThumbTriple.str();
153 // Get the target specific parser.
155 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
156 if (TheTarget && ThumbTripleName.empty())
159 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
163 errs() << "llvm-objdump: error: unable to get target for '";
165 errs() << TripleName;
167 errs() << ThumbTripleName;
168 errs() << "', see --version and --triple.\n";
172 struct SymbolSorter {
173 bool operator()(const SymbolRef &A, const SymbolRef &B) {
174 uint64_t AAddr = (A.getType() != SymbolRef::ST_Function) ? 0 : A.getValue();
175 uint64_t BAddr = (B.getType() != SymbolRef::ST_Function) ? 0 : B.getValue();
176 return AAddr < BAddr;
180 // Types for the storted data in code table that is built before disassembly
181 // and the predicate function to sort them.
182 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
183 typedef std::vector<DiceTableEntry> DiceTable;
184 typedef DiceTable::iterator dice_table_iterator;
186 // This is used to search for a data in code table entry for the PC being
187 // disassembled. The j parameter has the PC in j.first. A single data in code
188 // table entry can cover many bytes for each of its Kind's. So if the offset,
189 // aka the i.first value, of the data in code table entry plus its Length
190 // covers the PC being searched for this will return true. If not it will
192 static bool compareDiceTableEntries(const DiceTableEntry &i,
193 const DiceTableEntry &j) {
195 i.second.getLength(Length);
197 return j.first >= i.first && j.first < i.first + Length;
200 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
201 unsigned short Kind) {
202 uint32_t Value, Size = 1;
206 case MachO::DICE_KIND_DATA:
209 dumpBytes(makeArrayRef(bytes, 4), outs());
210 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
211 outs() << "\t.long " << Value;
213 } else if (Length >= 2) {
215 dumpBytes(makeArrayRef(bytes, 2), outs());
216 Value = bytes[1] << 8 | bytes[0];
217 outs() << "\t.short " << Value;
221 dumpBytes(makeArrayRef(bytes, 2), outs());
223 outs() << "\t.byte " << Value;
226 if (Kind == MachO::DICE_KIND_DATA)
227 outs() << "\t@ KIND_DATA\n";
229 outs() << "\t@ data in code kind = " << Kind << "\n";
231 case MachO::DICE_KIND_JUMP_TABLE8:
233 dumpBytes(makeArrayRef(bytes, 1), outs());
235 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
238 case MachO::DICE_KIND_JUMP_TABLE16:
240 dumpBytes(makeArrayRef(bytes, 2), outs());
241 Value = bytes[1] << 8 | bytes[0];
242 outs() << "\t.short " << format("%5u", Value & 0xffff)
243 << "\t@ KIND_JUMP_TABLE16\n";
246 case MachO::DICE_KIND_JUMP_TABLE32:
247 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
249 dumpBytes(makeArrayRef(bytes, 4), outs());
250 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
251 outs() << "\t.long " << Value;
252 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
253 outs() << "\t@ KIND_JUMP_TABLE32\n";
255 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
262 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
263 std::vector<SectionRef> &Sections,
264 std::vector<SymbolRef> &Symbols,
265 SmallVectorImpl<uint64_t> &FoundFns,
266 uint64_t &BaseSegmentAddress) {
267 for (const SymbolRef &Symbol : MachOObj->symbols()) {
268 ErrorOr<StringRef> SymName = Symbol.getName();
269 if (std::error_code EC = SymName.getError())
270 report_fatal_error(EC.message());
271 if (!SymName->startswith("ltmp"))
272 Symbols.push_back(Symbol);
275 for (const SectionRef &Section : MachOObj->sections()) {
277 Section.getName(SectName);
278 Sections.push_back(Section);
281 bool BaseSegmentAddressSet = false;
282 for (const auto &Command : MachOObj->load_commands()) {
283 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
284 // We found a function starts segment, parse the addresses for later
286 MachO::linkedit_data_command LLC =
287 MachOObj->getLinkeditDataLoadCommand(Command);
289 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
290 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
291 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
292 StringRef SegName = SLC.segname;
293 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
294 BaseSegmentAddressSet = true;
295 BaseSegmentAddress = SLC.vmaddr;
301 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
302 uint32_t n, uint32_t count,
303 uint32_t stride, uint64_t addr) {
304 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
305 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
306 if (n > nindirectsyms)
307 outs() << " (entries start past the end of the indirect symbol "
308 "table) (reserved1 field greater than the table size)";
309 else if (n + count > nindirectsyms)
310 outs() << " (entries extends past the end of the indirect symbol "
313 uint32_t cputype = O->getHeader().cputype;
314 if (cputype & MachO::CPU_ARCH_ABI64)
315 outs() << "address index";
317 outs() << "address index";
322 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
323 if (cputype & MachO::CPU_ARCH_ABI64)
324 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
326 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
327 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
328 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
329 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
333 if (indirect_symbol ==
334 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
335 outs() << "LOCAL ABSOLUTE\n";
338 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
339 outs() << "ABSOLUTE\n";
342 outs() << format("%5u ", indirect_symbol);
344 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
345 if (indirect_symbol < Symtab.nsyms) {
346 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
347 SymbolRef Symbol = *Sym;
348 ErrorOr<StringRef> SymName = Symbol.getName();
349 if (std::error_code EC = SymName.getError())
350 report_fatal_error(EC.message());
360 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
361 for (const auto &Load : O->load_commands()) {
362 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
363 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
364 for (unsigned J = 0; J < Seg.nsects; ++J) {
365 MachO::section_64 Sec = O->getSection64(Load, J);
366 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
367 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
368 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
369 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
370 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
371 section_type == MachO::S_SYMBOL_STUBS) {
373 if (section_type == MachO::S_SYMBOL_STUBS)
374 stride = Sec.reserved2;
378 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
379 << Sec.sectname << ") "
380 << "(size of stubs in reserved2 field is zero)\n";
383 uint32_t count = Sec.size / stride;
384 outs() << "Indirect symbols for (" << Sec.segname << ","
385 << Sec.sectname << ") " << count << " entries";
386 uint32_t n = Sec.reserved1;
387 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
390 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
391 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
392 for (unsigned J = 0; J < Seg.nsects; ++J) {
393 MachO::section Sec = O->getSection(Load, J);
394 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
395 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
396 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
397 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
398 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
399 section_type == MachO::S_SYMBOL_STUBS) {
401 if (section_type == MachO::S_SYMBOL_STUBS)
402 stride = Sec.reserved2;
406 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
407 << Sec.sectname << ") "
408 << "(size of stubs in reserved2 field is zero)\n";
411 uint32_t count = Sec.size / stride;
412 outs() << "Indirect symbols for (" << Sec.segname << ","
413 << Sec.sectname << ") " << count << " entries";
414 uint32_t n = Sec.reserved1;
415 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
422 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
423 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
424 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
425 outs() << "Data in code table (" << nentries << " entries)\n";
426 outs() << "offset length kind\n";
427 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
430 DI->getOffset(Offset);
431 outs() << format("0x%08" PRIx32, Offset) << " ";
433 DI->getLength(Length);
434 outs() << format("%6u", Length) << " ";
439 case MachO::DICE_KIND_DATA:
442 case MachO::DICE_KIND_JUMP_TABLE8:
443 outs() << "JUMP_TABLE8";
445 case MachO::DICE_KIND_JUMP_TABLE16:
446 outs() << "JUMP_TABLE16";
448 case MachO::DICE_KIND_JUMP_TABLE32:
449 outs() << "JUMP_TABLE32";
451 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
452 outs() << "ABS_JUMP_TABLE32";
455 outs() << format("0x%04" PRIx32, Kind);
459 outs() << format("0x%04" PRIx32, Kind);
464 static void PrintLinkOptHints(MachOObjectFile *O) {
465 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
466 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
467 uint32_t nloh = LohLC.datasize;
468 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
469 for (uint32_t i = 0; i < nloh;) {
471 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
473 outs() << " identifier " << identifier << " ";
476 switch (identifier) {
478 outs() << "AdrpAdrp\n";
481 outs() << "AdrpLdr\n";
484 outs() << "AdrpAddLdr\n";
487 outs() << "AdrpLdrGotLdr\n";
490 outs() << "AdrpAddStr\n";
493 outs() << "AdrpLdrGotStr\n";
496 outs() << "AdrpAdd\n";
499 outs() << "AdrpLdrGot\n";
502 outs() << "Unknown identifier value\n";
505 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
507 outs() << " narguments " << narguments << "\n";
511 for (uint32_t j = 0; j < narguments; j++) {
512 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
514 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
521 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
523 for (const auto &Load : O->load_commands()) {
524 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
525 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
526 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
527 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
528 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
529 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
530 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
531 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
532 if (dl.dylib.name < dl.cmdsize) {
533 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
538 outs() << " (compatibility version "
539 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
540 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
541 << (dl.dylib.compatibility_version & 0xff) << ",";
542 outs() << " current version "
543 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
544 << ((dl.dylib.current_version >> 8) & 0xff) << "."
545 << (dl.dylib.current_version & 0xff) << ")\n";
548 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
549 if (Load.C.cmd == MachO::LC_ID_DYLIB)
550 outs() << "LC_ID_DYLIB ";
551 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
552 outs() << "LC_LOAD_DYLIB ";
553 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
554 outs() << "LC_LOAD_WEAK_DYLIB ";
555 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
556 outs() << "LC_LAZY_LOAD_DYLIB ";
557 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
558 outs() << "LC_REEXPORT_DYLIB ";
559 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
560 outs() << "LC_LOAD_UPWARD_DYLIB ";
563 outs() << "command " << Index++ << "\n";
569 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
571 static void CreateSymbolAddressMap(MachOObjectFile *O,
572 SymbolAddressMap *AddrMap) {
573 // Create a map of symbol addresses to symbol names.
574 for (const SymbolRef &Symbol : O->symbols()) {
575 SymbolRef::Type ST = Symbol.getType();
576 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
577 ST == SymbolRef::ST_Other) {
578 uint64_t Address = Symbol.getValue();
579 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
580 if (std::error_code EC = SymNameOrErr.getError())
581 report_fatal_error(EC.message());
582 StringRef SymName = *SymNameOrErr;
583 if (!SymName.startswith(".objc"))
584 (*AddrMap)[Address] = SymName;
589 // GuessSymbolName is passed the address of what might be a symbol and a
590 // pointer to the SymbolAddressMap. It returns the name of a symbol
591 // with that address or nullptr if no symbol is found with that address.
592 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
593 const char *SymbolName = nullptr;
594 // A DenseMap can't lookup up some values.
595 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
596 StringRef name = AddrMap->lookup(value);
598 SymbolName = name.data();
603 static void DumpCstringChar(const char c) {
607 outs().write_escaped(p);
610 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
611 uint32_t sect_size, uint64_t sect_addr,
612 bool print_addresses) {
613 for (uint32_t i = 0; i < sect_size; i++) {
614 if (print_addresses) {
616 outs() << format("%016" PRIx64, sect_addr + i) << " ";
618 outs() << format("%08" PRIx64, sect_addr + i) << " ";
620 for (; i < sect_size && sect[i] != '\0'; i++)
621 DumpCstringChar(sect[i]);
622 if (i < sect_size && sect[i] == '\0')
627 static void DumpLiteral4(uint32_t l, float f) {
628 outs() << format("0x%08" PRIx32, l);
629 if ((l & 0x7f800000) != 0x7f800000)
630 outs() << format(" (%.16e)\n", f);
633 outs() << " (+Infinity)\n";
634 else if (l == 0xff800000)
635 outs() << " (-Infinity)\n";
636 else if ((l & 0x00400000) == 0x00400000)
637 outs() << " (non-signaling Not-a-Number)\n";
639 outs() << " (signaling Not-a-Number)\n";
643 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
644 uint32_t sect_size, uint64_t sect_addr,
645 bool print_addresses) {
646 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
647 if (print_addresses) {
649 outs() << format("%016" PRIx64, sect_addr + i) << " ";
651 outs() << format("%08" PRIx64, sect_addr + i) << " ";
654 memcpy(&f, sect + i, sizeof(float));
655 if (O->isLittleEndian() != sys::IsLittleEndianHost)
656 sys::swapByteOrder(f);
658 memcpy(&l, sect + i, sizeof(uint32_t));
659 if (O->isLittleEndian() != sys::IsLittleEndianHost)
660 sys::swapByteOrder(l);
665 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
667 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
669 if (O->isLittleEndian()) {
676 // Hi is the high word, so this is equivalent to if(isfinite(d))
677 if ((Hi & 0x7ff00000) != 0x7ff00000)
678 outs() << format(" (%.16e)\n", d);
680 if (Hi == 0x7ff00000 && Lo == 0)
681 outs() << " (+Infinity)\n";
682 else if (Hi == 0xfff00000 && Lo == 0)
683 outs() << " (-Infinity)\n";
684 else if ((Hi & 0x00080000) == 0x00080000)
685 outs() << " (non-signaling Not-a-Number)\n";
687 outs() << " (signaling Not-a-Number)\n";
691 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
692 uint32_t sect_size, uint64_t sect_addr,
693 bool print_addresses) {
694 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
695 if (print_addresses) {
697 outs() << format("%016" PRIx64, sect_addr + i) << " ";
699 outs() << format("%08" PRIx64, sect_addr + i) << " ";
702 memcpy(&d, sect + i, sizeof(double));
703 if (O->isLittleEndian() != sys::IsLittleEndianHost)
704 sys::swapByteOrder(d);
706 memcpy(&l0, sect + i, sizeof(uint32_t));
707 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
708 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
709 sys::swapByteOrder(l0);
710 sys::swapByteOrder(l1);
712 DumpLiteral8(O, l0, l1, d);
716 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
717 outs() << format("0x%08" PRIx32, l0) << " ";
718 outs() << format("0x%08" PRIx32, l1) << " ";
719 outs() << format("0x%08" PRIx32, l2) << " ";
720 outs() << format("0x%08" PRIx32, l3) << "\n";
723 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
724 uint32_t sect_size, uint64_t sect_addr,
725 bool print_addresses) {
726 for (uint32_t i = 0; i < sect_size; i += 16) {
727 if (print_addresses) {
729 outs() << format("%016" PRIx64, sect_addr + i) << " ";
731 outs() << format("%08" PRIx64, sect_addr + i) << " ";
733 uint32_t l0, l1, l2, l3;
734 memcpy(&l0, sect + i, sizeof(uint32_t));
735 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
736 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
737 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
738 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
739 sys::swapByteOrder(l0);
740 sys::swapByteOrder(l1);
741 sys::swapByteOrder(l2);
742 sys::swapByteOrder(l3);
744 DumpLiteral16(l0, l1, l2, l3);
748 static void DumpLiteralPointerSection(MachOObjectFile *O,
749 const SectionRef &Section,
750 const char *sect, uint32_t sect_size,
752 bool print_addresses) {
753 // Collect the literal sections in this Mach-O file.
754 std::vector<SectionRef> LiteralSections;
755 for (const SectionRef &Section : O->sections()) {
756 DataRefImpl Ref = Section.getRawDataRefImpl();
757 uint32_t section_type;
759 const MachO::section_64 Sec = O->getSection64(Ref);
760 section_type = Sec.flags & MachO::SECTION_TYPE;
762 const MachO::section Sec = O->getSection(Ref);
763 section_type = Sec.flags & MachO::SECTION_TYPE;
765 if (section_type == MachO::S_CSTRING_LITERALS ||
766 section_type == MachO::S_4BYTE_LITERALS ||
767 section_type == MachO::S_8BYTE_LITERALS ||
768 section_type == MachO::S_16BYTE_LITERALS)
769 LiteralSections.push_back(Section);
772 // Set the size of the literal pointer.
773 uint32_t lp_size = O->is64Bit() ? 8 : 4;
775 // Collect the external relocation symbols for the literal pointers.
776 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
777 for (const RelocationRef &Reloc : Section.relocations()) {
779 MachO::any_relocation_info RE;
780 bool isExtern = false;
781 Rel = Reloc.getRawDataRefImpl();
782 RE = O->getRelocation(Rel);
783 isExtern = O->getPlainRelocationExternal(RE);
785 uint64_t RelocOffset = Reloc.getOffset();
786 symbol_iterator RelocSym = Reloc.getSymbol();
787 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
790 array_pod_sort(Relocs.begin(), Relocs.end());
792 // Dump each literal pointer.
793 for (uint32_t i = 0; i < sect_size; i += lp_size) {
794 if (print_addresses) {
796 outs() << format("%016" PRIx64, sect_addr + i) << " ";
798 outs() << format("%08" PRIx64, sect_addr + i) << " ";
802 memcpy(&lp, sect + i, sizeof(uint64_t));
803 if (O->isLittleEndian() != sys::IsLittleEndianHost)
804 sys::swapByteOrder(lp);
807 memcpy(&li, sect + i, sizeof(uint32_t));
808 if (O->isLittleEndian() != sys::IsLittleEndianHost)
809 sys::swapByteOrder(li);
813 // First look for an external relocation entry for this literal pointer.
814 auto Reloc = std::find_if(
815 Relocs.begin(), Relocs.end(),
816 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
817 if (Reloc != Relocs.end()) {
818 symbol_iterator RelocSym = Reloc->second;
819 ErrorOr<StringRef> SymName = RelocSym->getName();
820 if (std::error_code EC = SymName.getError())
821 report_fatal_error(EC.message());
822 outs() << "external relocation entry for symbol:" << *SymName << "\n";
826 // For local references see what the section the literal pointer points to.
827 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
828 [&](const SectionRef &R) {
829 return lp >= R.getAddress() &&
830 lp < R.getAddress() + R.getSize();
832 if (Sect == LiteralSections.end()) {
833 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
837 uint64_t SectAddress = Sect->getAddress();
838 uint64_t SectSize = Sect->getSize();
841 Sect->getName(SectName);
842 DataRefImpl Ref = Sect->getRawDataRefImpl();
843 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
844 outs() << SegmentName << ":" << SectName << ":";
846 uint32_t section_type;
848 const MachO::section_64 Sec = O->getSection64(Ref);
849 section_type = Sec.flags & MachO::SECTION_TYPE;
851 const MachO::section Sec = O->getSection(Ref);
852 section_type = Sec.flags & MachO::SECTION_TYPE;
856 Sect->getContents(BytesStr);
857 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
859 switch (section_type) {
860 case MachO::S_CSTRING_LITERALS:
861 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
863 DumpCstringChar(Contents[i]);
867 case MachO::S_4BYTE_LITERALS:
869 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
871 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
872 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
873 sys::swapByteOrder(f);
874 sys::swapByteOrder(l);
878 case MachO::S_8BYTE_LITERALS: {
880 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
882 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
883 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
885 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
886 sys::swapByteOrder(f);
887 sys::swapByteOrder(l0);
888 sys::swapByteOrder(l1);
890 DumpLiteral8(O, l0, l1, d);
893 case MachO::S_16BYTE_LITERALS: {
894 uint32_t l0, l1, l2, l3;
895 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
896 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
898 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
900 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
902 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
903 sys::swapByteOrder(l0);
904 sys::swapByteOrder(l1);
905 sys::swapByteOrder(l2);
906 sys::swapByteOrder(l3);
908 DumpLiteral16(l0, l1, l2, l3);
915 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
916 uint32_t sect_size, uint64_t sect_addr,
917 SymbolAddressMap *AddrMap,
921 stride = sizeof(uint64_t);
923 stride = sizeof(uint32_t);
924 for (uint32_t i = 0; i < sect_size; i += stride) {
925 const char *SymbolName = nullptr;
927 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
928 uint64_t pointer_value;
929 memcpy(&pointer_value, sect + i, stride);
930 if (O->isLittleEndian() != sys::IsLittleEndianHost)
931 sys::swapByteOrder(pointer_value);
932 outs() << format("0x%016" PRIx64, pointer_value);
934 SymbolName = GuessSymbolName(pointer_value, AddrMap);
936 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
937 uint32_t pointer_value;
938 memcpy(&pointer_value, sect + i, stride);
939 if (O->isLittleEndian() != sys::IsLittleEndianHost)
940 sys::swapByteOrder(pointer_value);
941 outs() << format("0x%08" PRIx32, pointer_value);
943 SymbolName = GuessSymbolName(pointer_value, AddrMap);
946 outs() << " " << SymbolName;
951 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
952 uint32_t size, uint64_t addr) {
953 uint32_t cputype = O->getHeader().cputype;
954 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
956 for (uint32_t i = 0; i < size; i += j, addr += j) {
958 outs() << format("%016" PRIx64, addr) << "\t";
960 outs() << format("%08" PRIx64, addr) << "\t";
961 for (j = 0; j < 16 && i + j < size; j++) {
962 uint8_t byte_word = *(sect + i + j);
963 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
969 for (uint32_t i = 0; i < size; i += j, addr += j) {
971 outs() << format("%016" PRIx64, addr) << "\t";
973 outs() << format("%08" PRIx64, sect) << "\t";
974 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
975 j += sizeof(int32_t)) {
976 if (i + j + sizeof(int32_t) < size) {
978 memcpy(&long_word, sect + i + j, sizeof(int32_t));
979 if (O->isLittleEndian() != sys::IsLittleEndianHost)
980 sys::swapByteOrder(long_word);
981 outs() << format("%08" PRIx32, long_word) << " ";
983 for (uint32_t k = 0; i + j + k < size; k++) {
984 uint8_t byte_word = *(sect + i + j);
985 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
994 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
995 StringRef DisSegName, StringRef DisSectName);
996 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
997 uint32_t size, uint32_t addr);
999 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1001 SymbolAddressMap AddrMap;
1003 CreateSymbolAddressMap(O, &AddrMap);
1005 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1006 StringRef DumpSection = FilterSections[i];
1007 std::pair<StringRef, StringRef> DumpSegSectName;
1008 DumpSegSectName = DumpSection.split(',');
1009 StringRef DumpSegName, DumpSectName;
1010 if (DumpSegSectName.second.size()) {
1011 DumpSegName = DumpSegSectName.first;
1012 DumpSectName = DumpSegSectName.second;
1015 DumpSectName = DumpSegSectName.first;
1017 for (const SectionRef &Section : O->sections()) {
1019 Section.getName(SectName);
1020 DataRefImpl Ref = Section.getRawDataRefImpl();
1021 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1022 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1023 (SectName == DumpSectName)) {
1025 uint32_t section_flags;
1027 const MachO::section_64 Sec = O->getSection64(Ref);
1028 section_flags = Sec.flags;
1031 const MachO::section Sec = O->getSection(Ref);
1032 section_flags = Sec.flags;
1034 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1037 Section.getContents(BytesStr);
1038 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1039 uint32_t sect_size = BytesStr.size();
1040 uint64_t sect_addr = Section.getAddress();
1042 outs() << "Contents of (" << SegName << "," << SectName
1046 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1047 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1048 DisassembleMachO(Filename, O, SegName, SectName);
1051 if (SegName == "__TEXT" && SectName == "__info_plist") {
1055 if (SegName == "__OBJC" && SectName == "__protocol") {
1056 DumpProtocolSection(O, sect, sect_size, sect_addr);
1059 switch (section_type) {
1060 case MachO::S_REGULAR:
1061 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1063 case MachO::S_ZEROFILL:
1064 outs() << "zerofill section and has no contents in the file\n";
1066 case MachO::S_CSTRING_LITERALS:
1067 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1069 case MachO::S_4BYTE_LITERALS:
1070 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1072 case MachO::S_8BYTE_LITERALS:
1073 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1075 case MachO::S_16BYTE_LITERALS:
1076 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1078 case MachO::S_LITERAL_POINTERS:
1079 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1082 case MachO::S_MOD_INIT_FUNC_POINTERS:
1083 case MachO::S_MOD_TERM_FUNC_POINTERS:
1084 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1088 outs() << "Unknown section type ("
1089 << format("0x%08" PRIx32, section_type) << ")\n";
1090 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1094 if (section_type == MachO::S_ZEROFILL)
1095 outs() << "zerofill section and has no contents in the file\n";
1097 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1104 static void DumpInfoPlistSectionContents(StringRef Filename,
1105 MachOObjectFile *O) {
1106 for (const SectionRef &Section : O->sections()) {
1108 Section.getName(SectName);
1109 DataRefImpl Ref = Section.getRawDataRefImpl();
1110 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1111 if (SegName == "__TEXT" && SectName == "__info_plist") {
1112 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1114 Section.getContents(BytesStr);
1115 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1122 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1123 // and if it is and there is a list of architecture flags is specified then
1124 // check to make sure this Mach-O file is one of those architectures or all
1125 // architectures were specified. If not then an error is generated and this
1126 // routine returns false. Else it returns true.
1127 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1128 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1129 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1130 bool ArchFound = false;
1131 MachO::mach_header H;
1132 MachO::mach_header_64 H_64;
1134 if (MachO->is64Bit()) {
1135 H_64 = MachO->MachOObjectFile::getHeader64();
1136 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1138 H = MachO->MachOObjectFile::getHeader();
1139 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1142 for (i = 0; i < ArchFlags.size(); ++i) {
1143 if (ArchFlags[i] == T.getArchName())
1148 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1149 << "architecture: " + ArchFlags[i] + "\n";
1156 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1158 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1159 // archive member and or in a slice of a universal file. It prints the
1160 // the file name and header info and then processes it according to the
1161 // command line options.
1162 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1163 StringRef ArchiveMemberName = StringRef(),
1164 StringRef ArchitectureName = StringRef()) {
1165 // If we are doing some processing here on the Mach-O file print the header
1166 // info. And don't print it otherwise like in the case of printing the
1167 // UniversalHeaders or ArchiveHeaders.
1168 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
1169 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1170 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
1172 if (!ArchiveMemberName.empty())
1173 outs() << '(' << ArchiveMemberName << ')';
1174 if (!ArchitectureName.empty())
1175 outs() << " (architecture " << ArchitectureName << ")";
1180 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1181 if (IndirectSymbols)
1182 PrintIndirectSymbols(MachOOF, !NonVerbose);
1184 PrintDataInCodeTable(MachOOF, !NonVerbose);
1186 PrintLinkOptHints(MachOOF);
1188 PrintRelocations(MachOOF);
1190 PrintSectionHeaders(MachOOF);
1191 if (SectionContents)
1192 PrintSectionContents(MachOOF);
1193 if (FilterSections.size() != 0)
1194 DumpSectionContents(Filename, MachOOF, !NonVerbose);
1196 DumpInfoPlistSectionContents(Filename, MachOOF);
1198 PrintDylibs(MachOOF, false);
1200 PrintDylibs(MachOOF, true);
1202 PrintSymbolTable(MachOOF);
1204 printMachOUnwindInfo(MachOOF);
1206 printMachOFileHeader(MachOOF);
1208 printObjcMetaData(MachOOF, !NonVerbose);
1210 printExportsTrie(MachOOF);
1212 printRebaseTable(MachOOF);
1214 printBindTable(MachOOF);
1216 printLazyBindTable(MachOOF);
1218 printWeakBindTable(MachOOF);
1221 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1222 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1223 outs() << " cputype (" << cputype << ")\n";
1224 outs() << " cpusubtype (" << cpusubtype << ")\n";
1227 // printCPUType() helps print_fat_headers by printing the cputype and
1228 // pusubtype (symbolically for the one's it knows about).
1229 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1231 case MachO::CPU_TYPE_I386:
1232 switch (cpusubtype) {
1233 case MachO::CPU_SUBTYPE_I386_ALL:
1234 outs() << " cputype CPU_TYPE_I386\n";
1235 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1238 printUnknownCPUType(cputype, cpusubtype);
1242 case MachO::CPU_TYPE_X86_64:
1243 switch (cpusubtype) {
1244 case MachO::CPU_SUBTYPE_X86_64_ALL:
1245 outs() << " cputype CPU_TYPE_X86_64\n";
1246 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1248 case MachO::CPU_SUBTYPE_X86_64_H:
1249 outs() << " cputype CPU_TYPE_X86_64\n";
1250 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1253 printUnknownCPUType(cputype, cpusubtype);
1257 case MachO::CPU_TYPE_ARM:
1258 switch (cpusubtype) {
1259 case MachO::CPU_SUBTYPE_ARM_ALL:
1260 outs() << " cputype CPU_TYPE_ARM\n";
1261 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1263 case MachO::CPU_SUBTYPE_ARM_V4T:
1264 outs() << " cputype CPU_TYPE_ARM\n";
1265 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1267 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1268 outs() << " cputype CPU_TYPE_ARM\n";
1269 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1271 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1272 outs() << " cputype CPU_TYPE_ARM\n";
1273 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1275 case MachO::CPU_SUBTYPE_ARM_V6:
1276 outs() << " cputype CPU_TYPE_ARM\n";
1277 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1279 case MachO::CPU_SUBTYPE_ARM_V6M:
1280 outs() << " cputype CPU_TYPE_ARM\n";
1281 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1283 case MachO::CPU_SUBTYPE_ARM_V7:
1284 outs() << " cputype CPU_TYPE_ARM\n";
1285 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1287 case MachO::CPU_SUBTYPE_ARM_V7EM:
1288 outs() << " cputype CPU_TYPE_ARM\n";
1289 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1291 case MachO::CPU_SUBTYPE_ARM_V7K:
1292 outs() << " cputype CPU_TYPE_ARM\n";
1293 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1295 case MachO::CPU_SUBTYPE_ARM_V7M:
1296 outs() << " cputype CPU_TYPE_ARM\n";
1297 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1299 case MachO::CPU_SUBTYPE_ARM_V7S:
1300 outs() << " cputype CPU_TYPE_ARM\n";
1301 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1304 printUnknownCPUType(cputype, cpusubtype);
1308 case MachO::CPU_TYPE_ARM64:
1309 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1310 case MachO::CPU_SUBTYPE_ARM64_ALL:
1311 outs() << " cputype CPU_TYPE_ARM64\n";
1312 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1315 printUnknownCPUType(cputype, cpusubtype);
1320 printUnknownCPUType(cputype, cpusubtype);
1325 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1327 outs() << "Fat headers\n";
1329 outs() << "fat_magic FAT_MAGIC\n";
1331 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1333 uint32_t nfat_arch = UB->getNumberOfObjects();
1334 StringRef Buf = UB->getData();
1335 uint64_t size = Buf.size();
1336 uint64_t big_size = sizeof(struct MachO::fat_header) +
1337 nfat_arch * sizeof(struct MachO::fat_arch);
1338 outs() << "nfat_arch " << UB->getNumberOfObjects();
1340 outs() << " (malformed, contains zero architecture types)\n";
1341 else if (big_size > size)
1342 outs() << " (malformed, architectures past end of file)\n";
1346 for (uint32_t i = 0; i < nfat_arch; ++i) {
1347 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1348 uint32_t cputype = OFA.getCPUType();
1349 uint32_t cpusubtype = OFA.getCPUSubType();
1350 outs() << "architecture ";
1351 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1352 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1353 uint32_t other_cputype = other_OFA.getCPUType();
1354 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1355 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1356 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1357 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1358 outs() << "(illegal duplicate architecture) ";
1363 outs() << OFA.getArchTypeName() << "\n";
1364 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1366 outs() << i << "\n";
1367 outs() << " cputype " << cputype << "\n";
1368 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1372 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1373 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1375 outs() << " capabilities "
1376 << format("0x%" PRIx32,
1377 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1378 outs() << " offset " << OFA.getOffset();
1379 if (OFA.getOffset() > size)
1380 outs() << " (past end of file)";
1381 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1382 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1384 outs() << " size " << OFA.getSize();
1385 big_size = OFA.getOffset() + OFA.getSize();
1386 if (big_size > size)
1387 outs() << " (past end of file)";
1389 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1394 static void printArchiveChild(const Archive::Child &C, bool verbose,
1395 bool print_offset) {
1397 outs() << C.getChildOffset() << "\t";
1398 sys::fs::perms Mode = C.getAccessMode();
1400 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1401 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1403 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1404 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1405 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1406 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1407 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1408 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1409 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1410 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1411 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1413 outs() << format("0%o ", Mode);
1416 unsigned UID = C.getUID();
1417 outs() << format("%3d/", UID);
1418 unsigned GID = C.getGID();
1419 outs() << format("%-3d ", GID);
1420 ErrorOr<uint64_t> Size = C.getRawSize();
1421 if (std::error_code EC = Size.getError())
1422 report_fatal_error(EC.message());
1423 outs() << format("%5" PRId64, Size.get()) << " ";
1425 StringRef RawLastModified = C.getRawLastModified();
1428 if (RawLastModified.getAsInteger(10, Seconds))
1429 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1431 // Since cime(3) returns a 26 character string of the form:
1432 // "Sun Sep 16 01:03:52 1973\n\0"
1433 // just print 24 characters.
1435 outs() << format("%.24s ", ctime(&t));
1438 outs() << RawLastModified << " ";
1442 ErrorOr<StringRef> NameOrErr = C.getName();
1443 if (NameOrErr.getError()) {
1444 StringRef RawName = C.getRawName();
1445 outs() << RawName << "\n";
1447 StringRef Name = NameOrErr.get();
1448 outs() << Name << "\n";
1451 StringRef RawName = C.getRawName();
1452 outs() << RawName << "\n";
1456 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1457 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1459 if (std::error_code EC = I->getError())
1460 report_fatal_error(EC.message());
1461 const Archive::Child &C = **I;
1462 printArchiveChild(C, verbose, print_offset);
1466 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1467 // -arch flags selecting just those slices as specified by them and also parses
1468 // archive files. Then for each individual Mach-O file ProcessMachO() is
1469 // called to process the file based on the command line options.
1470 void llvm::ParseInputMachO(StringRef Filename) {
1471 // Check for -arch all and verifiy the -arch flags are valid.
1472 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1473 if (ArchFlags[i] == "all") {
1476 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1477 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1478 "'for the -arch option\n";
1484 // Attempt to open the binary.
1485 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1486 if (std::error_code EC = BinaryOrErr.getError()) {
1487 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
1490 Binary &Bin = *BinaryOrErr.get().getBinary();
1492 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1493 outs() << "Archive : " << Filename << "\n";
1495 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
1496 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1498 if (std::error_code EC = I->getError())
1499 report_error(Filename, EC);
1501 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1502 if (ChildOrErr.getError())
1504 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1505 if (!checkMachOAndArchFlags(O, Filename))
1507 ProcessMachO(Filename, O, O->getFileName());
1512 if (UniversalHeaders) {
1513 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1514 printMachOUniversalHeaders(UB, !NonVerbose);
1516 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1517 // If we have a list of architecture flags specified dump only those.
1518 if (!ArchAll && ArchFlags.size() != 0) {
1519 // Look for a slice in the universal binary that matches each ArchFlag.
1521 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1523 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1524 E = UB->end_objects();
1526 if (ArchFlags[i] == I->getArchTypeName()) {
1528 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1529 I->getAsObjectFile();
1530 std::string ArchitectureName = "";
1531 if (ArchFlags.size() > 1)
1532 ArchitectureName = I->getArchTypeName();
1534 ObjectFile &O = *ObjOrErr.get();
1535 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1536 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1537 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1538 I->getAsArchive()) {
1539 std::unique_ptr<Archive> &A = *AOrErr;
1540 outs() << "Archive : " << Filename;
1541 if (!ArchitectureName.empty())
1542 outs() << " (architecture " << ArchitectureName << ")";
1545 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1546 for (Archive::child_iterator AI = A->child_begin(),
1547 AE = A->child_end();
1549 if (std::error_code EC = AI->getError())
1550 report_error(Filename, EC);
1551 auto &C = AI->get();
1552 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1553 if (ChildOrErr.getError())
1555 if (MachOObjectFile *O =
1556 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1557 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1563 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1564 << "architecture: " + ArchFlags[i] + "\n";
1570 // No architecture flags were specified so if this contains a slice that
1571 // matches the host architecture dump only that.
1573 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1574 E = UB->end_objects();
1576 if (MachOObjectFile::getHostArch().getArchName() ==
1577 I->getArchTypeName()) {
1578 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1579 std::string ArchiveName;
1580 ArchiveName.clear();
1582 ObjectFile &O = *ObjOrErr.get();
1583 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1584 ProcessMachO(Filename, MachOOF);
1585 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1586 I->getAsArchive()) {
1587 std::unique_ptr<Archive> &A = *AOrErr;
1588 outs() << "Archive : " << Filename << "\n";
1590 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1591 for (Archive::child_iterator AI = A->child_begin(),
1592 AE = A->child_end();
1594 if (std::error_code EC = AI->getError())
1595 report_error(Filename, EC);
1596 auto &C = AI->get();
1597 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1598 if (ChildOrErr.getError())
1600 if (MachOObjectFile *O =
1601 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1602 ProcessMachO(Filename, O, O->getFileName());
1609 // Either all architectures have been specified or none have been specified
1610 // and this does not contain the host architecture so dump all the slices.
1611 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1612 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1613 E = UB->end_objects();
1615 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1616 std::string ArchitectureName = "";
1617 if (moreThanOneArch)
1618 ArchitectureName = I->getArchTypeName();
1620 ObjectFile &Obj = *ObjOrErr.get();
1621 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1622 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1623 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1624 std::unique_ptr<Archive> &A = *AOrErr;
1625 outs() << "Archive : " << Filename;
1626 if (!ArchitectureName.empty())
1627 outs() << " (architecture " << ArchitectureName << ")";
1630 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1631 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1633 if (std::error_code EC = AI->getError())
1634 report_error(Filename, EC);
1635 auto &C = AI->get();
1636 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1637 if (ChildOrErr.getError())
1639 if (MachOObjectFile *O =
1640 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1641 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1642 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1650 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1651 if (!checkMachOAndArchFlags(O, Filename))
1653 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1654 ProcessMachO(Filename, MachOOF);
1656 errs() << "llvm-objdump: '" << Filename << "': "
1657 << "Object is not a Mach-O file type.\n";
1659 errs() << "llvm-objdump: '" << Filename << "': "
1660 << "Unrecognized file type.\n";
1663 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1664 typedef std::vector<BindInfoEntry> BindTable;
1665 typedef BindTable::iterator bind_table_iterator;
1667 // The block of info used by the Symbolizer call backs.
1668 struct DisassembleInfo {
1672 SymbolAddressMap *AddrMap;
1673 std::vector<SectionRef> *Sections;
1674 const char *class_name;
1675 const char *selector_name;
1677 char *demangled_name;
1680 BindTable *bindtable;
1684 // SymbolizerGetOpInfo() is the operand information call back function.
1685 // This is called to get the symbolic information for operand(s) of an
1686 // instruction when it is being done. This routine does this from
1687 // the relocation information, symbol table, etc. That block of information
1688 // is a pointer to the struct DisassembleInfo that was passed when the
1689 // disassembler context was created and passed to back to here when
1690 // called back by the disassembler for instruction operands that could have
1691 // relocation information. The address of the instruction containing operand is
1692 // at the Pc parameter. The immediate value the operand has is passed in
1693 // op_info->Value and is at Offset past the start of the instruction and has a
1694 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1695 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1696 // names and addends of the symbolic expression to add for the operand. The
1697 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1698 // information is returned then this function returns 1 else it returns 0.
1699 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1700 uint64_t Size, int TagType, void *TagBuf) {
1701 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1702 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1703 uint64_t value = op_info->Value;
1705 // Make sure all fields returned are zero if we don't set them.
1706 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1707 op_info->Value = value;
1709 // If the TagType is not the value 1 which it code knows about or if no
1710 // verbose symbolic information is wanted then just return 0, indicating no
1711 // information is being returned.
1712 if (TagType != 1 || !info->verbose)
1715 unsigned int Arch = info->O->getArch();
1716 if (Arch == Triple::x86) {
1717 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1719 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1721 // Search the external relocation entries of a fully linked image
1722 // (if any) for an entry that matches this segment offset.
1723 // uint32_t seg_offset = (Pc + Offset);
1726 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1727 // for an entry for this section offset.
1728 uint32_t sect_addr = info->S.getAddress();
1729 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1730 bool reloc_found = false;
1732 MachO::any_relocation_info RE;
1733 bool isExtern = false;
1735 bool r_scattered = false;
1736 uint32_t r_value, pair_r_value, r_type;
1737 for (const RelocationRef &Reloc : info->S.relocations()) {
1738 uint64_t RelocOffset = Reloc.getOffset();
1739 if (RelocOffset == sect_offset) {
1740 Rel = Reloc.getRawDataRefImpl();
1741 RE = info->O->getRelocation(Rel);
1742 r_type = info->O->getAnyRelocationType(RE);
1743 r_scattered = info->O->isRelocationScattered(RE);
1745 r_value = info->O->getScatteredRelocationValue(RE);
1746 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1747 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1748 DataRefImpl RelNext = Rel;
1749 info->O->moveRelocationNext(RelNext);
1750 MachO::any_relocation_info RENext;
1751 RENext = info->O->getRelocation(RelNext);
1752 if (info->O->isRelocationScattered(RENext))
1753 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1758 isExtern = info->O->getPlainRelocationExternal(RE);
1760 symbol_iterator RelocSym = Reloc.getSymbol();
1768 if (reloc_found && isExtern) {
1769 ErrorOr<StringRef> SymName = Symbol.getName();
1770 if (std::error_code EC = SymName.getError())
1771 report_fatal_error(EC.message());
1772 const char *name = SymName->data();
1773 op_info->AddSymbol.Present = 1;
1774 op_info->AddSymbol.Name = name;
1775 // For i386 extern relocation entries the value in the instruction is
1776 // the offset from the symbol, and value is already set in op_info->Value.
1779 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1780 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1781 const char *add = GuessSymbolName(r_value, info->AddrMap);
1782 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1783 uint32_t offset = value - (r_value - pair_r_value);
1784 op_info->AddSymbol.Present = 1;
1786 op_info->AddSymbol.Name = add;
1788 op_info->AddSymbol.Value = r_value;
1789 op_info->SubtractSymbol.Present = 1;
1791 op_info->SubtractSymbol.Name = sub;
1793 op_info->SubtractSymbol.Value = pair_r_value;
1794 op_info->Value = offset;
1799 if (Arch == Triple::x86_64) {
1800 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1802 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1804 // Search the external relocation entries of a fully linked image
1805 // (if any) for an entry that matches this segment offset.
1806 // uint64_t seg_offset = (Pc + Offset);
1809 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1810 // for an entry for this section offset.
1811 uint64_t sect_addr = info->S.getAddress();
1812 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1813 bool reloc_found = false;
1815 MachO::any_relocation_info RE;
1816 bool isExtern = false;
1818 for (const RelocationRef &Reloc : info->S.relocations()) {
1819 uint64_t RelocOffset = Reloc.getOffset();
1820 if (RelocOffset == sect_offset) {
1821 Rel = Reloc.getRawDataRefImpl();
1822 RE = info->O->getRelocation(Rel);
1823 // NOTE: Scattered relocations don't exist on x86_64.
1824 isExtern = info->O->getPlainRelocationExternal(RE);
1826 symbol_iterator RelocSym = Reloc.getSymbol();
1833 if (reloc_found && isExtern) {
1834 // The Value passed in will be adjusted by the Pc if the instruction
1835 // adds the Pc. But for x86_64 external relocation entries the Value
1836 // is the offset from the external symbol.
1837 if (info->O->getAnyRelocationPCRel(RE))
1838 op_info->Value -= Pc + Offset + Size;
1839 ErrorOr<StringRef> SymName = Symbol.getName();
1840 if (std::error_code EC = SymName.getError())
1841 report_fatal_error(EC.message());
1842 const char *name = SymName->data();
1843 unsigned Type = info->O->getAnyRelocationType(RE);
1844 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1845 DataRefImpl RelNext = Rel;
1846 info->O->moveRelocationNext(RelNext);
1847 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1848 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1849 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1850 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1851 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1852 op_info->SubtractSymbol.Present = 1;
1853 op_info->SubtractSymbol.Name = name;
1854 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1855 Symbol = *RelocSymNext;
1856 ErrorOr<StringRef> SymNameNext = Symbol.getName();
1857 if (std::error_code EC = SymNameNext.getError())
1858 report_fatal_error(EC.message());
1859 name = SymNameNext->data();
1862 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1863 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1864 op_info->AddSymbol.Present = 1;
1865 op_info->AddSymbol.Name = name;
1870 if (Arch == Triple::arm) {
1871 if (Offset != 0 || (Size != 4 && Size != 2))
1873 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1875 // Search the external relocation entries of a fully linked image
1876 // (if any) for an entry that matches this segment offset.
1877 // uint32_t seg_offset = (Pc + Offset);
1880 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1881 // for an entry for this section offset.
1882 uint32_t sect_addr = info->S.getAddress();
1883 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1885 MachO::any_relocation_info RE;
1886 bool isExtern = false;
1888 bool r_scattered = false;
1889 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1891 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1892 [&](const RelocationRef &Reloc) {
1893 uint64_t RelocOffset = Reloc.getOffset();
1894 return RelocOffset == sect_offset;
1897 if (Reloc == info->S.relocations().end())
1900 Rel = Reloc->getRawDataRefImpl();
1901 RE = info->O->getRelocation(Rel);
1902 r_length = info->O->getAnyRelocationLength(RE);
1903 r_scattered = info->O->isRelocationScattered(RE);
1905 r_value = info->O->getScatteredRelocationValue(RE);
1906 r_type = info->O->getScatteredRelocationType(RE);
1908 r_type = info->O->getAnyRelocationType(RE);
1909 isExtern = info->O->getPlainRelocationExternal(RE);
1911 symbol_iterator RelocSym = Reloc->getSymbol();
1915 if (r_type == MachO::ARM_RELOC_HALF ||
1916 r_type == MachO::ARM_RELOC_SECTDIFF ||
1917 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1918 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1919 DataRefImpl RelNext = Rel;
1920 info->O->moveRelocationNext(RelNext);
1921 MachO::any_relocation_info RENext;
1922 RENext = info->O->getRelocation(RelNext);
1923 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1924 if (info->O->isRelocationScattered(RENext))
1925 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1929 ErrorOr<StringRef> SymName = Symbol.getName();
1930 if (std::error_code EC = SymName.getError())
1931 report_fatal_error(EC.message());
1932 const char *name = SymName->data();
1933 op_info->AddSymbol.Present = 1;
1934 op_info->AddSymbol.Name = name;
1936 case MachO::ARM_RELOC_HALF:
1937 if ((r_length & 0x1) == 1) {
1938 op_info->Value = value << 16 | other_half;
1939 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1941 op_info->Value = other_half << 16 | value;
1942 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1950 // If we have a branch that is not an external relocation entry then
1951 // return 0 so the code in tryAddingSymbolicOperand() can use the
1952 // SymbolLookUp call back with the branch target address to look up the
1953 // symbol and possiblity add an annotation for a symbol stub.
1954 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1955 r_type == MachO::ARM_THUMB_RELOC_BR22))
1958 uint32_t offset = 0;
1959 if (r_type == MachO::ARM_RELOC_HALF ||
1960 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1961 if ((r_length & 0x1) == 1)
1962 value = value << 16 | other_half;
1964 value = other_half << 16 | value;
1966 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1967 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1968 offset = value - r_value;
1972 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1973 if ((r_length & 0x1) == 1)
1974 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1976 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1977 const char *add = GuessSymbolName(r_value, info->AddrMap);
1978 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1979 int32_t offset = value - (r_value - pair_r_value);
1980 op_info->AddSymbol.Present = 1;
1982 op_info->AddSymbol.Name = add;
1984 op_info->AddSymbol.Value = r_value;
1985 op_info->SubtractSymbol.Present = 1;
1987 op_info->SubtractSymbol.Name = sub;
1989 op_info->SubtractSymbol.Value = pair_r_value;
1990 op_info->Value = offset;
1994 op_info->AddSymbol.Present = 1;
1995 op_info->Value = offset;
1996 if (r_type == MachO::ARM_RELOC_HALF) {
1997 if ((r_length & 0x1) == 1)
1998 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2000 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2002 const char *add = GuessSymbolName(value, info->AddrMap);
2003 if (add != nullptr) {
2004 op_info->AddSymbol.Name = add;
2007 op_info->AddSymbol.Value = value;
2010 if (Arch == Triple::aarch64) {
2011 if (Offset != 0 || Size != 4)
2013 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2015 // Search the external relocation entries of a fully linked image
2016 // (if any) for an entry that matches this segment offset.
2017 // uint64_t seg_offset = (Pc + Offset);
2020 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2021 // for an entry for this section offset.
2022 uint64_t sect_addr = info->S.getAddress();
2023 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2025 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2026 [&](const RelocationRef &Reloc) {
2027 uint64_t RelocOffset = Reloc.getOffset();
2028 return RelocOffset == sect_offset;
2031 if (Reloc == info->S.relocations().end())
2034 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2035 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2036 uint32_t r_type = info->O->getAnyRelocationType(RE);
2037 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2038 DataRefImpl RelNext = Rel;
2039 info->O->moveRelocationNext(RelNext);
2040 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2042 value = info->O->getPlainRelocationSymbolNum(RENext);
2043 op_info->Value = value;
2046 // NOTE: Scattered relocations don't exist on arm64.
2047 if (!info->O->getPlainRelocationExternal(RE))
2049 ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
2050 if (std::error_code EC = SymName.getError())
2051 report_fatal_error(EC.message());
2052 const char *name = SymName->data();
2053 op_info->AddSymbol.Present = 1;
2054 op_info->AddSymbol.Name = name;
2057 case MachO::ARM64_RELOC_PAGE21:
2059 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2061 case MachO::ARM64_RELOC_PAGEOFF12:
2063 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2065 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2067 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2069 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2071 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2073 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2074 /* @tvlppage is not implemented in llvm-mc */
2075 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2077 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2078 /* @tvlppageoff is not implemented in llvm-mc */
2079 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2082 case MachO::ARM64_RELOC_BRANCH26:
2083 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2091 // GuessCstringPointer is passed the address of what might be a pointer to a
2092 // literal string in a cstring section. If that address is in a cstring section
2093 // it returns a pointer to that string. Else it returns nullptr.
2094 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2095 struct DisassembleInfo *info) {
2096 for (const auto &Load : info->O->load_commands()) {
2097 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2098 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2099 for (unsigned J = 0; J < Seg.nsects; ++J) {
2100 MachO::section_64 Sec = info->O->getSection64(Load, J);
2101 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2102 if (section_type == MachO::S_CSTRING_LITERALS &&
2103 ReferenceValue >= Sec.addr &&
2104 ReferenceValue < Sec.addr + Sec.size) {
2105 uint64_t sect_offset = ReferenceValue - Sec.addr;
2106 uint64_t object_offset = Sec.offset + sect_offset;
2107 StringRef MachOContents = info->O->getData();
2108 uint64_t object_size = MachOContents.size();
2109 const char *object_addr = (const char *)MachOContents.data();
2110 if (object_offset < object_size) {
2111 const char *name = object_addr + object_offset;
2118 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2119 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2120 for (unsigned J = 0; J < Seg.nsects; ++J) {
2121 MachO::section Sec = info->O->getSection(Load, J);
2122 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2123 if (section_type == MachO::S_CSTRING_LITERALS &&
2124 ReferenceValue >= Sec.addr &&
2125 ReferenceValue < Sec.addr + Sec.size) {
2126 uint64_t sect_offset = ReferenceValue - Sec.addr;
2127 uint64_t object_offset = Sec.offset + sect_offset;
2128 StringRef MachOContents = info->O->getData();
2129 uint64_t object_size = MachOContents.size();
2130 const char *object_addr = (const char *)MachOContents.data();
2131 if (object_offset < object_size) {
2132 const char *name = object_addr + object_offset;
2144 // GuessIndirectSymbol returns the name of the indirect symbol for the
2145 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2146 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2147 // symbol name being referenced by the stub or pointer.
2148 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2149 struct DisassembleInfo *info) {
2150 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2151 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2152 for (const auto &Load : info->O->load_commands()) {
2153 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2154 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2155 for (unsigned J = 0; J < Seg.nsects; ++J) {
2156 MachO::section_64 Sec = info->O->getSection64(Load, J);
2157 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2158 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2159 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2160 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2161 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2162 section_type == MachO::S_SYMBOL_STUBS) &&
2163 ReferenceValue >= Sec.addr &&
2164 ReferenceValue < Sec.addr + Sec.size) {
2166 if (section_type == MachO::S_SYMBOL_STUBS)
2167 stride = Sec.reserved2;
2172 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2173 if (index < Dysymtab.nindirectsyms) {
2174 uint32_t indirect_symbol =
2175 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2176 if (indirect_symbol < Symtab.nsyms) {
2177 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2178 SymbolRef Symbol = *Sym;
2179 ErrorOr<StringRef> SymName = Symbol.getName();
2180 if (std::error_code EC = SymName.getError())
2181 report_fatal_error(EC.message());
2182 const char *name = SymName->data();
2188 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2189 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2190 for (unsigned J = 0; J < Seg.nsects; ++J) {
2191 MachO::section Sec = info->O->getSection(Load, J);
2192 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2193 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2194 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2195 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2196 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2197 section_type == MachO::S_SYMBOL_STUBS) &&
2198 ReferenceValue >= Sec.addr &&
2199 ReferenceValue < Sec.addr + Sec.size) {
2201 if (section_type == MachO::S_SYMBOL_STUBS)
2202 stride = Sec.reserved2;
2207 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2208 if (index < Dysymtab.nindirectsyms) {
2209 uint32_t indirect_symbol =
2210 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2211 if (indirect_symbol < Symtab.nsyms) {
2212 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2213 SymbolRef Symbol = *Sym;
2214 ErrorOr<StringRef> SymName = Symbol.getName();
2215 if (std::error_code EC = SymName.getError())
2216 report_fatal_error(EC.message());
2217 const char *name = SymName->data();
2228 // method_reference() is called passing it the ReferenceName that might be
2229 // a reference it to an Objective-C method call. If so then it allocates and
2230 // assembles a method call string with the values last seen and saved in
2231 // the DisassembleInfo's class_name and selector_name fields. This is saved
2232 // into the method field of the info and any previous string is free'ed.
2233 // Then the class_name field in the info is set to nullptr. The method call
2234 // string is set into ReferenceName and ReferenceType is set to
2235 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2236 // then both ReferenceType and ReferenceName are left unchanged.
2237 static void method_reference(struct DisassembleInfo *info,
2238 uint64_t *ReferenceType,
2239 const char **ReferenceName) {
2240 unsigned int Arch = info->O->getArch();
2241 if (*ReferenceName != nullptr) {
2242 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2243 if (info->selector_name != nullptr) {
2244 if (info->method != nullptr)
2246 if (info->class_name != nullptr) {
2247 info->method = (char *)malloc(5 + strlen(info->class_name) +
2248 strlen(info->selector_name));
2249 if (info->method != nullptr) {
2250 strcpy(info->method, "+[");
2251 strcat(info->method, info->class_name);
2252 strcat(info->method, " ");
2253 strcat(info->method, info->selector_name);
2254 strcat(info->method, "]");
2255 *ReferenceName = info->method;
2256 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2259 info->method = (char *)malloc(9 + strlen(info->selector_name));
2260 if (info->method != nullptr) {
2261 if (Arch == Triple::x86_64)
2262 strcpy(info->method, "-[%rdi ");
2263 else if (Arch == Triple::aarch64)
2264 strcpy(info->method, "-[x0 ");
2266 strcpy(info->method, "-[r? ");
2267 strcat(info->method, info->selector_name);
2268 strcat(info->method, "]");
2269 *ReferenceName = info->method;
2270 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2273 info->class_name = nullptr;
2275 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2276 if (info->selector_name != nullptr) {
2277 if (info->method != nullptr)
2279 info->method = (char *)malloc(17 + strlen(info->selector_name));
2280 if (info->method != nullptr) {
2281 if (Arch == Triple::x86_64)
2282 strcpy(info->method, "-[[%rdi super] ");
2283 else if (Arch == Triple::aarch64)
2284 strcpy(info->method, "-[[x0 super] ");
2286 strcpy(info->method, "-[[r? super] ");
2287 strcat(info->method, info->selector_name);
2288 strcat(info->method, "]");
2289 *ReferenceName = info->method;
2290 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2292 info->class_name = nullptr;
2298 // GuessPointerPointer() is passed the address of what might be a pointer to
2299 // a reference to an Objective-C class, selector, message ref or cfstring.
2300 // If so the value of the pointer is returned and one of the booleans are set
2301 // to true. If not zero is returned and all the booleans are set to false.
2302 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2303 struct DisassembleInfo *info,
2304 bool &classref, bool &selref, bool &msgref,
2310 for (const auto &Load : info->O->load_commands()) {
2311 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2312 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2313 for (unsigned J = 0; J < Seg.nsects; ++J) {
2314 MachO::section_64 Sec = info->O->getSection64(Load, J);
2315 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2316 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2317 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2318 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2319 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2320 ReferenceValue >= Sec.addr &&
2321 ReferenceValue < Sec.addr + Sec.size) {
2322 uint64_t sect_offset = ReferenceValue - Sec.addr;
2323 uint64_t object_offset = Sec.offset + sect_offset;
2324 StringRef MachOContents = info->O->getData();
2325 uint64_t object_size = MachOContents.size();
2326 const char *object_addr = (const char *)MachOContents.data();
2327 if (object_offset < object_size) {
2328 uint64_t pointer_value;
2329 memcpy(&pointer_value, object_addr + object_offset,
2331 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2332 sys::swapByteOrder(pointer_value);
2333 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2335 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2336 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2338 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2339 ReferenceValue + 8 < Sec.addr + Sec.size) {
2341 memcpy(&pointer_value, object_addr + object_offset + 8,
2343 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2344 sys::swapByteOrder(pointer_value);
2345 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2347 return pointer_value;
2354 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2359 // get_pointer_64 returns a pointer to the bytes in the object file at the
2360 // Address from a section in the Mach-O file. And indirectly returns the
2361 // offset into the section, number of bytes left in the section past the offset
2362 // and which section is was being referenced. If the Address is not in a
2363 // section nullptr is returned.
2364 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2365 uint32_t &left, SectionRef &S,
2366 DisassembleInfo *info,
2367 bool objc_only = false) {
2371 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2372 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2373 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2378 ((*(info->Sections))[SectIdx]).getName(SectName);
2379 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2380 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2381 if (SegName != "__OBJC" && SectName != "__cstring")
2384 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2385 S = (*(info->Sections))[SectIdx];
2386 offset = Address - SectAddress;
2387 left = SectSize - offset;
2388 StringRef SectContents;
2389 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2390 return SectContents.data() + offset;
2396 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2397 uint32_t &left, SectionRef &S,
2398 DisassembleInfo *info,
2399 bool objc_only = false) {
2400 return get_pointer_64(Address, offset, left, S, info, objc_only);
2403 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2404 // the symbol indirectly through n_value. Based on the relocation information
2405 // for the specified section offset in the specified section reference.
2406 // If no relocation information is found and a non-zero ReferenceValue for the
2407 // symbol is passed, look up that address in the info's AddrMap.
2408 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2409 DisassembleInfo *info, uint64_t &n_value,
2410 uint64_t ReferenceValue = 0) {
2415 // See if there is an external relocation entry at the sect_offset.
2416 bool reloc_found = false;
2418 MachO::any_relocation_info RE;
2419 bool isExtern = false;
2421 for (const RelocationRef &Reloc : S.relocations()) {
2422 uint64_t RelocOffset = Reloc.getOffset();
2423 if (RelocOffset == sect_offset) {
2424 Rel = Reloc.getRawDataRefImpl();
2425 RE = info->O->getRelocation(Rel);
2426 if (info->O->isRelocationScattered(RE))
2428 isExtern = info->O->getPlainRelocationExternal(RE);
2430 symbol_iterator RelocSym = Reloc.getSymbol();
2437 // If there is an external relocation entry for a symbol in this section
2438 // at this section_offset then use that symbol's value for the n_value
2439 // and return its name.
2440 const char *SymbolName = nullptr;
2441 if (reloc_found && isExtern) {
2442 n_value = Symbol.getValue();
2443 ErrorOr<StringRef> NameOrError = Symbol.getName();
2444 if (std::error_code EC = NameOrError.getError())
2445 report_fatal_error(EC.message());
2446 StringRef Name = *NameOrError;
2447 if (!Name.empty()) {
2448 SymbolName = Name.data();
2453 // TODO: For fully linked images, look through the external relocation
2454 // entries off the dynamic symtab command. For these the r_offset is from the
2455 // start of the first writeable segment in the Mach-O file. So the offset
2456 // to this section from that segment is passed to this routine by the caller,
2457 // as the database_offset. Which is the difference of the section's starting
2458 // address and the first writable segment.
2460 // NOTE: need add passing the database_offset to this routine.
2462 // We did not find an external relocation entry so look up the ReferenceValue
2463 // as an address of a symbol and if found return that symbol's name.
2464 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2469 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2470 DisassembleInfo *info,
2471 uint32_t ReferenceValue) {
2473 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2476 // These are structs in the Objective-C meta data and read to produce the
2477 // comments for disassembly. While these are part of the ABI they are no
2478 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2480 // The cfstring object in a 64-bit Mach-O file.
2481 struct cfstring64_t {
2482 uint64_t isa; // class64_t * (64-bit pointer)
2483 uint64_t flags; // flag bits
2484 uint64_t characters; // char * (64-bit pointer)
2485 uint64_t length; // number of non-NULL characters in above
2488 // The class object in a 64-bit Mach-O file.
2490 uint64_t isa; // class64_t * (64-bit pointer)
2491 uint64_t superclass; // class64_t * (64-bit pointer)
2492 uint64_t cache; // Cache (64-bit pointer)
2493 uint64_t vtable; // IMP * (64-bit pointer)
2494 uint64_t data; // class_ro64_t * (64-bit pointer)
2498 uint32_t isa; /* class32_t * (32-bit pointer) */
2499 uint32_t superclass; /* class32_t * (32-bit pointer) */
2500 uint32_t cache; /* Cache (32-bit pointer) */
2501 uint32_t vtable; /* IMP * (32-bit pointer) */
2502 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2505 struct class_ro64_t {
2507 uint32_t instanceStart;
2508 uint32_t instanceSize;
2510 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2511 uint64_t name; // const char * (64-bit pointer)
2512 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2513 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2514 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2515 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2516 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2519 struct class_ro32_t {
2521 uint32_t instanceStart;
2522 uint32_t instanceSize;
2523 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2524 uint32_t name; /* const char * (32-bit pointer) */
2525 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2526 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2527 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2528 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2529 uint32_t baseProperties; /* const struct objc_property_list *
2533 /* Values for class_ro{64,32}_t->flags */
2534 #define RO_META (1 << 0)
2535 #define RO_ROOT (1 << 1)
2536 #define RO_HAS_CXX_STRUCTORS (1 << 2)
2538 struct method_list64_t {
2541 /* struct method64_t first; These structures follow inline */
2544 struct method_list32_t {
2547 /* struct method32_t first; These structures follow inline */
2551 uint64_t name; /* SEL (64-bit pointer) */
2552 uint64_t types; /* const char * (64-bit pointer) */
2553 uint64_t imp; /* IMP (64-bit pointer) */
2557 uint32_t name; /* SEL (32-bit pointer) */
2558 uint32_t types; /* const char * (32-bit pointer) */
2559 uint32_t imp; /* IMP (32-bit pointer) */
2562 struct protocol_list64_t {
2563 uint64_t count; /* uintptr_t (a 64-bit value) */
2564 /* struct protocol64_t * list[0]; These pointers follow inline */
2567 struct protocol_list32_t {
2568 uint32_t count; /* uintptr_t (a 32-bit value) */
2569 /* struct protocol32_t * list[0]; These pointers follow inline */
2572 struct protocol64_t {
2573 uint64_t isa; /* id * (64-bit pointer) */
2574 uint64_t name; /* const char * (64-bit pointer) */
2575 uint64_t protocols; /* struct protocol_list64_t *
2577 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2578 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2579 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2580 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2581 uint64_t instanceProperties; /* struct objc_property_list *
2585 struct protocol32_t {
2586 uint32_t isa; /* id * (32-bit pointer) */
2587 uint32_t name; /* const char * (32-bit pointer) */
2588 uint32_t protocols; /* struct protocol_list_t *
2590 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2591 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2592 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2593 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2594 uint32_t instanceProperties; /* struct objc_property_list *
2598 struct ivar_list64_t {
2601 /* struct ivar64_t first; These structures follow inline */
2604 struct ivar_list32_t {
2607 /* struct ivar32_t first; These structures follow inline */
2611 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2612 uint64_t name; /* const char * (64-bit pointer) */
2613 uint64_t type; /* const char * (64-bit pointer) */
2619 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2620 uint32_t name; /* const char * (32-bit pointer) */
2621 uint32_t type; /* const char * (32-bit pointer) */
2626 struct objc_property_list64 {
2629 /* struct objc_property64 first; These structures follow inline */
2632 struct objc_property_list32 {
2635 /* struct objc_property32 first; These structures follow inline */
2638 struct objc_property64 {
2639 uint64_t name; /* const char * (64-bit pointer) */
2640 uint64_t attributes; /* const char * (64-bit pointer) */
2643 struct objc_property32 {
2644 uint32_t name; /* const char * (32-bit pointer) */
2645 uint32_t attributes; /* const char * (32-bit pointer) */
2648 struct category64_t {
2649 uint64_t name; /* const char * (64-bit pointer) */
2650 uint64_t cls; /* struct class_t * (64-bit pointer) */
2651 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2652 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2653 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2654 uint64_t instanceProperties; /* struct objc_property_list *
2658 struct category32_t {
2659 uint32_t name; /* const char * (32-bit pointer) */
2660 uint32_t cls; /* struct class_t * (32-bit pointer) */
2661 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2662 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2663 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2664 uint32_t instanceProperties; /* struct objc_property_list *
2668 struct objc_image_info64 {
2672 struct objc_image_info32 {
2676 struct imageInfo_t {
2680 /* masks for objc_image_info.flags */
2681 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2682 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2684 struct message_ref64 {
2685 uint64_t imp; /* IMP (64-bit pointer) */
2686 uint64_t sel; /* SEL (64-bit pointer) */
2689 struct message_ref32 {
2690 uint32_t imp; /* IMP (32-bit pointer) */
2691 uint32_t sel; /* SEL (32-bit pointer) */
2694 // Objective-C 1 (32-bit only) meta data structs.
2696 struct objc_module_t {
2699 uint32_t name; /* char * (32-bit pointer) */
2700 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2703 struct objc_symtab_t {
2704 uint32_t sel_ref_cnt;
2705 uint32_t refs; /* SEL * (32-bit pointer) */
2706 uint16_t cls_def_cnt;
2707 uint16_t cat_def_cnt;
2708 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2711 struct objc_class_t {
2712 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2713 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2714 uint32_t name; /* const char * (32-bit pointer) */
2717 int32_t instance_size;
2718 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2719 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2720 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2721 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2724 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2725 // class is not a metaclass
2726 #define CLS_CLASS 0x1
2727 // class is a metaclass
2728 #define CLS_META 0x2
2730 struct objc_category_t {
2731 uint32_t category_name; /* char * (32-bit pointer) */
2732 uint32_t class_name; /* char * (32-bit pointer) */
2733 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2734 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2735 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2738 struct objc_ivar_t {
2739 uint32_t ivar_name; /* char * (32-bit pointer) */
2740 uint32_t ivar_type; /* char * (32-bit pointer) */
2741 int32_t ivar_offset;
2744 struct objc_ivar_list_t {
2746 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2749 struct objc_method_list_t {
2750 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2751 int32_t method_count;
2752 // struct objc_method_t method_list[1]; /* variable length structure */
2755 struct objc_method_t {
2756 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2757 uint32_t method_types; /* char * (32-bit pointer) */
2758 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2762 struct objc_protocol_list_t {
2763 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2765 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2766 // (32-bit pointer) */
2769 struct objc_protocol_t {
2770 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2771 uint32_t protocol_name; /* char * (32-bit pointer) */
2772 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2773 uint32_t instance_methods; /* struct objc_method_description_list *
2775 uint32_t class_methods; /* struct objc_method_description_list *
2779 struct objc_method_description_list_t {
2781 // struct objc_method_description_t list[1];
2784 struct objc_method_description_t {
2785 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2786 uint32_t types; /* char * (32-bit pointer) */
2789 inline void swapStruct(struct cfstring64_t &cfs) {
2790 sys::swapByteOrder(cfs.isa);
2791 sys::swapByteOrder(cfs.flags);
2792 sys::swapByteOrder(cfs.characters);
2793 sys::swapByteOrder(cfs.length);
2796 inline void swapStruct(struct class64_t &c) {
2797 sys::swapByteOrder(c.isa);
2798 sys::swapByteOrder(c.superclass);
2799 sys::swapByteOrder(c.cache);
2800 sys::swapByteOrder(c.vtable);
2801 sys::swapByteOrder(c.data);
2804 inline void swapStruct(struct class32_t &c) {
2805 sys::swapByteOrder(c.isa);
2806 sys::swapByteOrder(c.superclass);
2807 sys::swapByteOrder(c.cache);
2808 sys::swapByteOrder(c.vtable);
2809 sys::swapByteOrder(c.data);
2812 inline void swapStruct(struct class_ro64_t &cro) {
2813 sys::swapByteOrder(cro.flags);
2814 sys::swapByteOrder(cro.instanceStart);
2815 sys::swapByteOrder(cro.instanceSize);
2816 sys::swapByteOrder(cro.reserved);
2817 sys::swapByteOrder(cro.ivarLayout);
2818 sys::swapByteOrder(cro.name);
2819 sys::swapByteOrder(cro.baseMethods);
2820 sys::swapByteOrder(cro.baseProtocols);
2821 sys::swapByteOrder(cro.ivars);
2822 sys::swapByteOrder(cro.weakIvarLayout);
2823 sys::swapByteOrder(cro.baseProperties);
2826 inline void swapStruct(struct class_ro32_t &cro) {
2827 sys::swapByteOrder(cro.flags);
2828 sys::swapByteOrder(cro.instanceStart);
2829 sys::swapByteOrder(cro.instanceSize);
2830 sys::swapByteOrder(cro.ivarLayout);
2831 sys::swapByteOrder(cro.name);
2832 sys::swapByteOrder(cro.baseMethods);
2833 sys::swapByteOrder(cro.baseProtocols);
2834 sys::swapByteOrder(cro.ivars);
2835 sys::swapByteOrder(cro.weakIvarLayout);
2836 sys::swapByteOrder(cro.baseProperties);
2839 inline void swapStruct(struct method_list64_t &ml) {
2840 sys::swapByteOrder(ml.entsize);
2841 sys::swapByteOrder(ml.count);
2844 inline void swapStruct(struct method_list32_t &ml) {
2845 sys::swapByteOrder(ml.entsize);
2846 sys::swapByteOrder(ml.count);
2849 inline void swapStruct(struct method64_t &m) {
2850 sys::swapByteOrder(m.name);
2851 sys::swapByteOrder(m.types);
2852 sys::swapByteOrder(m.imp);
2855 inline void swapStruct(struct method32_t &m) {
2856 sys::swapByteOrder(m.name);
2857 sys::swapByteOrder(m.types);
2858 sys::swapByteOrder(m.imp);
2861 inline void swapStruct(struct protocol_list64_t &pl) {
2862 sys::swapByteOrder(pl.count);
2865 inline void swapStruct(struct protocol_list32_t &pl) {
2866 sys::swapByteOrder(pl.count);
2869 inline void swapStruct(struct protocol64_t &p) {
2870 sys::swapByteOrder(p.isa);
2871 sys::swapByteOrder(p.name);
2872 sys::swapByteOrder(p.protocols);
2873 sys::swapByteOrder(p.instanceMethods);
2874 sys::swapByteOrder(p.classMethods);
2875 sys::swapByteOrder(p.optionalInstanceMethods);
2876 sys::swapByteOrder(p.optionalClassMethods);
2877 sys::swapByteOrder(p.instanceProperties);
2880 inline void swapStruct(struct protocol32_t &p) {
2881 sys::swapByteOrder(p.isa);
2882 sys::swapByteOrder(p.name);
2883 sys::swapByteOrder(p.protocols);
2884 sys::swapByteOrder(p.instanceMethods);
2885 sys::swapByteOrder(p.classMethods);
2886 sys::swapByteOrder(p.optionalInstanceMethods);
2887 sys::swapByteOrder(p.optionalClassMethods);
2888 sys::swapByteOrder(p.instanceProperties);
2891 inline void swapStruct(struct ivar_list64_t &il) {
2892 sys::swapByteOrder(il.entsize);
2893 sys::swapByteOrder(il.count);
2896 inline void swapStruct(struct ivar_list32_t &il) {
2897 sys::swapByteOrder(il.entsize);
2898 sys::swapByteOrder(il.count);
2901 inline void swapStruct(struct ivar64_t &i) {
2902 sys::swapByteOrder(i.offset);
2903 sys::swapByteOrder(i.name);
2904 sys::swapByteOrder(i.type);
2905 sys::swapByteOrder(i.alignment);
2906 sys::swapByteOrder(i.size);
2909 inline void swapStruct(struct ivar32_t &i) {
2910 sys::swapByteOrder(i.offset);
2911 sys::swapByteOrder(i.name);
2912 sys::swapByteOrder(i.type);
2913 sys::swapByteOrder(i.alignment);
2914 sys::swapByteOrder(i.size);
2917 inline void swapStruct(struct objc_property_list64 &pl) {
2918 sys::swapByteOrder(pl.entsize);
2919 sys::swapByteOrder(pl.count);
2922 inline void swapStruct(struct objc_property_list32 &pl) {
2923 sys::swapByteOrder(pl.entsize);
2924 sys::swapByteOrder(pl.count);
2927 inline void swapStruct(struct objc_property64 &op) {
2928 sys::swapByteOrder(op.name);
2929 sys::swapByteOrder(op.attributes);
2932 inline void swapStruct(struct objc_property32 &op) {
2933 sys::swapByteOrder(op.name);
2934 sys::swapByteOrder(op.attributes);
2937 inline void swapStruct(struct category64_t &c) {
2938 sys::swapByteOrder(c.name);
2939 sys::swapByteOrder(c.cls);
2940 sys::swapByteOrder(c.instanceMethods);
2941 sys::swapByteOrder(c.classMethods);
2942 sys::swapByteOrder(c.protocols);
2943 sys::swapByteOrder(c.instanceProperties);
2946 inline void swapStruct(struct category32_t &c) {
2947 sys::swapByteOrder(c.name);
2948 sys::swapByteOrder(c.cls);
2949 sys::swapByteOrder(c.instanceMethods);
2950 sys::swapByteOrder(c.classMethods);
2951 sys::swapByteOrder(c.protocols);
2952 sys::swapByteOrder(c.instanceProperties);
2955 inline void swapStruct(struct objc_image_info64 &o) {
2956 sys::swapByteOrder(o.version);
2957 sys::swapByteOrder(o.flags);
2960 inline void swapStruct(struct objc_image_info32 &o) {
2961 sys::swapByteOrder(o.version);
2962 sys::swapByteOrder(o.flags);
2965 inline void swapStruct(struct imageInfo_t &o) {
2966 sys::swapByteOrder(o.version);
2967 sys::swapByteOrder(o.flags);
2970 inline void swapStruct(struct message_ref64 &mr) {
2971 sys::swapByteOrder(mr.imp);
2972 sys::swapByteOrder(mr.sel);
2975 inline void swapStruct(struct message_ref32 &mr) {
2976 sys::swapByteOrder(mr.imp);
2977 sys::swapByteOrder(mr.sel);
2980 inline void swapStruct(struct objc_module_t &module) {
2981 sys::swapByteOrder(module.version);
2982 sys::swapByteOrder(module.size);
2983 sys::swapByteOrder(module.name);
2984 sys::swapByteOrder(module.symtab);
2987 inline void swapStruct(struct objc_symtab_t &symtab) {
2988 sys::swapByteOrder(symtab.sel_ref_cnt);
2989 sys::swapByteOrder(symtab.refs);
2990 sys::swapByteOrder(symtab.cls_def_cnt);
2991 sys::swapByteOrder(symtab.cat_def_cnt);
2994 inline void swapStruct(struct objc_class_t &objc_class) {
2995 sys::swapByteOrder(objc_class.isa);
2996 sys::swapByteOrder(objc_class.super_class);
2997 sys::swapByteOrder(objc_class.name);
2998 sys::swapByteOrder(objc_class.version);
2999 sys::swapByteOrder(objc_class.info);
3000 sys::swapByteOrder(objc_class.instance_size);
3001 sys::swapByteOrder(objc_class.ivars);
3002 sys::swapByteOrder(objc_class.methodLists);
3003 sys::swapByteOrder(objc_class.cache);
3004 sys::swapByteOrder(objc_class.protocols);
3007 inline void swapStruct(struct objc_category_t &objc_category) {
3008 sys::swapByteOrder(objc_category.category_name);
3009 sys::swapByteOrder(objc_category.class_name);
3010 sys::swapByteOrder(objc_category.instance_methods);
3011 sys::swapByteOrder(objc_category.class_methods);
3012 sys::swapByteOrder(objc_category.protocols);
3015 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3016 sys::swapByteOrder(objc_ivar_list.ivar_count);
3019 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3020 sys::swapByteOrder(objc_ivar.ivar_name);
3021 sys::swapByteOrder(objc_ivar.ivar_type);
3022 sys::swapByteOrder(objc_ivar.ivar_offset);
3025 inline void swapStruct(struct objc_method_list_t &method_list) {
3026 sys::swapByteOrder(method_list.obsolete);
3027 sys::swapByteOrder(method_list.method_count);
3030 inline void swapStruct(struct objc_method_t &method) {
3031 sys::swapByteOrder(method.method_name);
3032 sys::swapByteOrder(method.method_types);
3033 sys::swapByteOrder(method.method_imp);
3036 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3037 sys::swapByteOrder(protocol_list.next);
3038 sys::swapByteOrder(protocol_list.count);
3041 inline void swapStruct(struct objc_protocol_t &protocol) {
3042 sys::swapByteOrder(protocol.isa);
3043 sys::swapByteOrder(protocol.protocol_name);
3044 sys::swapByteOrder(protocol.protocol_list);
3045 sys::swapByteOrder(protocol.instance_methods);
3046 sys::swapByteOrder(protocol.class_methods);
3049 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3050 sys::swapByteOrder(mdl.count);
3053 inline void swapStruct(struct objc_method_description_t &md) {
3054 sys::swapByteOrder(md.name);
3055 sys::swapByteOrder(md.types);
3058 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3059 struct DisassembleInfo *info);
3061 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3062 // to an Objective-C class and returns the class name. It is also passed the
3063 // address of the pointer, so when the pointer is zero as it can be in an .o
3064 // file, that is used to look for an external relocation entry with a symbol
3066 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3067 uint64_t ReferenceValue,
3068 struct DisassembleInfo *info) {
3070 uint32_t offset, left;
3073 // The pointer_value can be 0 in an object file and have a relocation
3074 // entry for the class symbol at the ReferenceValue (the address of the
3076 if (pointer_value == 0) {
3077 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3078 if (r == nullptr || left < sizeof(uint64_t))
3081 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3082 if (symbol_name == nullptr)
3084 const char *class_name = strrchr(symbol_name, '$');
3085 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3086 return class_name + 2;
3091 // The case were the pointer_value is non-zero and points to a class defined
3092 // in this Mach-O file.
3093 r = get_pointer_64(pointer_value, offset, left, S, info);
3094 if (r == nullptr || left < sizeof(struct class64_t))
3097 memcpy(&c, r, sizeof(struct class64_t));
3098 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3102 r = get_pointer_64(c.data, offset, left, S, info);
3103 if (r == nullptr || left < sizeof(struct class_ro64_t))
3105 struct class_ro64_t cro;
3106 memcpy(&cro, r, sizeof(struct class_ro64_t));
3107 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3111 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3115 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3116 // pointer to a cfstring and returns its name or nullptr.
3117 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3118 struct DisassembleInfo *info) {
3119 const char *r, *name;
3120 uint32_t offset, left;
3122 struct cfstring64_t cfs;
3123 uint64_t cfs_characters;
3125 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3126 if (r == nullptr || left < sizeof(struct cfstring64_t))
3128 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3129 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3131 if (cfs.characters == 0) {
3133 const char *symbol_name = get_symbol_64(
3134 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3135 if (symbol_name == nullptr)
3137 cfs_characters = n_value;
3139 cfs_characters = cfs.characters;
3140 name = get_pointer_64(cfs_characters, offset, left, S, info);
3145 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
3146 // of a pointer to an Objective-C selector reference when the pointer value is
3147 // zero as in a .o file and is likely to have a external relocation entry with
3148 // who's symbol's n_value is the real pointer to the selector name. If that is
3149 // the case the real pointer to the selector name is returned else 0 is
3151 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3152 struct DisassembleInfo *info) {
3153 uint32_t offset, left;
3156 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3157 if (r == nullptr || left < sizeof(uint64_t))
3160 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3161 if (symbol_name == nullptr)
3166 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3167 const char *sectname) {
3168 for (const SectionRef &Section : O->sections()) {
3170 Section.getName(SectName);
3171 DataRefImpl Ref = Section.getRawDataRefImpl();
3172 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3173 if (SegName == segname && SectName == sectname)
3176 return SectionRef();
3180 walk_pointer_list_64(const char *listname, const SectionRef S,
3181 MachOObjectFile *O, struct DisassembleInfo *info,
3182 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3183 if (S == SectionRef())
3187 S.getName(SectName);
3188 DataRefImpl Ref = S.getRawDataRefImpl();
3189 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3190 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3193 S.getContents(BytesStr);
3194 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3196 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3197 uint32_t left = S.getSize() - i;
3198 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3200 memcpy(&p, Contents + i, size);
3201 if (i + sizeof(uint64_t) > S.getSize())
3202 outs() << listname << " list pointer extends past end of (" << SegName
3203 << "," << SectName << ") section\n";
3204 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3206 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3207 sys::swapByteOrder(p);
3209 uint64_t n_value = 0;
3210 const char *name = get_symbol_64(i, S, info, n_value, p);
3211 if (name == nullptr)
3212 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3215 outs() << format("0x%" PRIx64, n_value);
3217 outs() << " + " << format("0x%" PRIx64, p);
3219 outs() << format("0x%" PRIx64, p);
3220 if (name != nullptr)
3221 outs() << " " << name;
3231 walk_pointer_list_32(const char *listname, const SectionRef S,
3232 MachOObjectFile *O, struct DisassembleInfo *info,
3233 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3234 if (S == SectionRef())
3238 S.getName(SectName);
3239 DataRefImpl Ref = S.getRawDataRefImpl();
3240 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3241 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3244 S.getContents(BytesStr);
3245 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3247 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3248 uint32_t left = S.getSize() - i;
3249 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3251 memcpy(&p, Contents + i, size);
3252 if (i + sizeof(uint32_t) > S.getSize())
3253 outs() << listname << " list pointer extends past end of (" << SegName
3254 << "," << SectName << ") section\n";
3255 uint32_t Address = S.getAddress() + i;
3256 outs() << format("%08" PRIx32, Address) << " ";
3258 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3259 sys::swapByteOrder(p);
3260 outs() << format("0x%" PRIx32, p);
3262 const char *name = get_symbol_32(i, S, info, p);
3263 if (name != nullptr)
3264 outs() << " " << name;
3272 static void print_layout_map(const char *layout_map, uint32_t left) {
3273 if (layout_map == nullptr)
3275 outs() << " layout map: ";
3277 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3280 } while (*layout_map != '\0' && left != 0);
3284 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3285 uint32_t offset, left;
3287 const char *layout_map;
3291 layout_map = get_pointer_64(p, offset, left, S, info);
3292 print_layout_map(layout_map, left);
3295 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3296 uint32_t offset, left;
3298 const char *layout_map;
3302 layout_map = get_pointer_32(p, offset, left, S, info);
3303 print_layout_map(layout_map, left);
3306 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3307 const char *indent) {
3308 struct method_list64_t ml;
3309 struct method64_t m;
3311 uint32_t offset, xoffset, left, i;
3313 const char *name, *sym_name;
3316 r = get_pointer_64(p, offset, left, S, info);
3319 memset(&ml, '\0', sizeof(struct method_list64_t));
3320 if (left < sizeof(struct method_list64_t)) {
3321 memcpy(&ml, r, left);
3322 outs() << " (method_list_t entends past the end of the section)\n";
3324 memcpy(&ml, r, sizeof(struct method_list64_t));
3325 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3327 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3328 outs() << indent << "\t\t count " << ml.count << "\n";
3330 p += sizeof(struct method_list64_t);
3331 offset += sizeof(struct method_list64_t);
3332 for (i = 0; i < ml.count; i++) {
3333 r = get_pointer_64(p, offset, left, S, info);
3336 memset(&m, '\0', sizeof(struct method64_t));
3337 if (left < sizeof(struct method64_t)) {
3338 memcpy(&m, r, left);
3339 outs() << indent << " (method_t extends past the end of the section)\n";
3341 memcpy(&m, r, sizeof(struct method64_t));
3342 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3345 outs() << indent << "\t\t name ";
3346 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3347 info, n_value, m.name);
3349 if (info->verbose && sym_name != nullptr)
3352 outs() << format("0x%" PRIx64, n_value);
3354 outs() << " + " << format("0x%" PRIx64, m.name);
3356 outs() << format("0x%" PRIx64, m.name);
3357 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3358 if (name != nullptr)
3359 outs() << format(" %.*s", left, name);
3362 outs() << indent << "\t\t types ";
3363 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3364 info, n_value, m.types);
3366 if (info->verbose && sym_name != nullptr)
3369 outs() << format("0x%" PRIx64, n_value);
3371 outs() << " + " << format("0x%" PRIx64, m.types);
3373 outs() << format("0x%" PRIx64, m.types);
3374 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3375 if (name != nullptr)
3376 outs() << format(" %.*s", left, name);
3379 outs() << indent << "\t\t imp ";
3380 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3382 if (info->verbose && name == nullptr) {
3384 outs() << format("0x%" PRIx64, n_value) << " ";
3386 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3388 outs() << format("0x%" PRIx64, m.imp) << " ";
3390 if (name != nullptr)
3394 p += sizeof(struct method64_t);
3395 offset += sizeof(struct method64_t);
3399 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3400 const char *indent) {
3401 struct method_list32_t ml;
3402 struct method32_t m;
3403 const char *r, *name;
3404 uint32_t offset, xoffset, left, i;
3407 r = get_pointer_32(p, offset, left, S, info);
3410 memset(&ml, '\0', sizeof(struct method_list32_t));
3411 if (left < sizeof(struct method_list32_t)) {
3412 memcpy(&ml, r, left);
3413 outs() << " (method_list_t entends past the end of the section)\n";
3415 memcpy(&ml, r, sizeof(struct method_list32_t));
3416 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3418 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3419 outs() << indent << "\t\t count " << ml.count << "\n";
3421 p += sizeof(struct method_list32_t);
3422 offset += sizeof(struct method_list32_t);
3423 for (i = 0; i < ml.count; i++) {
3424 r = get_pointer_32(p, offset, left, S, info);
3427 memset(&m, '\0', sizeof(struct method32_t));
3428 if (left < sizeof(struct method32_t)) {
3429 memcpy(&ml, r, left);
3430 outs() << indent << " (method_t entends past the end of the section)\n";
3432 memcpy(&m, r, sizeof(struct method32_t));
3433 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3436 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3437 name = get_pointer_32(m.name, xoffset, left, xS, info);
3438 if (name != nullptr)
3439 outs() << format(" %.*s", left, name);
3442 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3443 name = get_pointer_32(m.types, xoffset, left, xS, info);
3444 if (name != nullptr)
3445 outs() << format(" %.*s", left, name);
3448 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3449 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3451 if (name != nullptr)
3452 outs() << " " << name;
3455 p += sizeof(struct method32_t);
3456 offset += sizeof(struct method32_t);
3460 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3461 uint32_t offset, left, xleft;
3463 struct objc_method_list_t method_list;
3464 struct objc_method_t method;
3465 const char *r, *methods, *name, *SymbolName;
3468 r = get_pointer_32(p, offset, left, S, info, true);
3473 if (left > sizeof(struct objc_method_list_t)) {
3474 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3476 outs() << "\t\t objc_method_list extends past end of the section\n";
3477 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3478 memcpy(&method_list, r, left);
3480 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3481 swapStruct(method_list);
3483 outs() << "\t\t obsolete "
3484 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3485 outs() << "\t\t method_count " << method_list.method_count << "\n";
3487 methods = r + sizeof(struct objc_method_list_t);
3488 for (i = 0; i < method_list.method_count; i++) {
3489 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3490 outs() << "\t\t remaining method's extend past the of the section\n";
3493 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3494 sizeof(struct objc_method_t));
3495 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3498 outs() << "\t\t method_name "
3499 << format("0x%08" PRIx32, method.method_name);
3500 if (info->verbose) {
3501 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3502 if (name != nullptr)
3503 outs() << format(" %.*s", xleft, name);
3505 outs() << " (not in an __OBJC section)";
3509 outs() << "\t\t method_types "
3510 << format("0x%08" PRIx32, method.method_types);
3511 if (info->verbose) {
3512 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3513 if (name != nullptr)
3514 outs() << format(" %.*s", xleft, name);
3516 outs() << " (not in an __OBJC section)";
3520 outs() << "\t\t method_imp "
3521 << format("0x%08" PRIx32, method.method_imp) << " ";
3522 if (info->verbose) {
3523 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3524 if (SymbolName != nullptr)
3525 outs() << SymbolName;
3532 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3533 struct protocol_list64_t pl;
3534 uint64_t q, n_value;
3535 struct protocol64_t pc;
3537 uint32_t offset, xoffset, left, i;
3539 const char *name, *sym_name;
3541 r = get_pointer_64(p, offset, left, S, info);
3544 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3545 if (left < sizeof(struct protocol_list64_t)) {
3546 memcpy(&pl, r, left);
3547 outs() << " (protocol_list_t entends past the end of the section)\n";
3549 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3550 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3552 outs() << " count " << pl.count << "\n";
3554 p += sizeof(struct protocol_list64_t);
3555 offset += sizeof(struct protocol_list64_t);
3556 for (i = 0; i < pl.count; i++) {
3557 r = get_pointer_64(p, offset, left, S, info);
3561 if (left < sizeof(uint64_t)) {
3562 memcpy(&q, r, left);
3563 outs() << " (protocol_t * entends past the end of the section)\n";
3565 memcpy(&q, r, sizeof(uint64_t));
3566 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3567 sys::swapByteOrder(q);
3569 outs() << "\t\t list[" << i << "] ";
3570 sym_name = get_symbol_64(offset, S, info, n_value, q);
3572 if (info->verbose && sym_name != nullptr)
3575 outs() << format("0x%" PRIx64, n_value);
3577 outs() << " + " << format("0x%" PRIx64, q);
3579 outs() << format("0x%" PRIx64, q);
3580 outs() << " (struct protocol_t *)\n";
3582 r = get_pointer_64(q + n_value, offset, left, S, info);
3585 memset(&pc, '\0', sizeof(struct protocol64_t));
3586 if (left < sizeof(struct protocol64_t)) {
3587 memcpy(&pc, r, left);
3588 outs() << " (protocol_t entends past the end of the section)\n";
3590 memcpy(&pc, r, sizeof(struct protocol64_t));
3591 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3594 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3596 outs() << "\t\t\t name ";
3597 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3598 info, n_value, pc.name);
3600 if (info->verbose && sym_name != nullptr)
3603 outs() << format("0x%" PRIx64, n_value);
3605 outs() << " + " << format("0x%" PRIx64, pc.name);
3607 outs() << format("0x%" PRIx64, pc.name);
3608 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3609 if (name != nullptr)
3610 outs() << format(" %.*s", left, name);
3613 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3615 outs() << "\t\t instanceMethods ";
3617 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3618 S, info, n_value, pc.instanceMethods);
3620 if (info->verbose && sym_name != nullptr)
3623 outs() << format("0x%" PRIx64, n_value);
3624 if (pc.instanceMethods != 0)
3625 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3627 outs() << format("0x%" PRIx64, pc.instanceMethods);
3628 outs() << " (struct method_list_t *)\n";
3629 if (pc.instanceMethods + n_value != 0)
3630 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3632 outs() << "\t\t classMethods ";
3634 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3635 info, n_value, pc.classMethods);
3637 if (info->verbose && sym_name != nullptr)
3640 outs() << format("0x%" PRIx64, n_value);
3641 if (pc.classMethods != 0)
3642 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3644 outs() << format("0x%" PRIx64, pc.classMethods);
3645 outs() << " (struct method_list_t *)\n";
3646 if (pc.classMethods + n_value != 0)
3647 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3649 outs() << "\t optionalInstanceMethods "
3650 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3651 outs() << "\t optionalClassMethods "
3652 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3653 outs() << "\t instanceProperties "
3654 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3656 p += sizeof(uint64_t);
3657 offset += sizeof(uint64_t);
3661 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3662 struct protocol_list32_t pl;
3664 struct protocol32_t pc;
3666 uint32_t offset, xoffset, left, i;
3670 r = get_pointer_32(p, offset, left, S, info);
3673 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3674 if (left < sizeof(struct protocol_list32_t)) {
3675 memcpy(&pl, r, left);
3676 outs() << " (protocol_list_t entends past the end of the section)\n";
3678 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3679 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3681 outs() << " count " << pl.count << "\n";
3683 p += sizeof(struct protocol_list32_t);
3684 offset += sizeof(struct protocol_list32_t);
3685 for (i = 0; i < pl.count; i++) {
3686 r = get_pointer_32(p, offset, left, S, info);
3690 if (left < sizeof(uint32_t)) {
3691 memcpy(&q, r, left);
3692 outs() << " (protocol_t * entends past the end of the section)\n";
3694 memcpy(&q, r, sizeof(uint32_t));
3695 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3696 sys::swapByteOrder(q);
3697 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3698 << " (struct protocol_t *)\n";
3699 r = get_pointer_32(q, offset, left, S, info);
3702 memset(&pc, '\0', sizeof(struct protocol32_t));
3703 if (left < sizeof(struct protocol32_t)) {
3704 memcpy(&pc, r, left);
3705 outs() << " (protocol_t entends past the end of the section)\n";
3707 memcpy(&pc, r, sizeof(struct protocol32_t));
3708 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3710 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3711 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3712 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3713 if (name != nullptr)
3714 outs() << format(" %.*s", left, name);
3716 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3717 outs() << "\t\t instanceMethods "
3718 << format("0x%" PRIx32, pc.instanceMethods)
3719 << " (struct method_list_t *)\n";
3720 if (pc.instanceMethods != 0)
3721 print_method_list32_t(pc.instanceMethods, info, "\t");
3722 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3723 << " (struct method_list_t *)\n";
3724 if (pc.classMethods != 0)
3725 print_method_list32_t(pc.classMethods, info, "\t");
3726 outs() << "\t optionalInstanceMethods "
3727 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3728 outs() << "\t optionalClassMethods "
3729 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3730 outs() << "\t instanceProperties "
3731 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3732 p += sizeof(uint32_t);
3733 offset += sizeof(uint32_t);
3737 static void print_indent(uint32_t indent) {
3738 for (uint32_t i = 0; i < indent;) {
3739 if (indent - i >= 8) {
3743 for (uint32_t j = i; j < indent; j++)
3750 static bool print_method_description_list(uint32_t p, uint32_t indent,
3751 struct DisassembleInfo *info) {
3752 uint32_t offset, left, xleft;
3754 struct objc_method_description_list_t mdl;
3755 struct objc_method_description_t md;
3756 const char *r, *list, *name;
3759 r = get_pointer_32(p, offset, left, S, info, true);
3764 if (left > sizeof(struct objc_method_description_list_t)) {
3765 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3767 print_indent(indent);
3768 outs() << " objc_method_description_list extends past end of the section\n";
3769 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3770 memcpy(&mdl, r, left);
3772 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3775 print_indent(indent);
3776 outs() << " count " << mdl.count << "\n";
3778 list = r + sizeof(struct objc_method_description_list_t);
3779 for (i = 0; i < mdl.count; i++) {
3780 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3781 print_indent(indent);
3782 outs() << " remaining list entries extend past the of the section\n";
3785 print_indent(indent);
3786 outs() << " list[" << i << "]\n";
3787 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3788 sizeof(struct objc_method_description_t));
3789 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3792 print_indent(indent);
3793 outs() << " name " << format("0x%08" PRIx32, md.name);
3794 if (info->verbose) {
3795 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3796 if (name != nullptr)
3797 outs() << format(" %.*s", xleft, name);
3799 outs() << " (not in an __OBJC section)";
3803 print_indent(indent);
3804 outs() << " types " << format("0x%08" PRIx32, md.types);
3805 if (info->verbose) {
3806 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3807 if (name != nullptr)
3808 outs() << format(" %.*s", xleft, name);
3810 outs() << " (not in an __OBJC section)";
3817 static bool print_protocol_list(uint32_t p, uint32_t indent,
3818 struct DisassembleInfo *info);
3820 static bool print_protocol(uint32_t p, uint32_t indent,
3821 struct DisassembleInfo *info) {
3822 uint32_t offset, left;
3824 struct objc_protocol_t protocol;
3825 const char *r, *name;
3827 r = get_pointer_32(p, offset, left, S, info, true);
3832 if (left >= sizeof(struct objc_protocol_t)) {
3833 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3835 print_indent(indent);
3836 outs() << " Protocol extends past end of the section\n";
3837 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3838 memcpy(&protocol, r, left);
3840 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3841 swapStruct(protocol);
3843 print_indent(indent);
3844 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3847 print_indent(indent);
3848 outs() << " protocol_name "
3849 << format("0x%08" PRIx32, protocol.protocol_name);
3850 if (info->verbose) {
3851 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3852 if (name != nullptr)
3853 outs() << format(" %.*s", left, name);
3855 outs() << " (not in an __OBJC section)";
3859 print_indent(indent);
3860 outs() << " protocol_list "
3861 << format("0x%08" PRIx32, protocol.protocol_list);
3862 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3863 outs() << " (not in an __OBJC section)\n";
3865 print_indent(indent);
3866 outs() << " instance_methods "
3867 << format("0x%08" PRIx32, protocol.instance_methods);
3868 if (print_method_description_list(protocol.instance_methods, indent, info))
3869 outs() << " (not in an __OBJC section)\n";
3871 print_indent(indent);
3872 outs() << " class_methods "
3873 << format("0x%08" PRIx32, protocol.class_methods);
3874 if (print_method_description_list(protocol.class_methods, indent, info))
3875 outs() << " (not in an __OBJC section)\n";
3880 static bool print_protocol_list(uint32_t p, uint32_t indent,
3881 struct DisassembleInfo *info) {
3882 uint32_t offset, left, l;
3884 struct objc_protocol_list_t protocol_list;
3885 const char *r, *list;
3888 r = get_pointer_32(p, offset, left, S, info, true);
3893 if (left > sizeof(struct objc_protocol_list_t)) {
3894 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3896 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3897 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3898 memcpy(&protocol_list, r, left);
3900 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3901 swapStruct(protocol_list);
3903 print_indent(indent);
3904 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3906 print_indent(indent);
3907 outs() << " count " << protocol_list.count << "\n";
3909 list = r + sizeof(struct objc_protocol_list_t);
3910 for (i = 0; i < protocol_list.count; i++) {
3911 if ((i + 1) * sizeof(uint32_t) > left) {
3912 outs() << "\t\t remaining list entries extend past the of the section\n";
3915 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3916 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3917 sys::swapByteOrder(l);
3919 print_indent(indent);
3920 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3921 if (print_protocol(l, indent, info))
3922 outs() << "(not in an __OBJC section)\n";
3927 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3928 struct ivar_list64_t il;
3931 uint32_t offset, xoffset, left, j;
3933 const char *name, *sym_name, *ivar_offset_p;
3934 uint64_t ivar_offset, n_value;
3936 r = get_pointer_64(p, offset, left, S, info);
3939 memset(&il, '\0', sizeof(struct ivar_list64_t));
3940 if (left < sizeof(struct ivar_list64_t)) {
3941 memcpy(&il, r, left);
3942 outs() << " (ivar_list_t entends past the end of the section)\n";
3944 memcpy(&il, r, sizeof(struct ivar_list64_t));
3945 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3947 outs() << " entsize " << il.entsize << "\n";
3948 outs() << " count " << il.count << "\n";
3950 p += sizeof(struct ivar_list64_t);
3951 offset += sizeof(struct ivar_list64_t);
3952 for (j = 0; j < il.count; j++) {
3953 r = get_pointer_64(p, offset, left, S, info);
3956 memset(&i, '\0', sizeof(struct ivar64_t));
3957 if (left < sizeof(struct ivar64_t)) {
3958 memcpy(&i, r, left);
3959 outs() << " (ivar_t entends past the end of the section)\n";
3961 memcpy(&i, r, sizeof(struct ivar64_t));
3962 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3965 outs() << "\t\t\t offset ";
3966 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3967 info, n_value, i.offset);
3969 if (info->verbose && sym_name != nullptr)
3972 outs() << format("0x%" PRIx64, n_value);
3974 outs() << " + " << format("0x%" PRIx64, i.offset);
3976 outs() << format("0x%" PRIx64, i.offset);
3977 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3978 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3979 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3980 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3981 sys::swapByteOrder(ivar_offset);
3982 outs() << " " << ivar_offset << "\n";
3986 outs() << "\t\t\t name ";
3987 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
3990 if (info->verbose && sym_name != nullptr)
3993 outs() << format("0x%" PRIx64, n_value);
3995 outs() << " + " << format("0x%" PRIx64, i.name);
3997 outs() << format("0x%" PRIx64, i.name);
3998 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
3999 if (name != nullptr)
4000 outs() << format(" %.*s", left, name);
4003 outs() << "\t\t\t type ";
4004 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4006 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4008 if (info->verbose && sym_name != nullptr)
4011 outs() << format("0x%" PRIx64, n_value);
4013 outs() << " + " << format("0x%" PRIx64, i.type);
4015 outs() << format("0x%" PRIx64, i.type);
4016 if (name != nullptr)
4017 outs() << format(" %.*s", left, name);
4020 outs() << "\t\t\talignment " << i.alignment << "\n";
4021 outs() << "\t\t\t size " << i.size << "\n";
4023 p += sizeof(struct ivar64_t);
4024 offset += sizeof(struct ivar64_t);
4028 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4029 struct ivar_list32_t il;
4032 uint32_t offset, xoffset, left, j;
4034 const char *name, *ivar_offset_p;
4035 uint32_t ivar_offset;
4037 r = get_pointer_32(p, offset, left, S, info);
4040 memset(&il, '\0', sizeof(struct ivar_list32_t));
4041 if (left < sizeof(struct ivar_list32_t)) {
4042 memcpy(&il, r, left);
4043 outs() << " (ivar_list_t entends past the end of the section)\n";
4045 memcpy(&il, r, sizeof(struct ivar_list32_t));
4046 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4048 outs() << " entsize " << il.entsize << "\n";
4049 outs() << " count " << il.count << "\n";
4051 p += sizeof(struct ivar_list32_t);
4052 offset += sizeof(struct ivar_list32_t);
4053 for (j = 0; j < il.count; j++) {
4054 r = get_pointer_32(p, offset, left, S, info);
4057 memset(&i, '\0', sizeof(struct ivar32_t));
4058 if (left < sizeof(struct ivar32_t)) {
4059 memcpy(&i, r, left);
4060 outs() << " (ivar_t entends past the end of the section)\n";
4062 memcpy(&i, r, sizeof(struct ivar32_t));
4063 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4066 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4067 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4068 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4069 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4070 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4071 sys::swapByteOrder(ivar_offset);
4072 outs() << " " << ivar_offset << "\n";
4076 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4077 name = get_pointer_32(i.name, xoffset, left, xS, info);
4078 if (name != nullptr)
4079 outs() << format(" %.*s", left, name);
4082 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4083 name = get_pointer_32(i.type, xoffset, left, xS, info);
4084 if (name != nullptr)
4085 outs() << format(" %.*s", left, name);
4088 outs() << "\t\t\talignment " << i.alignment << "\n";
4089 outs() << "\t\t\t size " << i.size << "\n";
4091 p += sizeof(struct ivar32_t);
4092 offset += sizeof(struct ivar32_t);
4096 static void print_objc_property_list64(uint64_t p,
4097 struct DisassembleInfo *info) {
4098 struct objc_property_list64 opl;
4099 struct objc_property64 op;
4101 uint32_t offset, xoffset, left, j;
4103 const char *name, *sym_name;
4106 r = get_pointer_64(p, offset, left, S, info);
4109 memset(&opl, '\0', sizeof(struct objc_property_list64));
4110 if (left < sizeof(struct objc_property_list64)) {
4111 memcpy(&opl, r, left);
4112 outs() << " (objc_property_list entends past the end of the section)\n";
4114 memcpy(&opl, r, sizeof(struct objc_property_list64));
4115 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4117 outs() << " entsize " << opl.entsize << "\n";
4118 outs() << " count " << opl.count << "\n";
4120 p += sizeof(struct objc_property_list64);
4121 offset += sizeof(struct objc_property_list64);
4122 for (j = 0; j < opl.count; j++) {
4123 r = get_pointer_64(p, offset, left, S, info);
4126 memset(&op, '\0', sizeof(struct objc_property64));
4127 if (left < sizeof(struct objc_property64)) {
4128 memcpy(&op, r, left);
4129 outs() << " (objc_property entends past the end of the section)\n";
4131 memcpy(&op, r, sizeof(struct objc_property64));
4132 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4135 outs() << "\t\t\t name ";
4136 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4137 info, n_value, op.name);
4139 if (info->verbose && sym_name != nullptr)
4142 outs() << format("0x%" PRIx64, n_value);
4144 outs() << " + " << format("0x%" PRIx64, op.name);
4146 outs() << format("0x%" PRIx64, op.name);
4147 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4148 if (name != nullptr)
4149 outs() << format(" %.*s", left, name);
4152 outs() << "\t\t\tattributes ";
4154 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4155 info, n_value, op.attributes);
4157 if (info->verbose && sym_name != nullptr)
4160 outs() << format("0x%" PRIx64, n_value);
4161 if (op.attributes != 0)
4162 outs() << " + " << format("0x%" PRIx64, op.attributes);
4164 outs() << format("0x%" PRIx64, op.attributes);
4165 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4166 if (name != nullptr)
4167 outs() << format(" %.*s", left, name);
4170 p += sizeof(struct objc_property64);
4171 offset += sizeof(struct objc_property64);
4175 static void print_objc_property_list32(uint32_t p,
4176 struct DisassembleInfo *info) {
4177 struct objc_property_list32 opl;
4178 struct objc_property32 op;
4180 uint32_t offset, xoffset, left, j;
4184 r = get_pointer_32(p, offset, left, S, info);
4187 memset(&opl, '\0', sizeof(struct objc_property_list32));
4188 if (left < sizeof(struct objc_property_list32)) {
4189 memcpy(&opl, r, left);
4190 outs() << " (objc_property_list entends past the end of the section)\n";
4192 memcpy(&opl, r, sizeof(struct objc_property_list32));
4193 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4195 outs() << " entsize " << opl.entsize << "\n";
4196 outs() << " count " << opl.count << "\n";
4198 p += sizeof(struct objc_property_list32);
4199 offset += sizeof(struct objc_property_list32);
4200 for (j = 0; j < opl.count; j++) {
4201 r = get_pointer_32(p, offset, left, S, info);
4204 memset(&op, '\0', sizeof(struct objc_property32));
4205 if (left < sizeof(struct objc_property32)) {
4206 memcpy(&op, r, left);
4207 outs() << " (objc_property entends past the end of the section)\n";
4209 memcpy(&op, r, sizeof(struct objc_property32));
4210 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4213 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4214 name = get_pointer_32(op.name, xoffset, left, xS, info);
4215 if (name != nullptr)
4216 outs() << format(" %.*s", left, name);
4219 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4220 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4221 if (name != nullptr)
4222 outs() << format(" %.*s", left, name);
4225 p += sizeof(struct objc_property32);
4226 offset += sizeof(struct objc_property32);
4230 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
4231 bool &is_meta_class) {
4232 struct class_ro64_t cro;
4234 uint32_t offset, xoffset, left;
4236 const char *name, *sym_name;
4239 r = get_pointer_64(p, offset, left, S, info);
4240 if (r == nullptr || left < sizeof(struct class_ro64_t))
4242 memset(&cro, '\0', sizeof(struct class_ro64_t));
4243 if (left < sizeof(struct class_ro64_t)) {
4244 memcpy(&cro, r, left);
4245 outs() << " (class_ro_t entends past the end of the section)\n";
4247 memcpy(&cro, r, sizeof(struct class_ro64_t));
4248 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4250 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4251 if (cro.flags & RO_META)
4252 outs() << " RO_META";
4253 if (cro.flags & RO_ROOT)
4254 outs() << " RO_ROOT";
4255 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4256 outs() << " RO_HAS_CXX_STRUCTORS";
4258 outs() << " instanceStart " << cro.instanceStart << "\n";
4259 outs() << " instanceSize " << cro.instanceSize << "\n";
4260 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4262 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4264 print_layout_map64(cro.ivarLayout, info);
4267 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4268 info, n_value, cro.name);
4270 if (info->verbose && sym_name != nullptr)
4273 outs() << format("0x%" PRIx64, n_value);
4275 outs() << " + " << format("0x%" PRIx64, cro.name);
4277 outs() << format("0x%" PRIx64, cro.name);
4278 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4279 if (name != nullptr)
4280 outs() << format(" %.*s", left, name);
4283 outs() << " baseMethods ";
4284 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4285 S, info, n_value, cro.baseMethods);
4287 if (info->verbose && sym_name != nullptr)
4290 outs() << format("0x%" PRIx64, n_value);
4291 if (cro.baseMethods != 0)
4292 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4294 outs() << format("0x%" PRIx64, cro.baseMethods);
4295 outs() << " (struct method_list_t *)\n";
4296 if (cro.baseMethods + n_value != 0)
4297 print_method_list64_t(cro.baseMethods + n_value, info, "");
4299 outs() << " baseProtocols ";
4301 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4302 info, n_value, cro.baseProtocols);
4304 if (info->verbose && sym_name != nullptr)
4307 outs() << format("0x%" PRIx64, n_value);
4308 if (cro.baseProtocols != 0)
4309 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4311 outs() << format("0x%" PRIx64, cro.baseProtocols);
4313 if (cro.baseProtocols + n_value != 0)
4314 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4316 outs() << " ivars ";
4317 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
4318 info, n_value, cro.ivars);
4320 if (info->verbose && sym_name != nullptr)
4323 outs() << format("0x%" PRIx64, n_value);
4325 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4327 outs() << format("0x%" PRIx64, cro.ivars);
4329 if (cro.ivars + n_value != 0)
4330 print_ivar_list64_t(cro.ivars + n_value, info);
4332 outs() << " weakIvarLayout ";
4334 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4335 info, n_value, cro.weakIvarLayout);
4337 if (info->verbose && sym_name != nullptr)
4340 outs() << format("0x%" PRIx64, n_value);
4341 if (cro.weakIvarLayout != 0)
4342 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4344 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4346 print_layout_map64(cro.weakIvarLayout + n_value, info);
4348 outs() << " baseProperties ";
4350 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4351 info, n_value, cro.baseProperties);
4353 if (info->verbose && sym_name != nullptr)
4356 outs() << format("0x%" PRIx64, n_value);
4357 if (cro.baseProperties != 0)
4358 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4360 outs() << format("0x%" PRIx64, cro.baseProperties);
4362 if (cro.baseProperties + n_value != 0)
4363 print_objc_property_list64(cro.baseProperties + n_value, info);
4365 is_meta_class = (cro.flags & RO_META) != 0;
4369 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
4370 bool &is_meta_class) {
4371 struct class_ro32_t cro;
4373 uint32_t offset, xoffset, left;
4377 r = get_pointer_32(p, offset, left, S, info);
4380 memset(&cro, '\0', sizeof(struct class_ro32_t));
4381 if (left < sizeof(struct class_ro32_t)) {
4382 memcpy(&cro, r, left);
4383 outs() << " (class_ro_t entends past the end of the section)\n";
4385 memcpy(&cro, r, sizeof(struct class_ro32_t));
4386 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4388 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4389 if (cro.flags & RO_META)
4390 outs() << " RO_META";
4391 if (cro.flags & RO_ROOT)
4392 outs() << " RO_ROOT";
4393 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4394 outs() << " RO_HAS_CXX_STRUCTORS";
4396 outs() << " instanceStart " << cro.instanceStart << "\n";
4397 outs() << " instanceSize " << cro.instanceSize << "\n";
4398 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4400 print_layout_map32(cro.ivarLayout, info);
4402 outs() << " name " << format("0x%" PRIx32, cro.name);
4403 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4404 if (name != nullptr)
4405 outs() << format(" %.*s", left, name);
4408 outs() << " baseMethods "
4409 << format("0x%" PRIx32, cro.baseMethods)
4410 << " (struct method_list_t *)\n";
4411 if (cro.baseMethods != 0)
4412 print_method_list32_t(cro.baseMethods, info, "");
4414 outs() << " baseProtocols "
4415 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4416 if (cro.baseProtocols != 0)
4417 print_protocol_list32_t(cro.baseProtocols, info);
4418 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4421 print_ivar_list32_t(cro.ivars, info);
4422 outs() << " weakIvarLayout "
4423 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4424 print_layout_map32(cro.weakIvarLayout, info);
4425 outs() << " baseProperties "
4426 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4427 if (cro.baseProperties != 0)
4428 print_objc_property_list32(cro.baseProperties, info);
4429 is_meta_class = (cro.flags & RO_META) != 0;
4433 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4436 uint32_t offset, left;
4439 uint64_t isa_n_value, n_value;
4441 r = get_pointer_64(p, offset, left, S, info);
4442 if (r == nullptr || left < sizeof(struct class64_t))
4444 memset(&c, '\0', sizeof(struct class64_t));
4445 if (left < sizeof(struct class64_t)) {
4446 memcpy(&c, r, left);
4447 outs() << " (class_t entends past the end of the section)\n";
4449 memcpy(&c, r, sizeof(struct class64_t));
4450 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4453 outs() << " isa " << format("0x%" PRIx64, c.isa);
4454 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4455 isa_n_value, c.isa);
4456 if (name != nullptr)
4457 outs() << " " << name;
4460 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4461 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4462 n_value, c.superclass);
4463 if (name != nullptr)
4464 outs() << " " << name;
4467 outs() << " cache " << format("0x%" PRIx64, c.cache);
4468 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4470 if (name != nullptr)
4471 outs() << " " << name;
4474 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4475 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4477 if (name != nullptr)
4478 outs() << " " << name;
4481 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4485 if (info->verbose && name != nullptr)
4488 outs() << format("0x%" PRIx64, n_value);
4490 outs() << " + " << format("0x%" PRIx64, c.data);
4492 outs() << format("0x%" PRIx64, c.data);
4493 outs() << " (struct class_ro_t *)";
4495 // This is a Swift class if some of the low bits of the pointer are set.
4496 if ((c.data + n_value) & 0x7)
4497 outs() << " Swift class";
4500 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4503 if (!is_meta_class &&
4504 c.isa + isa_n_value != p &&
4505 c.isa + isa_n_value != 0 &&
4506 info->depth < 100) {
4508 outs() << "Meta Class\n";
4509 print_class64_t(c.isa + isa_n_value, info);
4513 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4516 uint32_t offset, left;
4520 r = get_pointer_32(p, offset, left, S, info);
4523 memset(&c, '\0', sizeof(struct class32_t));
4524 if (left < sizeof(struct class32_t)) {
4525 memcpy(&c, r, left);
4526 outs() << " (class_t entends past the end of the section)\n";
4528 memcpy(&c, r, sizeof(struct class32_t));
4529 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4532 outs() << " isa " << format("0x%" PRIx32, c.isa);
4534 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4535 if (name != nullptr)
4536 outs() << " " << name;
4539 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4540 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4542 if (name != nullptr)
4543 outs() << " " << name;
4546 outs() << " cache " << format("0x%" PRIx32, c.cache);
4547 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4549 if (name != nullptr)
4550 outs() << " " << name;
4553 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4554 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4556 if (name != nullptr)
4557 outs() << " " << name;
4561 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4562 outs() << " data " << format("0x%" PRIx32, c.data)
4563 << " (struct class_ro_t *)";
4565 // This is a Swift class if some of the low bits of the pointer are set.
4567 outs() << " Swift class";
4570 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4573 if (!is_meta_class) {
4574 outs() << "Meta Class\n";
4575 print_class32_t(c.isa, info);
4579 static void print_objc_class_t(struct objc_class_t *objc_class,
4580 struct DisassembleInfo *info) {
4581 uint32_t offset, left, xleft;
4582 const char *name, *p, *ivar_list;
4585 struct objc_ivar_list_t objc_ivar_list;
4586 struct objc_ivar_t ivar;
4588 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4589 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4590 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4591 if (name != nullptr)
4592 outs() << format(" %.*s", left, name);
4594 outs() << " (not in an __OBJC section)";
4598 outs() << "\t super_class "
4599 << format("0x%08" PRIx32, objc_class->super_class);
4600 if (info->verbose) {
4601 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4602 if (name != nullptr)
4603 outs() << format(" %.*s", left, name);
4605 outs() << " (not in an __OBJC section)";
4609 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4610 if (info->verbose) {
4611 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4612 if (name != nullptr)
4613 outs() << format(" %.*s", left, name);
4615 outs() << " (not in an __OBJC section)";
4619 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4622 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4623 if (info->verbose) {
4624 if (CLS_GETINFO(objc_class, CLS_CLASS))
4625 outs() << " CLS_CLASS";
4626 else if (CLS_GETINFO(objc_class, CLS_META))
4627 outs() << " CLS_META";
4631 outs() << "\t instance_size "
4632 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4634 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4635 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4637 if (left > sizeof(struct objc_ivar_list_t)) {
4639 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4641 outs() << " (entends past the end of the section)\n";
4642 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4643 memcpy(&objc_ivar_list, p, left);
4645 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4646 swapStruct(objc_ivar_list);
4647 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4648 ivar_list = p + sizeof(struct objc_ivar_list_t);
4649 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4650 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4651 outs() << "\t\t remaining ivar's extend past the of the section\n";
4654 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4655 sizeof(struct objc_ivar_t));
4656 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4659 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4660 if (info->verbose) {
4661 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4662 if (name != nullptr)
4663 outs() << format(" %.*s", xleft, name);
4665 outs() << " (not in an __OBJC section)";
4669 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4670 if (info->verbose) {
4671 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4672 if (name != nullptr)
4673 outs() << format(" %.*s", xleft, name);
4675 outs() << " (not in an __OBJC section)";
4679 outs() << "\t\t ivar_offset "
4680 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4683 outs() << " (not in an __OBJC section)\n";
4686 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4687 if (print_method_list(objc_class->methodLists, info))
4688 outs() << " (not in an __OBJC section)\n";
4690 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4693 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4694 if (print_protocol_list(objc_class->protocols, 16, info))
4695 outs() << " (not in an __OBJC section)\n";
4698 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4699 struct DisassembleInfo *info) {
4700 uint32_t offset, left;
4704 outs() << "\t category name "
4705 << format("0x%08" PRIx32, objc_category->category_name);
4706 if (info->verbose) {
4707 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4709 if (name != nullptr)
4710 outs() << format(" %.*s", left, name);
4712 outs() << " (not in an __OBJC section)";
4716 outs() << "\t\t class name "
4717 << format("0x%08" PRIx32, objc_category->class_name);
4718 if (info->verbose) {
4720 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4721 if (name != nullptr)
4722 outs() << format(" %.*s", left, name);
4724 outs() << " (not in an __OBJC section)";
4728 outs() << "\t instance methods "
4729 << format("0x%08" PRIx32, objc_category->instance_methods);
4730 if (print_method_list(objc_category->instance_methods, info))
4731 outs() << " (not in an __OBJC section)\n";
4733 outs() << "\t class methods "
4734 << format("0x%08" PRIx32, objc_category->class_methods);
4735 if (print_method_list(objc_category->class_methods, info))
4736 outs() << " (not in an __OBJC section)\n";
4739 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4740 struct category64_t c;
4742 uint32_t offset, xoffset, left;
4744 const char *name, *sym_name;
4747 r = get_pointer_64(p, offset, left, S, info);
4750 memset(&c, '\0', sizeof(struct category64_t));
4751 if (left < sizeof(struct category64_t)) {
4752 memcpy(&c, r, left);
4753 outs() << " (category_t entends past the end of the section)\n";
4755 memcpy(&c, r, sizeof(struct category64_t));
4756 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4760 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4761 info, n_value, c.name);
4763 if (info->verbose && sym_name != nullptr)
4766 outs() << format("0x%" PRIx64, n_value);
4768 outs() << " + " << format("0x%" PRIx64, c.name);
4770 outs() << format("0x%" PRIx64, c.name);
4771 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4772 if (name != nullptr)
4773 outs() << format(" %.*s", left, name);
4777 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4780 if (info->verbose && sym_name != nullptr)
4783 outs() << format("0x%" PRIx64, n_value);
4785 outs() << " + " << format("0x%" PRIx64, c.cls);
4787 outs() << format("0x%" PRIx64, c.cls);
4789 if (c.cls + n_value != 0)
4790 print_class64_t(c.cls + n_value, info);
4792 outs() << " instanceMethods ";
4794 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4795 info, n_value, c.instanceMethods);
4797 if (info->verbose && sym_name != nullptr)
4800 outs() << format("0x%" PRIx64, n_value);
4801 if (c.instanceMethods != 0)
4802 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4804 outs() << format("0x%" PRIx64, c.instanceMethods);
4806 if (c.instanceMethods + n_value != 0)
4807 print_method_list64_t(c.instanceMethods + n_value, info, "");
4809 outs() << " classMethods ";
4810 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4811 S, info, n_value, c.classMethods);
4813 if (info->verbose && sym_name != nullptr)
4816 outs() << format("0x%" PRIx64, n_value);
4817 if (c.classMethods != 0)
4818 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4820 outs() << format("0x%" PRIx64, c.classMethods);
4822 if (c.classMethods + n_value != 0)
4823 print_method_list64_t(c.classMethods + n_value, info, "");
4825 outs() << " protocols ";
4826 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4827 info, n_value, c.protocols);
4829 if (info->verbose && sym_name != nullptr)
4832 outs() << format("0x%" PRIx64, n_value);
4833 if (c.protocols != 0)
4834 outs() << " + " << format("0x%" PRIx64, c.protocols);
4836 outs() << format("0x%" PRIx64, c.protocols);
4838 if (c.protocols + n_value != 0)
4839 print_protocol_list64_t(c.protocols + n_value, info);
4841 outs() << "instanceProperties ";
4843 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4844 S, info, n_value, c.instanceProperties);
4846 if (info->verbose && sym_name != nullptr)
4849 outs() << format("0x%" PRIx64, n_value);
4850 if (c.instanceProperties != 0)
4851 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4853 outs() << format("0x%" PRIx64, c.instanceProperties);
4855 if (c.instanceProperties + n_value != 0)
4856 print_objc_property_list64(c.instanceProperties + n_value, info);
4859 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4860 struct category32_t c;
4862 uint32_t offset, left;
4866 r = get_pointer_32(p, offset, left, S, info);
4869 memset(&c, '\0', sizeof(struct category32_t));
4870 if (left < sizeof(struct category32_t)) {
4871 memcpy(&c, r, left);
4872 outs() << " (category_t entends past the end of the section)\n";
4874 memcpy(&c, r, sizeof(struct category32_t));
4875 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4878 outs() << " name " << format("0x%" PRIx32, c.name);
4879 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4882 outs() << " " << name;
4885 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4887 print_class32_t(c.cls, info);
4888 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4890 if (c.instanceMethods != 0)
4891 print_method_list32_t(c.instanceMethods, info, "");
4892 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4894 if (c.classMethods != 0)
4895 print_method_list32_t(c.classMethods, info, "");
4896 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4897 if (c.protocols != 0)
4898 print_protocol_list32_t(c.protocols, info);
4899 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4901 if (c.instanceProperties != 0)
4902 print_objc_property_list32(c.instanceProperties, info);
4905 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4906 uint32_t i, left, offset, xoffset;
4907 uint64_t p, n_value;
4908 struct message_ref64 mr;
4909 const char *name, *sym_name;
4913 if (S == SectionRef())
4917 S.getName(SectName);
4918 DataRefImpl Ref = S.getRawDataRefImpl();
4919 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4920 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4922 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4923 p = S.getAddress() + i;
4924 r = get_pointer_64(p, offset, left, S, info);
4927 memset(&mr, '\0', sizeof(struct message_ref64));
4928 if (left < sizeof(struct message_ref64)) {
4929 memcpy(&mr, r, left);
4930 outs() << " (message_ref entends past the end of the section)\n";
4932 memcpy(&mr, r, sizeof(struct message_ref64));
4933 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4937 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4940 outs() << format("0x%" PRIx64, n_value) << " ";
4942 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4944 outs() << format("0x%" PRIx64, mr.imp) << " ";
4945 if (name != nullptr)
4946 outs() << " " << name;
4950 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4951 info, n_value, mr.sel);
4953 if (info->verbose && sym_name != nullptr)
4956 outs() << format("0x%" PRIx64, n_value);
4958 outs() << " + " << format("0x%" PRIx64, mr.sel);
4960 outs() << format("0x%" PRIx64, mr.sel);
4961 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4962 if (name != nullptr)
4963 outs() << format(" %.*s", left, name);
4966 offset += sizeof(struct message_ref64);
4970 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
4971 uint32_t i, left, offset, xoffset, p;
4972 struct message_ref32 mr;
4973 const char *name, *r;
4976 if (S == SectionRef())
4980 S.getName(SectName);
4981 DataRefImpl Ref = S.getRawDataRefImpl();
4982 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4983 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4985 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4986 p = S.getAddress() + i;
4987 r = get_pointer_32(p, offset, left, S, info);
4990 memset(&mr, '\0', sizeof(struct message_ref32));
4991 if (left < sizeof(struct message_ref32)) {
4992 memcpy(&mr, r, left);
4993 outs() << " (message_ref entends past the end of the section)\n";
4995 memcpy(&mr, r, sizeof(struct message_ref32));
4996 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4999 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5000 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5002 if (name != nullptr)
5003 outs() << " " << name;
5006 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5007 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5008 if (name != nullptr)
5009 outs() << " " << name;
5012 offset += sizeof(struct message_ref32);
5016 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5017 uint32_t left, offset, swift_version;
5019 struct objc_image_info64 o;
5022 if (S == SectionRef())
5026 S.getName(SectName);
5027 DataRefImpl Ref = S.getRawDataRefImpl();
5028 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5029 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5031 r = get_pointer_64(p, offset, left, S, info);
5034 memset(&o, '\0', sizeof(struct objc_image_info64));
5035 if (left < sizeof(struct objc_image_info64)) {
5036 memcpy(&o, r, left);
5037 outs() << " (objc_image_info entends past the end of the section)\n";
5039 memcpy(&o, r, sizeof(struct objc_image_info64));
5040 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5042 outs() << " version " << o.version << "\n";
5043 outs() << " flags " << format("0x%" PRIx32, o.flags);
5044 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5045 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5046 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5047 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5048 swift_version = (o.flags >> 8) & 0xff;
5049 if (swift_version != 0) {
5050 if (swift_version == 1)
5051 outs() << " Swift 1.0";
5052 else if (swift_version == 2)
5053 outs() << " Swift 1.1";
5055 outs() << " unknown future Swift version (" << swift_version << ")";
5060 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5061 uint32_t left, offset, swift_version, p;
5062 struct objc_image_info32 o;
5066 S.getName(SectName);
5067 DataRefImpl Ref = S.getRawDataRefImpl();
5068 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5069 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5071 r = get_pointer_32(p, offset, left, S, info);
5074 memset(&o, '\0', sizeof(struct objc_image_info32));
5075 if (left < sizeof(struct objc_image_info32)) {
5076 memcpy(&o, r, left);
5077 outs() << " (objc_image_info entends past the end of the section)\n";
5079 memcpy(&o, r, sizeof(struct objc_image_info32));
5080 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5082 outs() << " version " << o.version << "\n";
5083 outs() << " flags " << format("0x%" PRIx32, o.flags);
5084 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5085 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5086 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5087 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5088 swift_version = (o.flags >> 8) & 0xff;
5089 if (swift_version != 0) {
5090 if (swift_version == 1)
5091 outs() << " Swift 1.0";
5092 else if (swift_version == 2)
5093 outs() << " Swift 1.1";
5095 outs() << " unknown future Swift version (" << swift_version << ")";
5100 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5101 uint32_t left, offset, p;
5102 struct imageInfo_t o;
5106 S.getName(SectName);
5107 DataRefImpl Ref = S.getRawDataRefImpl();
5108 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5109 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5111 r = get_pointer_32(p, offset, left, S, info);
5114 memset(&o, '\0', sizeof(struct imageInfo_t));
5115 if (left < sizeof(struct imageInfo_t)) {
5116 memcpy(&o, r, left);
5117 outs() << " (imageInfo entends past the end of the section)\n";
5119 memcpy(&o, r, sizeof(struct imageInfo_t));
5120 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5122 outs() << " version " << o.version << "\n";
5123 outs() << " flags " << format("0x%" PRIx32, o.flags);
5129 outs() << " GC-only";
5135 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5136 SymbolAddressMap AddrMap;
5138 CreateSymbolAddressMap(O, &AddrMap);
5140 std::vector<SectionRef> Sections;
5141 for (const SectionRef &Section : O->sections()) {
5143 Section.getName(SectName);
5144 Sections.push_back(Section);
5147 struct DisassembleInfo info;
5148 // Set up the block of info used by the Symbolizer call backs.
5149 info.verbose = verbose;
5151 info.AddrMap = &AddrMap;
5152 info.Sections = &Sections;
5153 info.class_name = nullptr;
5154 info.selector_name = nullptr;
5155 info.method = nullptr;
5156 info.demangled_name = nullptr;
5157 info.bindtable = nullptr;
5162 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5163 if (CL != SectionRef()) {
5165 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5167 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5169 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5172 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5173 if (CR != SectionRef()) {
5175 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5177 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5179 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5182 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5183 if (SR != SectionRef()) {
5185 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5187 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5189 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5192 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5193 if (CA != SectionRef()) {
5195 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5197 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5199 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5202 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5203 if (PL != SectionRef()) {
5205 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5207 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5209 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5212 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5213 if (MR != SectionRef()) {
5215 print_message_refs64(MR, &info);
5217 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5219 print_message_refs64(MR, &info);
5222 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5223 if (II != SectionRef()) {
5225 print_image_info64(II, &info);
5227 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5229 print_image_info64(II, &info);
5232 if (info.bindtable != nullptr)
5233 delete info.bindtable;
5236 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5237 SymbolAddressMap AddrMap;
5239 CreateSymbolAddressMap(O, &AddrMap);
5241 std::vector<SectionRef> Sections;
5242 for (const SectionRef &Section : O->sections()) {
5244 Section.getName(SectName);
5245 Sections.push_back(Section);
5248 struct DisassembleInfo info;
5249 // Set up the block of info used by the Symbolizer call backs.
5250 info.verbose = verbose;
5252 info.AddrMap = &AddrMap;
5253 info.Sections = &Sections;
5254 info.class_name = nullptr;
5255 info.selector_name = nullptr;
5256 info.method = nullptr;
5257 info.demangled_name = nullptr;
5258 info.bindtable = nullptr;
5262 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5263 if (CL != SectionRef()) {
5265 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5267 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5269 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5272 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5273 if (CR != SectionRef()) {
5275 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5277 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5279 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5282 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5283 if (SR != SectionRef()) {
5285 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5287 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5289 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5292 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5293 if (CA != SectionRef()) {
5295 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5297 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5299 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5302 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5303 if (PL != SectionRef()) {
5305 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5307 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5309 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5312 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5313 if (MR != SectionRef()) {
5315 print_message_refs32(MR, &info);
5317 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5319 print_message_refs32(MR, &info);
5322 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5323 if (II != SectionRef()) {
5325 print_image_info32(II, &info);
5327 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5329 print_image_info32(II, &info);
5333 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5334 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5335 const char *r, *name, *defs;
5336 struct objc_module_t module;
5338 struct objc_symtab_t symtab;
5339 struct objc_class_t objc_class;
5340 struct objc_category_t objc_category;
5342 outs() << "Objective-C segment\n";
5343 S = get_section(O, "__OBJC", "__module_info");
5344 if (S == SectionRef())
5347 SymbolAddressMap AddrMap;
5349 CreateSymbolAddressMap(O, &AddrMap);
5351 std::vector<SectionRef> Sections;
5352 for (const SectionRef &Section : O->sections()) {
5354 Section.getName(SectName);
5355 Sections.push_back(Section);
5358 struct DisassembleInfo info;
5359 // Set up the block of info used by the Symbolizer call backs.
5360 info.verbose = verbose;
5362 info.AddrMap = &AddrMap;
5363 info.Sections = &Sections;
5364 info.class_name = nullptr;
5365 info.selector_name = nullptr;
5366 info.method = nullptr;
5367 info.demangled_name = nullptr;
5368 info.bindtable = nullptr;
5372 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5373 p = S.getAddress() + i;
5374 r = get_pointer_32(p, offset, left, S, &info, true);
5377 memset(&module, '\0', sizeof(struct objc_module_t));
5378 if (left < sizeof(struct objc_module_t)) {
5379 memcpy(&module, r, left);
5380 outs() << " (module extends past end of __module_info section)\n";
5382 memcpy(&module, r, sizeof(struct objc_module_t));
5383 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5386 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5387 outs() << " version " << module.version << "\n";
5388 outs() << " size " << module.size << "\n";
5390 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5391 if (name != nullptr)
5392 outs() << format("%.*s", left, name);
5394 outs() << format("0x%08" PRIx32, module.name)
5395 << "(not in an __OBJC section)";
5398 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5399 if (module.symtab == 0 || r == nullptr) {
5400 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5401 << " (not in an __OBJC section)\n";
5404 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5405 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5408 if (left < sizeof(struct objc_symtab_t)) {
5409 memcpy(&symtab, r, left);
5410 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5412 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5413 if (left > sizeof(struct objc_symtab_t)) {
5414 defs_left = left - sizeof(struct objc_symtab_t);
5415 defs = r + sizeof(struct objc_symtab_t);
5418 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5421 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5422 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5423 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5425 outs() << " (not in an __OBJC section)";
5427 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5428 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5429 if (symtab.cls_def_cnt > 0)
5430 outs() << "\tClass Definitions\n";
5431 for (j = 0; j < symtab.cls_def_cnt; j++) {
5432 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5433 outs() << "\t(remaining class defs entries entends past the end of the "
5437 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5438 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5439 sys::swapByteOrder(def);
5441 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5442 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5444 if (left > sizeof(struct objc_class_t)) {
5446 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5448 outs() << " (entends past the end of the section)\n";
5449 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5450 memcpy(&objc_class, r, left);
5452 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5453 swapStruct(objc_class);
5454 print_objc_class_t(&objc_class, &info);
5456 outs() << "(not in an __OBJC section)\n";
5459 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5460 outs() << "\tMeta Class";
5461 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5463 if (left > sizeof(struct objc_class_t)) {
5465 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5467 outs() << " (entends past the end of the section)\n";
5468 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5469 memcpy(&objc_class, r, left);
5471 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5472 swapStruct(objc_class);
5473 print_objc_class_t(&objc_class, &info);
5475 outs() << "(not in an __OBJC section)\n";
5479 if (symtab.cat_def_cnt > 0)
5480 outs() << "\tCategory Definitions\n";
5481 for (j = 0; j < symtab.cat_def_cnt; j++) {
5482 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5483 outs() << "\t(remaining category defs entries entends past the end of "
5484 << "the section)\n";
5487 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5489 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5490 sys::swapByteOrder(def);
5492 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5493 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5494 << format("0x%08" PRIx32, def);
5496 if (left > sizeof(struct objc_category_t)) {
5498 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5500 outs() << " (entends past the end of the section)\n";
5501 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5502 memcpy(&objc_category, r, left);
5504 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5505 swapStruct(objc_category);
5506 print_objc_objc_category_t(&objc_category, &info);
5508 outs() << "(not in an __OBJC section)\n";
5512 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5513 if (II != SectionRef())
5514 print_image_info(II, &info);
5519 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5520 uint32_t size, uint32_t addr) {
5521 SymbolAddressMap AddrMap;
5522 CreateSymbolAddressMap(O, &AddrMap);
5524 std::vector<SectionRef> Sections;
5525 for (const SectionRef &Section : O->sections()) {
5527 Section.getName(SectName);
5528 Sections.push_back(Section);
5531 struct DisassembleInfo info;
5532 // Set up the block of info used by the Symbolizer call backs.
5533 info.verbose = true;
5535 info.AddrMap = &AddrMap;
5536 info.Sections = &Sections;
5537 info.class_name = nullptr;
5538 info.selector_name = nullptr;
5539 info.method = nullptr;
5540 info.demangled_name = nullptr;
5541 info.bindtable = nullptr;
5546 struct objc_protocol_t protocol;
5547 uint32_t left, paddr;
5548 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5549 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5550 left = size - (p - sect);
5551 if (left < sizeof(struct objc_protocol_t)) {
5552 outs() << "Protocol extends past end of __protocol section\n";
5553 memcpy(&protocol, p, left);
5555 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5556 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5557 swapStruct(protocol);
5558 paddr = addr + (p - sect);
5559 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5560 if (print_protocol(paddr, 0, &info))
5561 outs() << "(not in an __OBJC section)\n";
5565 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5567 printObjc2_64bit_MetaData(O, verbose);
5569 MachO::mach_header H;
5571 if (H.cputype == MachO::CPU_TYPE_ARM)
5572 printObjc2_32bit_MetaData(O, verbose);
5574 // This is the 32-bit non-arm cputype case. Which is normally
5575 // the first Objective-C ABI. But it may be the case of a
5576 // binary for the iOS simulator which is the second Objective-C
5577 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5578 // and return false.
5579 if (!printObjc1_32bit_MetaData(O, verbose))
5580 printObjc2_32bit_MetaData(O, verbose);
5585 // GuessLiteralPointer returns a string which for the item in the Mach-O file
5586 // for the address passed in as ReferenceValue for printing as a comment with
5587 // the instruction and also returns the corresponding type of that item
5588 // indirectly through ReferenceType.
5590 // If ReferenceValue is an address of literal cstring then a pointer to the
5591 // cstring is returned and ReferenceType is set to
5592 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5594 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5595 // Class ref that name is returned and the ReferenceType is set accordingly.
5597 // Lastly, literals which are Symbol address in a literal pool are looked for
5598 // and if found the symbol name is returned and ReferenceType is set to
5599 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5601 // If there is no item in the Mach-O file for the address passed in as
5602 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
5603 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5604 uint64_t ReferencePC,
5605 uint64_t *ReferenceType,
5606 struct DisassembleInfo *info) {
5607 // First see if there is an external relocation entry at the ReferencePC.
5608 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
5609 uint64_t sect_addr = info->S.getAddress();
5610 uint64_t sect_offset = ReferencePC - sect_addr;
5611 bool reloc_found = false;
5613 MachO::any_relocation_info RE;
5614 bool isExtern = false;
5616 for (const RelocationRef &Reloc : info->S.relocations()) {
5617 uint64_t RelocOffset = Reloc.getOffset();
5618 if (RelocOffset == sect_offset) {
5619 Rel = Reloc.getRawDataRefImpl();
5620 RE = info->O->getRelocation(Rel);
5621 if (info->O->isRelocationScattered(RE))
5623 isExtern = info->O->getPlainRelocationExternal(RE);
5625 symbol_iterator RelocSym = Reloc.getSymbol();
5632 // If there is an external relocation entry for a symbol in a section
5633 // then used that symbol's value for the value of the reference.
5634 if (reloc_found && isExtern) {
5635 if (info->O->getAnyRelocationPCRel(RE)) {
5636 unsigned Type = info->O->getAnyRelocationType(RE);
5637 if (Type == MachO::X86_64_RELOC_SIGNED) {
5638 ReferenceValue = Symbol.getValue();
5644 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5645 // Message refs and Class refs.
5646 bool classref, selref, msgref, cfstring;
5647 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5648 selref, msgref, cfstring);
5649 if (classref && pointer_value == 0) {
5650 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5651 // And the pointer_value in that section is typically zero as it will be
5652 // set by dyld as part of the "bind information".
5653 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5654 if (name != nullptr) {
5655 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5656 const char *class_name = strrchr(name, '$');
5657 if (class_name != nullptr && class_name[1] == '_' &&
5658 class_name[2] != '\0') {
5659 info->class_name = class_name + 2;
5666 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5668 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5669 if (name != nullptr)
5670 info->class_name = name;
5672 name = "bad class ref";
5677 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5678 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5682 if (selref && pointer_value == 0)
5683 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5685 if (pointer_value != 0)
5686 ReferenceValue = pointer_value;
5688 const char *name = GuessCstringPointer(ReferenceValue, info);
5690 if (pointer_value != 0 && selref) {
5691 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5692 info->selector_name = name;
5693 } else if (pointer_value != 0 && msgref) {
5694 info->class_name = nullptr;
5695 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5696 info->selector_name = name;
5698 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5702 // Lastly look for an indirect symbol with this ReferenceValue which is in
5703 // a literal pool. If found return that symbol name.
5704 name = GuessIndirectSymbol(ReferenceValue, info);
5706 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5713 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
5714 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
5715 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5716 // is created and returns the symbol name that matches the ReferenceValue or
5717 // nullptr if none. The ReferenceType is passed in for the IN type of
5718 // reference the instruction is making from the values in defined in the header
5719 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5720 // Out type and the ReferenceName will also be set which is added as a comment
5721 // to the disassembled instruction.
5724 // If the symbol name is a C++ mangled name then the demangled name is
5725 // returned through ReferenceName and ReferenceType is set to
5726 // LLVMDisassembler_ReferenceType_DeMangled_Name .
5729 // When this is called to get a symbol name for a branch target then the
5730 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5731 // SymbolValue will be looked for in the indirect symbol table to determine if
5732 // it is an address for a symbol stub. If so then the symbol name for that
5733 // stub is returned indirectly through ReferenceName and then ReferenceType is
5734 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5736 // When this is called with an value loaded via a PC relative load then
5737 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5738 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
5739 // or an Objective-C meta data reference. If so the output ReferenceType is
5740 // set to correspond to that as well as setting the ReferenceName.
5741 static const char *SymbolizerSymbolLookUp(void *DisInfo,
5742 uint64_t ReferenceValue,
5743 uint64_t *ReferenceType,
5744 uint64_t ReferencePC,
5745 const char **ReferenceName) {
5746 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
5747 // If no verbose symbolic information is wanted then just return nullptr.
5748 if (!info->verbose) {
5749 *ReferenceName = nullptr;
5750 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5754 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
5756 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5757 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
5758 if (*ReferenceName != nullptr) {
5759 method_reference(info, ReferenceType, ReferenceName);
5760 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5761 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5764 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5765 if (info->demangled_name != nullptr)
5766 free(info->demangled_name);
5768 info->demangled_name =
5769 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5770 if (info->demangled_name != nullptr) {
5771 *ReferenceName = info->demangled_name;
5772 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5774 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5777 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5778 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5780 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5782 method_reference(info, ReferenceType, ReferenceName);
5784 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5785 // If this is arm64 and the reference is an adrp instruction save the
5786 // instruction, passed in ReferenceValue and the address of the instruction
5787 // for use later if we see and add immediate instruction.
5788 } else if (info->O->getArch() == Triple::aarch64 &&
5789 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5790 info->adrp_inst = ReferenceValue;
5791 info->adrp_addr = ReferencePC;
5792 SymbolName = nullptr;
5793 *ReferenceName = nullptr;
5794 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5795 // If this is arm64 and reference is an add immediate instruction and we
5797 // seen an adrp instruction just before it and the adrp's Xd register
5799 // this add's Xn register reconstruct the value being referenced and look to
5800 // see if it is a literal pointer. Note the add immediate instruction is
5801 // passed in ReferenceValue.
5802 } else if (info->O->getArch() == Triple::aarch64 &&
5803 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5804 ReferencePC - 4 == info->adrp_addr &&
5805 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5806 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5807 uint32_t addxri_inst;
5808 uint64_t adrp_imm, addxri_imm;
5811 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5812 if (info->adrp_inst & 0x0200000)
5813 adrp_imm |= 0xfffffffffc000000LL;
5815 addxri_inst = ReferenceValue;
5816 addxri_imm = (addxri_inst >> 10) & 0xfff;
5817 if (((addxri_inst >> 22) & 0x3) == 1)
5820 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5821 (adrp_imm << 12) + addxri_imm;
5824 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5825 if (*ReferenceName == nullptr)
5826 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5827 // If this is arm64 and the reference is a load register instruction and we
5828 // have seen an adrp instruction just before it and the adrp's Xd register
5829 // matches this add's Xn register reconstruct the value being referenced and
5830 // look to see if it is a literal pointer. Note the load register
5831 // instruction is passed in ReferenceValue.
5832 } else if (info->O->getArch() == Triple::aarch64 &&
5833 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5834 ReferencePC - 4 == info->adrp_addr &&
5835 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5836 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5837 uint32_t ldrxui_inst;
5838 uint64_t adrp_imm, ldrxui_imm;
5841 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5842 if (info->adrp_inst & 0x0200000)
5843 adrp_imm |= 0xfffffffffc000000LL;
5845 ldrxui_inst = ReferenceValue;
5846 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5848 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5849 (adrp_imm << 12) + (ldrxui_imm << 3);
5852 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5853 if (*ReferenceName == nullptr)
5854 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5856 // If this arm64 and is an load register (PC-relative) instruction the
5857 // ReferenceValue is the PC plus the immediate value.
5858 else if (info->O->getArch() == Triple::aarch64 &&
5859 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5860 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5862 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5863 if (*ReferenceName == nullptr)
5864 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5867 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5868 if (info->demangled_name != nullptr)
5869 free(info->demangled_name);
5871 info->demangled_name =
5872 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5873 if (info->demangled_name != nullptr) {
5874 *ReferenceName = info->demangled_name;
5875 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5880 *ReferenceName = nullptr;
5881 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5887 /// \brief Emits the comments that are stored in the CommentStream.
5888 /// Each comment in the CommentStream must end with a newline.
5889 static void emitComments(raw_svector_ostream &CommentStream,
5890 SmallString<128> &CommentsToEmit,
5891 formatted_raw_ostream &FormattedOS,
5892 const MCAsmInfo &MAI) {
5893 // Flush the stream before taking its content.
5894 StringRef Comments = CommentsToEmit.str();
5895 // Get the default information for printing a comment.
5896 const char *CommentBegin = MAI.getCommentString();
5897 unsigned CommentColumn = MAI.getCommentColumn();
5898 bool IsFirst = true;
5899 while (!Comments.empty()) {
5901 FormattedOS << '\n';
5902 // Emit a line of comments.
5903 FormattedOS.PadToColumn(CommentColumn);
5904 size_t Position = Comments.find('\n');
5905 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5906 // Move after the newline character.
5907 Comments = Comments.substr(Position + 1);
5910 FormattedOS.flush();
5912 // Tell the comment stream that the vector changed underneath it.
5913 CommentsToEmit.clear();
5916 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5917 StringRef DisSegName, StringRef DisSectName) {
5918 const char *McpuDefault = nullptr;
5919 const Target *ThumbTarget = nullptr;
5920 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
5922 // GetTarget prints out stuff.
5925 if (MCPU.empty() && McpuDefault)
5928 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
5929 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
5931 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
5933 // Package up features to be passed to target/subtarget
5934 std::string FeaturesStr;
5935 if (MAttrs.size()) {
5936 SubtargetFeatures Features;
5937 for (unsigned i = 0; i != MAttrs.size(); ++i)
5938 Features.AddFeature(MAttrs[i]);
5939 FeaturesStr = Features.getString();
5942 // Set up disassembler.
5943 std::unique_ptr<const MCRegisterInfo> MRI(
5944 TheTarget->createMCRegInfo(TripleName));
5945 std::unique_ptr<const MCAsmInfo> AsmInfo(
5946 TheTarget->createMCAsmInfo(*MRI, TripleName));
5947 std::unique_ptr<const MCSubtargetInfo> STI(
5948 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
5949 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
5950 std::unique_ptr<MCDisassembler> DisAsm(
5951 TheTarget->createMCDisassembler(*STI, Ctx));
5952 std::unique_ptr<MCSymbolizer> Symbolizer;
5953 struct DisassembleInfo SymbolizerInfo;
5954 std::unique_ptr<MCRelocationInfo> RelInfo(
5955 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5957 Symbolizer.reset(TheTarget->createMCSymbolizer(
5958 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5959 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
5960 DisAsm->setSymbolizer(std::move(Symbolizer));
5962 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
5963 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
5964 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
5965 // Set the display preference for hex vs. decimal immediates.
5966 IP->setPrintImmHex(PrintImmHex);
5967 // Comment stream and backing vector.
5968 SmallString<128> CommentsToEmit;
5969 raw_svector_ostream CommentStream(CommentsToEmit);
5970 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5971 // if it is done then arm64 comments for string literals don't get printed
5972 // and some constant get printed instead and not setting it causes intel
5973 // (32-bit and 64-bit) comments printed with different spacing before the
5974 // comment causing different diffs with the 'C' disassembler library API.
5975 // IP->setCommentStream(CommentStream);
5977 if (!AsmInfo || !STI || !DisAsm || !IP) {
5978 errs() << "error: couldn't initialize disassembler for target "
5979 << TripleName << '\n';
5983 // Set up thumb disassembler.
5984 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5985 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5986 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
5987 std::unique_ptr<MCDisassembler> ThumbDisAsm;
5988 std::unique_ptr<MCInstPrinter> ThumbIP;
5989 std::unique_ptr<MCContext> ThumbCtx;
5990 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5991 struct DisassembleInfo ThumbSymbolizerInfo;
5992 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
5994 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
5996 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
5998 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
5999 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6000 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
6001 MCContext *PtrThumbCtx = ThumbCtx.get();
6003 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6005 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6006 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
6007 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
6008 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6010 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6011 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
6012 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6013 *ThumbInstrInfo, *ThumbMRI));
6014 // Set the display preference for hex vs. decimal immediates.
6015 ThumbIP->setPrintImmHex(PrintImmHex);
6018 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
6019 errs() << "error: couldn't initialize disassembler for target "
6020 << ThumbTripleName << '\n';
6024 MachO::mach_header Header = MachOOF->getHeader();
6026 // FIXME: Using the -cfg command line option, this code used to be able to
6027 // annotate relocations with the referenced symbol's name, and if this was
6028 // inside a __[cf]string section, the data it points to. This is now replaced
6029 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
6030 std::vector<SectionRef> Sections;
6031 std::vector<SymbolRef> Symbols;
6032 SmallVector<uint64_t, 8> FoundFns;
6033 uint64_t BaseSegmentAddress;
6035 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
6036 BaseSegmentAddress);
6038 // Sort the symbols by address, just in case they didn't come in that way.
6039 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
6041 // Build a data in code table that is sorted on by the address of each entry.
6042 uint64_t BaseAddress = 0;
6043 if (Header.filetype == MachO::MH_OBJECT)
6044 BaseAddress = Sections[0].getAddress();
6046 BaseAddress = BaseSegmentAddress;
6048 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
6051 DI->getOffset(Offset);
6052 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6054 array_pod_sort(Dices.begin(), Dices.end());
6057 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6059 raw_ostream &DebugOut = nulls();
6062 std::unique_ptr<DIContext> diContext;
6063 ObjectFile *DbgObj = MachOOF;
6064 // Try to find debug info and set up the DIContext for it.
6066 // A separate DSym file path was specified, parse it as a macho file,
6067 // get the sections and supply it to the section name parsing machinery.
6068 if (!DSYMFile.empty()) {
6069 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
6070 MemoryBuffer::getFileOrSTDIN(DSYMFile);
6071 if (std::error_code EC = BufOrErr.getError()) {
6072 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
6076 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6081 // Setup the DIContext
6082 diContext.reset(new DWARFContextInMemory(*DbgObj));
6085 if (FilterSections.size() == 0)
6086 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
6088 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
6090 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6093 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
6095 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
6096 if (SegmentName != DisSegName)
6100 Sections[SectIdx].getContents(BytesStr);
6101 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6103 uint64_t SectAddress = Sections[SectIdx].getAddress();
6105 bool symbolTableWorked = false;
6107 // Create a map of symbol addresses to symbol names for use by
6108 // the SymbolizerSymbolLookUp() routine.
6109 SymbolAddressMap AddrMap;
6110 bool DisSymNameFound = false;
6111 for (const SymbolRef &Symbol : MachOOF->symbols()) {
6112 SymbolRef::Type ST = Symbol.getType();
6113 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6114 ST == SymbolRef::ST_Other) {
6115 uint64_t Address = Symbol.getValue();
6116 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6117 if (std::error_code EC = SymNameOrErr.getError())
6118 report_fatal_error(EC.message());
6119 StringRef SymName = *SymNameOrErr;
6120 AddrMap[Address] = SymName;
6121 if (!DisSymName.empty() && DisSymName == SymName)
6122 DisSymNameFound = true;
6125 if (!DisSymName.empty() && !DisSymNameFound) {
6126 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6129 // Set up the block of info used by the Symbolizer call backs.
6130 SymbolizerInfo.verbose = !NoSymbolicOperands;
6131 SymbolizerInfo.O = MachOOF;
6132 SymbolizerInfo.S = Sections[SectIdx];
6133 SymbolizerInfo.AddrMap = &AddrMap;
6134 SymbolizerInfo.Sections = &Sections;
6135 SymbolizerInfo.class_name = nullptr;
6136 SymbolizerInfo.selector_name = nullptr;
6137 SymbolizerInfo.method = nullptr;
6138 SymbolizerInfo.demangled_name = nullptr;
6139 SymbolizerInfo.bindtable = nullptr;
6140 SymbolizerInfo.adrp_addr = 0;
6141 SymbolizerInfo.adrp_inst = 0;
6142 // Same for the ThumbSymbolizer
6143 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
6144 ThumbSymbolizerInfo.O = MachOOF;
6145 ThumbSymbolizerInfo.S = Sections[SectIdx];
6146 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6147 ThumbSymbolizerInfo.Sections = &Sections;
6148 ThumbSymbolizerInfo.class_name = nullptr;
6149 ThumbSymbolizerInfo.selector_name = nullptr;
6150 ThumbSymbolizerInfo.method = nullptr;
6151 ThumbSymbolizerInfo.demangled_name = nullptr;
6152 ThumbSymbolizerInfo.bindtable = nullptr;
6153 ThumbSymbolizerInfo.adrp_addr = 0;
6154 ThumbSymbolizerInfo.adrp_inst = 0;
6156 // Disassemble symbol by symbol.
6157 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
6158 ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6159 if (std::error_code EC = SymNameOrErr.getError())
6160 report_fatal_error(EC.message());
6161 StringRef SymName = *SymNameOrErr;
6163 SymbolRef::Type ST = Symbols[SymIdx].getType();
6164 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
6167 // Make sure the symbol is defined in this section.
6168 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
6172 // If we are only disassembling one symbol see if this is that symbol.
6173 if (!DisSymName.empty() && DisSymName != SymName)
6176 // Start at the address of the symbol relative to the section's address.
6177 uint64_t Start = Symbols[SymIdx].getValue();
6178 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6179 Start -= SectionAddress;
6181 // Stop disassembling either at the beginning of the next symbol or at
6182 // the end of the section.
6183 bool containsNextSym = false;
6184 uint64_t NextSym = 0;
6185 uint64_t NextSymIdx = SymIdx + 1;
6186 while (Symbols.size() > NextSymIdx) {
6187 SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
6188 if (NextSymType == SymbolRef::ST_Function) {
6190 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
6191 NextSym = Symbols[NextSymIdx].getValue();
6192 NextSym -= SectionAddress;
6198 uint64_t SectSize = Sections[SectIdx].getSize();
6199 uint64_t End = containsNextSym ? NextSym : SectSize;
6202 symbolTableWorked = true;
6204 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6206 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6208 outs() << SymName << ":\n";
6209 DILineInfo lastLine;
6210 for (uint64_t Index = Start; Index < End; Index += Size) {
6213 uint64_t PC = SectAddress + Index;
6214 if (!NoLeadingAddr) {
6215 if (FullLeadingAddr) {
6216 if (MachOOF->is64Bit())
6217 outs() << format("%016" PRIx64, PC);
6219 outs() << format("%08" PRIx64, PC);
6221 outs() << format("%8" PRIx64 ":", PC);
6227 // Check the data in code table here to see if this is data not an
6228 // instruction to be disassembled.
6230 Dice.push_back(std::make_pair(PC, DiceRef()));
6231 dice_table_iterator DTI =
6232 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6233 compareDiceTableEntries);
6234 if (DTI != Dices.end()) {
6236 DTI->second.getLength(Length);
6238 DTI->second.getKind(Kind);
6239 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
6240 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6241 (PC == (DTI->first + Length - 1)) && (Length & 1))
6246 SmallVector<char, 64> AnnotationsBytes;
6247 raw_svector_ostream Annotations(AnnotationsBytes);
6251 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
6252 PC, DebugOut, Annotations);
6254 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
6255 DebugOut, Annotations);
6257 if (!NoShowRawInsn) {
6258 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
6260 formatted_raw_ostream FormattedOS(outs());
6261 StringRef AnnotationsStr = Annotations.str();
6263 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
6265 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
6266 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
6268 // Print debug info.
6270 DILineInfo dli = diContext->getLineInfoForAddress(PC);
6271 // Print valid line info if it changed.
6272 if (dli != lastLine && dli.Line != 0)
6273 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6279 unsigned int Arch = MachOOF->getArch();
6280 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6281 outs() << format("\t.byte 0x%02x #bad opcode\n",
6282 *(Bytes.data() + Index) & 0xff);
6283 Size = 1; // skip exactly one illegible byte and move on.
6284 } else if (Arch == Triple::aarch64) {
6285 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6286 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6287 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6288 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6289 outs() << format("\t.long\t0x%08x\n", opcode);
6292 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6294 Size = 1; // skip illegible bytes
6299 if (!symbolTableWorked) {
6300 // Reading the symbol table didn't work, disassemble the whole section.
6301 uint64_t SectAddress = Sections[SectIdx].getAddress();
6302 uint64_t SectSize = Sections[SectIdx].getSize();
6304 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
6307 uint64_t PC = SectAddress + Index;
6308 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6309 DebugOut, nulls())) {
6310 if (!NoLeadingAddr) {
6311 if (FullLeadingAddr) {
6312 if (MachOOF->is64Bit())
6313 outs() << format("%016" PRIx64, PC);
6315 outs() << format("%08" PRIx64, PC);
6317 outs() << format("%8" PRIx64 ":", PC);
6320 if (!NoShowRawInsn) {
6322 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
6324 IP->printInst(&Inst, outs(), "", *STI);
6327 unsigned int Arch = MachOOF->getArch();
6328 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6329 outs() << format("\t.byte 0x%02x #bad opcode\n",
6330 *(Bytes.data() + Index) & 0xff);
6331 InstSize = 1; // skip exactly one illegible byte and move on.
6333 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6335 InstSize = 1; // skip illegible bytes
6340 // The TripleName's need to be reset if we are called again for a different
6343 ThumbTripleName = "";
6345 if (SymbolizerInfo.method != nullptr)
6346 free(SymbolizerInfo.method);
6347 if (SymbolizerInfo.demangled_name != nullptr)
6348 free(SymbolizerInfo.demangled_name);
6349 if (SymbolizerInfo.bindtable != nullptr)
6350 delete SymbolizerInfo.bindtable;
6351 if (ThumbSymbolizerInfo.method != nullptr)
6352 free(ThumbSymbolizerInfo.method);
6353 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6354 free(ThumbSymbolizerInfo.demangled_name);
6355 if (ThumbSymbolizerInfo.bindtable != nullptr)
6356 delete ThumbSymbolizerInfo.bindtable;
6360 //===----------------------------------------------------------------------===//
6361 // __compact_unwind section dumping
6362 //===----------------------------------------------------------------------===//
6366 template <typename T> static uint64_t readNext(const char *&Buf) {
6367 using llvm::support::little;
6368 using llvm::support::unaligned;
6370 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6375 struct CompactUnwindEntry {
6376 uint32_t OffsetInSection;
6378 uint64_t FunctionAddr;
6380 uint32_t CompactEncoding;
6381 uint64_t PersonalityAddr;
6384 RelocationRef FunctionReloc;
6385 RelocationRef PersonalityReloc;
6386 RelocationRef LSDAReloc;
6388 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
6389 : OffsetInSection(Offset) {
6391 read<uint64_t>(Contents.data() + Offset);
6393 read<uint32_t>(Contents.data() + Offset);
6397 template <typename UIntPtr> void read(const char *Buf) {
6398 FunctionAddr = readNext<UIntPtr>(Buf);
6399 Length = readNext<uint32_t>(Buf);
6400 CompactEncoding = readNext<uint32_t>(Buf);
6401 PersonalityAddr = readNext<UIntPtr>(Buf);
6402 LSDAAddr = readNext<UIntPtr>(Buf);
6407 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
6408 /// and data being relocated, determine the best base Name and Addend to use for
6409 /// display purposes.
6411 /// 1. An Extern relocation will directly reference a symbol (and the data is
6412 /// then already an addend), so use that.
6413 /// 2. Otherwise the data is an offset in the object file's layout; try to find
6414 // a symbol before it in the same section, and use the offset from there.
6415 /// 3. Finally, if all that fails, fall back to an offset from the start of the
6416 /// referenced section.
6417 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6418 std::map<uint64_t, SymbolRef> &Symbols,
6419 const RelocationRef &Reloc, uint64_t Addr,
6420 StringRef &Name, uint64_t &Addend) {
6421 if (Reloc.getSymbol() != Obj->symbol_end()) {
6422 ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6423 if (std::error_code EC = NameOrErr.getError())
6424 report_fatal_error(EC.message());
6430 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
6431 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
6433 uint64_t SectionAddr = RelocSection.getAddress();
6435 auto Sym = Symbols.upper_bound(Addr);
6436 if (Sym == Symbols.begin()) {
6437 // The first symbol in the object is after this reference, the best we can
6438 // do is section-relative notation.
6439 RelocSection.getName(Name);
6440 Addend = Addr - SectionAddr;
6444 // Go back one so that SymbolAddress <= Addr.
6447 section_iterator SymSection = *Sym->second.getSection();
6448 if (RelocSection == *SymSection) {
6449 // There's a valid symbol in the same section before this reference.
6450 ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6451 if (std::error_code EC = NameOrErr.getError())
6452 report_fatal_error(EC.message());
6454 Addend = Addr - Sym->first;
6458 // There is a symbol before this reference, but it's in a different
6459 // section. Probably not helpful to mention it, so use the section name.
6460 RelocSection.getName(Name);
6461 Addend = Addr - SectionAddr;
6464 static void printUnwindRelocDest(const MachOObjectFile *Obj,
6465 std::map<uint64_t, SymbolRef> &Symbols,
6466 const RelocationRef &Reloc, uint64_t Addr) {
6470 if (!Reloc.getObject())
6473 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6477 outs() << " + " << format("0x%" PRIx64, Addend);
6481 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6482 std::map<uint64_t, SymbolRef> &Symbols,
6483 const SectionRef &CompactUnwind) {
6485 assert(Obj->isLittleEndian() &&
6486 "There should not be a big-endian .o with __compact_unwind");
6488 bool Is64 = Obj->is64Bit();
6489 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6490 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6493 CompactUnwind.getContents(Contents);
6495 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6497 // First populate the initial raw offsets, encodings and so on from the entry.
6498 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6499 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6500 CompactUnwinds.push_back(Entry);
6503 // Next we need to look at the relocations to find out what objects are
6504 // actually being referred to.
6505 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
6506 uint64_t RelocAddress = Reloc.getOffset();
6508 uint32_t EntryIdx = RelocAddress / EntrySize;
6509 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6510 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6512 if (OffsetInEntry == 0)
6513 Entry.FunctionReloc = Reloc;
6514 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6515 Entry.PersonalityReloc = Reloc;
6516 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6517 Entry.LSDAReloc = Reloc;
6519 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6522 // Finally, we're ready to print the data we've gathered.
6523 outs() << "Contents of __compact_unwind section:\n";
6524 for (auto &Entry : CompactUnwinds) {
6525 outs() << " Entry at offset "
6526 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
6528 // 1. Start of the region this entry applies to.
6529 outs() << " start: " << format("0x%" PRIx64,
6530 Entry.FunctionAddr) << ' ';
6531 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
6534 // 2. Length of the region this entry applies to.
6535 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6537 // 3. The 32-bit compact encoding.
6538 outs() << " compact encoding: "
6539 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
6541 // 4. The personality function, if present.
6542 if (Entry.PersonalityReloc.getObject()) {
6543 outs() << " personality function: "
6544 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
6545 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6546 Entry.PersonalityAddr);
6550 // 5. This entry's language-specific data area.
6551 if (Entry.LSDAReloc.getObject()) {
6552 outs() << " LSDA: " << format("0x%" PRIx64,
6553 Entry.LSDAAddr) << ' ';
6554 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6560 //===----------------------------------------------------------------------===//
6561 // __unwind_info section dumping
6562 //===----------------------------------------------------------------------===//
6564 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6565 const char *Pos = PageStart;
6566 uint32_t Kind = readNext<uint32_t>(Pos);
6568 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6570 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6571 uint16_t NumEntries = readNext<uint16_t>(Pos);
6573 Pos = PageStart + EntriesStart;
6574 for (unsigned i = 0; i < NumEntries; ++i) {
6575 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6576 uint32_t Encoding = readNext<uint32_t>(Pos);
6578 outs() << " [" << i << "]: "
6579 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6581 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
6585 static void printCompressedSecondLevelUnwindPage(
6586 const char *PageStart, uint32_t FunctionBase,
6587 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6588 const char *Pos = PageStart;
6589 uint32_t Kind = readNext<uint32_t>(Pos);
6591 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6593 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6594 uint16_t NumEntries = readNext<uint16_t>(Pos);
6596 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6597 readNext<uint16_t>(Pos);
6598 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6599 PageStart + EncodingsStart);
6601 Pos = PageStart + EntriesStart;
6602 for (unsigned i = 0; i < NumEntries; ++i) {
6603 uint32_t Entry = readNext<uint32_t>(Pos);
6604 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6605 uint32_t EncodingIdx = Entry >> 24;
6608 if (EncodingIdx < CommonEncodings.size())
6609 Encoding = CommonEncodings[EncodingIdx];
6611 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6613 outs() << " [" << i << "]: "
6614 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6616 << "encoding[" << EncodingIdx
6617 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
6621 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6622 std::map<uint64_t, SymbolRef> &Symbols,
6623 const SectionRef &UnwindInfo) {
6625 assert(Obj->isLittleEndian() &&
6626 "There should not be a big-endian .o with __unwind_info");
6628 outs() << "Contents of __unwind_info section:\n";
6631 UnwindInfo.getContents(Contents);
6632 const char *Pos = Contents.data();
6634 //===----------------------------------
6636 //===----------------------------------
6638 uint32_t Version = readNext<uint32_t>(Pos);
6639 outs() << " Version: "
6640 << format("0x%" PRIx32, Version) << '\n';
6641 assert(Version == 1 && "only understand version 1");
6643 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6644 outs() << " Common encodings array section offset: "
6645 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6646 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6647 outs() << " Number of common encodings in array: "
6648 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6650 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6651 outs() << " Personality function array section offset: "
6652 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6653 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6654 outs() << " Number of personality functions in array: "
6655 << format("0x%" PRIx32, NumPersonalities) << '\n';
6657 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6658 outs() << " Index array section offset: "
6659 << format("0x%" PRIx32, IndicesStart) << '\n';
6660 uint32_t NumIndices = readNext<uint32_t>(Pos);
6661 outs() << " Number of indices in array: "
6662 << format("0x%" PRIx32, NumIndices) << '\n';
6664 //===----------------------------------
6665 // A shared list of common encodings
6666 //===----------------------------------
6668 // These occupy indices in the range [0, N] whenever an encoding is referenced
6669 // from a compressed 2nd level index table. In practice the linker only
6670 // creates ~128 of these, so that indices are available to embed encodings in
6671 // the 2nd level index.
6673 SmallVector<uint32_t, 64> CommonEncodings;
6674 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6675 Pos = Contents.data() + CommonEncodingsStart;
6676 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6677 uint32_t Encoding = readNext<uint32_t>(Pos);
6678 CommonEncodings.push_back(Encoding);
6680 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6684 //===----------------------------------
6685 // Personality functions used in this executable
6686 //===----------------------------------
6688 // There should be only a handful of these (one per source language,
6689 // roughly). Particularly since they only get 2 bits in the compact encoding.
6691 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6692 Pos = Contents.data() + PersonalitiesStart;
6693 for (unsigned i = 0; i < NumPersonalities; ++i) {
6694 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6695 outs() << " personality[" << i + 1
6696 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6699 //===----------------------------------
6700 // The level 1 index entries
6701 //===----------------------------------
6703 // These specify an approximate place to start searching for the more detailed
6704 // information, sorted by PC.
6707 uint32_t FunctionOffset;
6708 uint32_t SecondLevelPageStart;
6712 SmallVector<IndexEntry, 4> IndexEntries;
6714 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6715 Pos = Contents.data() + IndicesStart;
6716 for (unsigned i = 0; i < NumIndices; ++i) {
6719 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6720 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6721 Entry.LSDAStart = readNext<uint32_t>(Pos);
6722 IndexEntries.push_back(Entry);
6724 outs() << " [" << i << "]: "
6725 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6727 << "2nd level page offset="
6728 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
6729 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
6732 //===----------------------------------
6733 // Next come the LSDA tables
6734 //===----------------------------------
6736 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6737 // the first top-level index's LSDAOffset to the last (sentinel).
6739 outs() << " LSDA descriptors:\n";
6740 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6741 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6742 (2 * sizeof(uint32_t));
6743 for (int i = 0; i < NumLSDAs; ++i) {
6744 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6745 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6746 outs() << " [" << i << "]: "
6747 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6749 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
6752 //===----------------------------------
6753 // Finally, the 2nd level indices
6754 //===----------------------------------
6756 // Generally these are 4K in size, and have 2 possible forms:
6757 // + Regular stores up to 511 entries with disparate encodings
6758 // + Compressed stores up to 1021 entries if few enough compact encoding
6760 outs() << " Second level indices:\n";
6761 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6762 // The final sentinel top-level index has no associated 2nd level page
6763 if (IndexEntries[i].SecondLevelPageStart == 0)
6766 outs() << " Second level index[" << i << "]: "
6767 << "offset in section="
6768 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6770 << "base function offset="
6771 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6773 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
6774 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
6776 printRegularSecondLevelUnwindPage(Pos);
6778 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6781 llvm_unreachable("Do not know how to print this kind of 2nd level page");
6785 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6786 std::map<uint64_t, SymbolRef> Symbols;
6787 for (const SymbolRef &SymRef : Obj->symbols()) {
6788 // Discard any undefined or absolute symbols. They're not going to take part
6789 // in the convenience lookup for unwind info and just take up resources.
6790 section_iterator Section = *SymRef.getSection();
6791 if (Section == Obj->section_end())
6794 uint64_t Addr = SymRef.getValue();
6795 Symbols.insert(std::make_pair(Addr, SymRef));
6798 for (const SectionRef &Section : Obj->sections()) {
6800 Section.getName(SectName);
6801 if (SectName == "__compact_unwind")
6802 printMachOCompactUnwindSection(Obj, Symbols, Section);
6803 else if (SectName == "__unwind_info")
6804 printMachOUnwindInfoSection(Obj, Symbols, Section);
6805 else if (SectName == "__eh_frame")
6806 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
6810 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6811 uint32_t cpusubtype, uint32_t filetype,
6812 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6814 outs() << "Mach header\n";
6815 outs() << " magic cputype cpusubtype caps filetype ncmds "
6816 "sizeofcmds flags\n";
6818 if (magic == MachO::MH_MAGIC)
6819 outs() << " MH_MAGIC";
6820 else if (magic == MachO::MH_MAGIC_64)
6821 outs() << "MH_MAGIC_64";
6823 outs() << format(" 0x%08" PRIx32, magic);
6825 case MachO::CPU_TYPE_I386:
6827 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6828 case MachO::CPU_SUBTYPE_I386_ALL:
6832 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6836 case MachO::CPU_TYPE_X86_64:
6837 outs() << " X86_64";
6838 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6839 case MachO::CPU_SUBTYPE_X86_64_ALL:
6842 case MachO::CPU_SUBTYPE_X86_64_H:
6843 outs() << " Haswell";
6846 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6850 case MachO::CPU_TYPE_ARM:
6852 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6853 case MachO::CPU_SUBTYPE_ARM_ALL:
6856 case MachO::CPU_SUBTYPE_ARM_V4T:
6859 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6862 case MachO::CPU_SUBTYPE_ARM_XSCALE:
6863 outs() << " XSCALE";
6865 case MachO::CPU_SUBTYPE_ARM_V6:
6868 case MachO::CPU_SUBTYPE_ARM_V6M:
6871 case MachO::CPU_SUBTYPE_ARM_V7:
6874 case MachO::CPU_SUBTYPE_ARM_V7EM:
6877 case MachO::CPU_SUBTYPE_ARM_V7K:
6880 case MachO::CPU_SUBTYPE_ARM_V7M:
6883 case MachO::CPU_SUBTYPE_ARM_V7S:
6887 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6891 case MachO::CPU_TYPE_ARM64:
6893 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6894 case MachO::CPU_SUBTYPE_ARM64_ALL:
6898 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6902 case MachO::CPU_TYPE_POWERPC:
6904 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6905 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6909 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6913 case MachO::CPU_TYPE_POWERPC64:
6915 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6916 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6920 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6925 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
6928 outs() << format(" 0x%02" PRIx32,
6929 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
6932 case MachO::MH_OBJECT:
6933 outs() << " OBJECT";
6935 case MachO::MH_EXECUTE:
6936 outs() << " EXECUTE";
6938 case MachO::MH_FVMLIB:
6939 outs() << " FVMLIB";
6941 case MachO::MH_CORE:
6944 case MachO::MH_PRELOAD:
6945 outs() << " PRELOAD";
6947 case MachO::MH_DYLIB:
6950 case MachO::MH_DYLIB_STUB:
6951 outs() << " DYLIB_STUB";
6953 case MachO::MH_DYLINKER:
6954 outs() << " DYLINKER";
6956 case MachO::MH_BUNDLE:
6957 outs() << " BUNDLE";
6959 case MachO::MH_DSYM:
6962 case MachO::MH_KEXT_BUNDLE:
6963 outs() << " KEXTBUNDLE";
6966 outs() << format(" %10u", filetype);
6969 outs() << format(" %5u", ncmds);
6970 outs() << format(" %10u", sizeofcmds);
6972 if (f & MachO::MH_NOUNDEFS) {
6973 outs() << " NOUNDEFS";
6974 f &= ~MachO::MH_NOUNDEFS;
6976 if (f & MachO::MH_INCRLINK) {
6977 outs() << " INCRLINK";
6978 f &= ~MachO::MH_INCRLINK;
6980 if (f & MachO::MH_DYLDLINK) {
6981 outs() << " DYLDLINK";
6982 f &= ~MachO::MH_DYLDLINK;
6984 if (f & MachO::MH_BINDATLOAD) {
6985 outs() << " BINDATLOAD";
6986 f &= ~MachO::MH_BINDATLOAD;
6988 if (f & MachO::MH_PREBOUND) {
6989 outs() << " PREBOUND";
6990 f &= ~MachO::MH_PREBOUND;
6992 if (f & MachO::MH_SPLIT_SEGS) {
6993 outs() << " SPLIT_SEGS";
6994 f &= ~MachO::MH_SPLIT_SEGS;
6996 if (f & MachO::MH_LAZY_INIT) {
6997 outs() << " LAZY_INIT";
6998 f &= ~MachO::MH_LAZY_INIT;
7000 if (f & MachO::MH_TWOLEVEL) {
7001 outs() << " TWOLEVEL";
7002 f &= ~MachO::MH_TWOLEVEL;
7004 if (f & MachO::MH_FORCE_FLAT) {
7005 outs() << " FORCE_FLAT";
7006 f &= ~MachO::MH_FORCE_FLAT;
7008 if (f & MachO::MH_NOMULTIDEFS) {
7009 outs() << " NOMULTIDEFS";
7010 f &= ~MachO::MH_NOMULTIDEFS;
7012 if (f & MachO::MH_NOFIXPREBINDING) {
7013 outs() << " NOFIXPREBINDING";
7014 f &= ~MachO::MH_NOFIXPREBINDING;
7016 if (f & MachO::MH_PREBINDABLE) {
7017 outs() << " PREBINDABLE";
7018 f &= ~MachO::MH_PREBINDABLE;
7020 if (f & MachO::MH_ALLMODSBOUND) {
7021 outs() << " ALLMODSBOUND";
7022 f &= ~MachO::MH_ALLMODSBOUND;
7024 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7025 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7026 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7028 if (f & MachO::MH_CANONICAL) {
7029 outs() << " CANONICAL";
7030 f &= ~MachO::MH_CANONICAL;
7032 if (f & MachO::MH_WEAK_DEFINES) {
7033 outs() << " WEAK_DEFINES";
7034 f &= ~MachO::MH_WEAK_DEFINES;
7036 if (f & MachO::MH_BINDS_TO_WEAK) {
7037 outs() << " BINDS_TO_WEAK";
7038 f &= ~MachO::MH_BINDS_TO_WEAK;
7040 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7041 outs() << " ALLOW_STACK_EXECUTION";
7042 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7044 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7045 outs() << " DEAD_STRIPPABLE_DYLIB";
7046 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7048 if (f & MachO::MH_PIE) {
7050 f &= ~MachO::MH_PIE;
7052 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7053 outs() << " NO_REEXPORTED_DYLIBS";
7054 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7056 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7057 outs() << " MH_HAS_TLV_DESCRIPTORS";
7058 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7060 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7061 outs() << " MH_NO_HEAP_EXECUTION";
7062 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7064 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7065 outs() << " APP_EXTENSION_SAFE";
7066 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7068 if (f != 0 || flags == 0)
7069 outs() << format(" 0x%08" PRIx32, f);
7071 outs() << format(" 0x%08" PRIx32, magic);
7072 outs() << format(" %7d", cputype);
7073 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7074 outs() << format(" 0x%02" PRIx32,
7075 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7076 outs() << format(" %10u", filetype);
7077 outs() << format(" %5u", ncmds);
7078 outs() << format(" %10u", sizeofcmds);
7079 outs() << format(" 0x%08" PRIx32, flags);
7084 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7085 StringRef SegName, uint64_t vmaddr,
7086 uint64_t vmsize, uint64_t fileoff,
7087 uint64_t filesize, uint32_t maxprot,
7088 uint32_t initprot, uint32_t nsects,
7089 uint32_t flags, uint32_t object_size,
7091 uint64_t expected_cmdsize;
7092 if (cmd == MachO::LC_SEGMENT) {
7093 outs() << " cmd LC_SEGMENT\n";
7094 expected_cmdsize = nsects;
7095 expected_cmdsize *= sizeof(struct MachO::section);
7096 expected_cmdsize += sizeof(struct MachO::segment_command);
7098 outs() << " cmd LC_SEGMENT_64\n";
7099 expected_cmdsize = nsects;
7100 expected_cmdsize *= sizeof(struct MachO::section_64);
7101 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7103 outs() << " cmdsize " << cmdsize;
7104 if (cmdsize != expected_cmdsize)
7105 outs() << " Inconsistent size\n";
7108 outs() << " segname " << SegName << "\n";
7109 if (cmd == MachO::LC_SEGMENT_64) {
7110 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7111 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7113 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7114 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
7116 outs() << " fileoff " << fileoff;
7117 if (fileoff > object_size)
7118 outs() << " (past end of file)\n";
7121 outs() << " filesize " << filesize;
7122 if (fileoff + filesize > object_size)
7123 outs() << " (past end of file)\n";
7128 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7129 MachO::VM_PROT_EXECUTE)) != 0)
7130 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7132 outs() << " maxprot ";
7133 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7134 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7135 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7138 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7139 MachO::VM_PROT_EXECUTE)) != 0)
7140 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7142 outs() << " initprot ";
7143 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7144 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7145 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7148 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7149 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7151 outs() << " nsects " << nsects << "\n";
7155 outs() << " (none)\n";
7157 if (flags & MachO::SG_HIGHVM) {
7158 outs() << " HIGHVM";
7159 flags &= ~MachO::SG_HIGHVM;
7161 if (flags & MachO::SG_FVMLIB) {
7162 outs() << " FVMLIB";
7163 flags &= ~MachO::SG_FVMLIB;
7165 if (flags & MachO::SG_NORELOC) {
7166 outs() << " NORELOC";
7167 flags &= ~MachO::SG_NORELOC;
7169 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7170 outs() << " PROTECTED_VERSION_1";
7171 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7174 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7179 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7183 static void PrintSection(const char *sectname, const char *segname,
7184 uint64_t addr, uint64_t size, uint32_t offset,
7185 uint32_t align, uint32_t reloff, uint32_t nreloc,
7186 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7187 uint32_t cmd, const char *sg_segname,
7188 uint32_t filetype, uint32_t object_size,
7190 outs() << "Section\n";
7191 outs() << " sectname " << format("%.16s\n", sectname);
7192 outs() << " segname " << format("%.16s", segname);
7193 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7194 outs() << " (does not match segment)\n";
7197 if (cmd == MachO::LC_SEGMENT_64) {
7198 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7199 outs() << " size " << format("0x%016" PRIx64, size);
7201 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7202 outs() << " size " << format("0x%08" PRIx64, size);
7204 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7205 outs() << " (past end of file)\n";
7208 outs() << " offset " << offset;
7209 if (offset > object_size)
7210 outs() << " (past end of file)\n";
7213 uint32_t align_shifted = 1 << align;
7214 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7215 outs() << " reloff " << reloff;
7216 if (reloff > object_size)
7217 outs() << " (past end of file)\n";
7220 outs() << " nreloc " << nreloc;
7221 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7222 outs() << " (past end of file)\n";
7225 uint32_t section_type = flags & MachO::SECTION_TYPE;
7228 if (section_type == MachO::S_REGULAR)
7229 outs() << " S_REGULAR\n";
7230 else if (section_type == MachO::S_ZEROFILL)
7231 outs() << " S_ZEROFILL\n";
7232 else if (section_type == MachO::S_CSTRING_LITERALS)
7233 outs() << " S_CSTRING_LITERALS\n";
7234 else if (section_type == MachO::S_4BYTE_LITERALS)
7235 outs() << " S_4BYTE_LITERALS\n";
7236 else if (section_type == MachO::S_8BYTE_LITERALS)
7237 outs() << " S_8BYTE_LITERALS\n";
7238 else if (section_type == MachO::S_16BYTE_LITERALS)
7239 outs() << " S_16BYTE_LITERALS\n";
7240 else if (section_type == MachO::S_LITERAL_POINTERS)
7241 outs() << " S_LITERAL_POINTERS\n";
7242 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7243 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7244 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7245 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7246 else if (section_type == MachO::S_SYMBOL_STUBS)
7247 outs() << " S_SYMBOL_STUBS\n";
7248 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7249 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7250 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7251 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7252 else if (section_type == MachO::S_COALESCED)
7253 outs() << " S_COALESCED\n";
7254 else if (section_type == MachO::S_INTERPOSING)
7255 outs() << " S_INTERPOSING\n";
7256 else if (section_type == MachO::S_DTRACE_DOF)
7257 outs() << " S_DTRACE_DOF\n";
7258 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7259 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7260 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7261 outs() << " S_THREAD_LOCAL_REGULAR\n";
7262 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7263 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7264 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7265 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7266 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7267 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7268 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7269 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7271 outs() << format("0x%08" PRIx32, section_type) << "\n";
7272 outs() << "attributes";
7273 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7274 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7275 outs() << " PURE_INSTRUCTIONS";
7276 if (section_attributes & MachO::S_ATTR_NO_TOC)
7277 outs() << " NO_TOC";
7278 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7279 outs() << " STRIP_STATIC_SYMS";
7280 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7281 outs() << " NO_DEAD_STRIP";
7282 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7283 outs() << " LIVE_SUPPORT";
7284 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7285 outs() << " SELF_MODIFYING_CODE";
7286 if (section_attributes & MachO::S_ATTR_DEBUG)
7288 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7289 outs() << " SOME_INSTRUCTIONS";
7290 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7291 outs() << " EXT_RELOC";
7292 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7293 outs() << " LOC_RELOC";
7294 if (section_attributes == 0)
7295 outs() << " (none)";
7298 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7299 outs() << " reserved1 " << reserved1;
7300 if (section_type == MachO::S_SYMBOL_STUBS ||
7301 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7302 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7303 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7304 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7305 outs() << " (index into indirect symbol table)\n";
7308 outs() << " reserved2 " << reserved2;
7309 if (section_type == MachO::S_SYMBOL_STUBS)
7310 outs() << " (size of stubs)\n";
7315 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
7316 uint32_t object_size) {
7317 outs() << " cmd LC_SYMTAB\n";
7318 outs() << " cmdsize " << st.cmdsize;
7319 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7320 outs() << " Incorrect size\n";
7323 outs() << " symoff " << st.symoff;
7324 if (st.symoff > object_size)
7325 outs() << " (past end of file)\n";
7328 outs() << " nsyms " << st.nsyms;
7331 big_size = st.nsyms;
7332 big_size *= sizeof(struct MachO::nlist_64);
7333 big_size += st.symoff;
7334 if (big_size > object_size)
7335 outs() << " (past end of file)\n";
7339 big_size = st.nsyms;
7340 big_size *= sizeof(struct MachO::nlist);
7341 big_size += st.symoff;
7342 if (big_size > object_size)
7343 outs() << " (past end of file)\n";
7347 outs() << " stroff " << st.stroff;
7348 if (st.stroff > object_size)
7349 outs() << " (past end of file)\n";
7352 outs() << " strsize " << st.strsize;
7353 big_size = st.stroff;
7354 big_size += st.strsize;
7355 if (big_size > object_size)
7356 outs() << " (past end of file)\n";
7361 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7362 uint32_t nsyms, uint32_t object_size,
7364 outs() << " cmd LC_DYSYMTAB\n";
7365 outs() << " cmdsize " << dyst.cmdsize;
7366 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7367 outs() << " Incorrect size\n";
7370 outs() << " ilocalsym " << dyst.ilocalsym;
7371 if (dyst.ilocalsym > nsyms)
7372 outs() << " (greater than the number of symbols)\n";
7375 outs() << " nlocalsym " << dyst.nlocalsym;
7377 big_size = dyst.ilocalsym;
7378 big_size += dyst.nlocalsym;
7379 if (big_size > nsyms)
7380 outs() << " (past the end of the symbol table)\n";
7383 outs() << " iextdefsym " << dyst.iextdefsym;
7384 if (dyst.iextdefsym > nsyms)
7385 outs() << " (greater than the number of symbols)\n";
7388 outs() << " nextdefsym " << dyst.nextdefsym;
7389 big_size = dyst.iextdefsym;
7390 big_size += dyst.nextdefsym;
7391 if (big_size > nsyms)
7392 outs() << " (past the end of the symbol table)\n";
7395 outs() << " iundefsym " << dyst.iundefsym;
7396 if (dyst.iundefsym > nsyms)
7397 outs() << " (greater than the number of symbols)\n";
7400 outs() << " nundefsym " << dyst.nundefsym;
7401 big_size = dyst.iundefsym;
7402 big_size += dyst.nundefsym;
7403 if (big_size > nsyms)
7404 outs() << " (past the end of the symbol table)\n";
7407 outs() << " tocoff " << dyst.tocoff;
7408 if (dyst.tocoff > object_size)
7409 outs() << " (past end of file)\n";
7412 outs() << " ntoc " << dyst.ntoc;
7413 big_size = dyst.ntoc;
7414 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7415 big_size += dyst.tocoff;
7416 if (big_size > object_size)
7417 outs() << " (past end of file)\n";
7420 outs() << " modtaboff " << dyst.modtaboff;
7421 if (dyst.modtaboff > object_size)
7422 outs() << " (past end of file)\n";
7425 outs() << " nmodtab " << dyst.nmodtab;
7428 modtabend = dyst.nmodtab;
7429 modtabend *= sizeof(struct MachO::dylib_module_64);
7430 modtabend += dyst.modtaboff;
7432 modtabend = dyst.nmodtab;
7433 modtabend *= sizeof(struct MachO::dylib_module);
7434 modtabend += dyst.modtaboff;
7436 if (modtabend > object_size)
7437 outs() << " (past end of file)\n";
7440 outs() << " extrefsymoff " << dyst.extrefsymoff;
7441 if (dyst.extrefsymoff > object_size)
7442 outs() << " (past end of file)\n";
7445 outs() << " nextrefsyms " << dyst.nextrefsyms;
7446 big_size = dyst.nextrefsyms;
7447 big_size *= sizeof(struct MachO::dylib_reference);
7448 big_size += dyst.extrefsymoff;
7449 if (big_size > object_size)
7450 outs() << " (past end of file)\n";
7453 outs() << " indirectsymoff " << dyst.indirectsymoff;
7454 if (dyst.indirectsymoff > object_size)
7455 outs() << " (past end of file)\n";
7458 outs() << " nindirectsyms " << dyst.nindirectsyms;
7459 big_size = dyst.nindirectsyms;
7460 big_size *= sizeof(uint32_t);
7461 big_size += dyst.indirectsymoff;
7462 if (big_size > object_size)
7463 outs() << " (past end of file)\n";
7466 outs() << " extreloff " << dyst.extreloff;
7467 if (dyst.extreloff > object_size)
7468 outs() << " (past end of file)\n";
7471 outs() << " nextrel " << dyst.nextrel;
7472 big_size = dyst.nextrel;
7473 big_size *= sizeof(struct MachO::relocation_info);
7474 big_size += dyst.extreloff;
7475 if (big_size > object_size)
7476 outs() << " (past end of file)\n";
7479 outs() << " locreloff " << dyst.locreloff;
7480 if (dyst.locreloff > object_size)
7481 outs() << " (past end of file)\n";
7484 outs() << " nlocrel " << dyst.nlocrel;
7485 big_size = dyst.nlocrel;
7486 big_size *= sizeof(struct MachO::relocation_info);
7487 big_size += dyst.locreloff;
7488 if (big_size > object_size)
7489 outs() << " (past end of file)\n";
7494 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7495 uint32_t object_size) {
7496 if (dc.cmd == MachO::LC_DYLD_INFO)
7497 outs() << " cmd LC_DYLD_INFO\n";
7499 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7500 outs() << " cmdsize " << dc.cmdsize;
7501 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7502 outs() << " Incorrect size\n";
7505 outs() << " rebase_off " << dc.rebase_off;
7506 if (dc.rebase_off > object_size)
7507 outs() << " (past end of file)\n";
7510 outs() << " rebase_size " << dc.rebase_size;
7512 big_size = dc.rebase_off;
7513 big_size += dc.rebase_size;
7514 if (big_size > object_size)
7515 outs() << " (past end of file)\n";
7518 outs() << " bind_off " << dc.bind_off;
7519 if (dc.bind_off > object_size)
7520 outs() << " (past end of file)\n";
7523 outs() << " bind_size " << dc.bind_size;
7524 big_size = dc.bind_off;
7525 big_size += dc.bind_size;
7526 if (big_size > object_size)
7527 outs() << " (past end of file)\n";
7530 outs() << " weak_bind_off " << dc.weak_bind_off;
7531 if (dc.weak_bind_off > object_size)
7532 outs() << " (past end of file)\n";
7535 outs() << " weak_bind_size " << dc.weak_bind_size;
7536 big_size = dc.weak_bind_off;
7537 big_size += dc.weak_bind_size;
7538 if (big_size > object_size)
7539 outs() << " (past end of file)\n";
7542 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7543 if (dc.lazy_bind_off > object_size)
7544 outs() << " (past end of file)\n";
7547 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7548 big_size = dc.lazy_bind_off;
7549 big_size += dc.lazy_bind_size;
7550 if (big_size > object_size)
7551 outs() << " (past end of file)\n";
7554 outs() << " export_off " << dc.export_off;
7555 if (dc.export_off > object_size)
7556 outs() << " (past end of file)\n";
7559 outs() << " export_size " << dc.export_size;
7560 big_size = dc.export_off;
7561 big_size += dc.export_size;
7562 if (big_size > object_size)
7563 outs() << " (past end of file)\n";
7568 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7570 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7571 outs() << " cmd LC_ID_DYLINKER\n";
7572 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7573 outs() << " cmd LC_LOAD_DYLINKER\n";
7574 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7575 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7577 outs() << " cmd ?(" << dyld.cmd << ")\n";
7578 outs() << " cmdsize " << dyld.cmdsize;
7579 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7580 outs() << " Incorrect size\n";
7583 if (dyld.name >= dyld.cmdsize)
7584 outs() << " name ?(bad offset " << dyld.name << ")\n";
7586 const char *P = (const char *)(Ptr) + dyld.name;
7587 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7591 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7592 outs() << " cmd LC_UUID\n";
7593 outs() << " cmdsize " << uuid.cmdsize;
7594 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7595 outs() << " Incorrect size\n";
7599 for (int i = 0; i < 16; ++i) {
7600 outs() << format("%02" PRIX32, uuid.uuid[i]);
7601 if (i == 3 || i == 5 || i == 7 || i == 9)
7607 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
7608 outs() << " cmd LC_RPATH\n";
7609 outs() << " cmdsize " << rpath.cmdsize;
7610 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7611 outs() << " Incorrect size\n";
7614 if (rpath.path >= rpath.cmdsize)
7615 outs() << " path ?(bad offset " << rpath.path << ")\n";
7617 const char *P = (const char *)(Ptr) + rpath.path;
7618 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7622 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
7623 StringRef LoadCmdName;
7625 case MachO::LC_VERSION_MIN_MACOSX:
7626 LoadCmdName = "LC_VERSION_MIN_MACOSX";
7628 case MachO::LC_VERSION_MIN_IPHONEOS:
7629 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
7631 case MachO::LC_VERSION_MIN_TVOS:
7632 LoadCmdName = "LC_VERSION_MIN_TVOS";
7634 case MachO::LC_VERSION_MIN_WATCHOS:
7635 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
7638 llvm_unreachable("Unknown version min load command");
7641 outs() << " cmd " << LoadCmdName << '\n';
7642 outs() << " cmdsize " << vd.cmdsize;
7643 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7644 outs() << " Incorrect size\n";
7647 outs() << " version "
7648 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7649 << MachOObjectFile::getVersionMinMinor(vd, false);
7650 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7652 outs() << "." << Update;
7655 outs() << " sdk n/a";
7658 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7659 << MachOObjectFile::getVersionMinMinor(vd, true);
7661 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7663 outs() << "." << Update;
7667 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7668 outs() << " cmd LC_SOURCE_VERSION\n";
7669 outs() << " cmdsize " << sd.cmdsize;
7670 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7671 outs() << " Incorrect size\n";
7674 uint64_t a = (sd.version >> 40) & 0xffffff;
7675 uint64_t b = (sd.version >> 30) & 0x3ff;
7676 uint64_t c = (sd.version >> 20) & 0x3ff;
7677 uint64_t d = (sd.version >> 10) & 0x3ff;
7678 uint64_t e = sd.version & 0x3ff;
7679 outs() << " version " << a << "." << b;
7681 outs() << "." << c << "." << d << "." << e;
7683 outs() << "." << c << "." << d;
7689 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7690 outs() << " cmd LC_MAIN\n";
7691 outs() << " cmdsize " << ep.cmdsize;
7692 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7693 outs() << " Incorrect size\n";
7696 outs() << " entryoff " << ep.entryoff << "\n";
7697 outs() << " stacksize " << ep.stacksize << "\n";
7700 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7701 uint32_t object_size) {
7702 outs() << " cmd LC_ENCRYPTION_INFO\n";
7703 outs() << " cmdsize " << ec.cmdsize;
7704 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7705 outs() << " Incorrect size\n";
7708 outs() << " cryptoff " << ec.cryptoff;
7709 if (ec.cryptoff > object_size)
7710 outs() << " (past end of file)\n";
7713 outs() << " cryptsize " << ec.cryptsize;
7714 if (ec.cryptsize > object_size)
7715 outs() << " (past end of file)\n";
7718 outs() << " cryptid " << ec.cryptid << "\n";
7721 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
7722 uint32_t object_size) {
7723 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7724 outs() << " cmdsize " << ec.cmdsize;
7725 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7726 outs() << " Incorrect size\n";
7729 outs() << " cryptoff " << ec.cryptoff;
7730 if (ec.cryptoff > object_size)
7731 outs() << " (past end of file)\n";
7734 outs() << " cryptsize " << ec.cryptsize;
7735 if (ec.cryptsize > object_size)
7736 outs() << " (past end of file)\n";
7739 outs() << " cryptid " << ec.cryptid << "\n";
7740 outs() << " pad " << ec.pad << "\n";
7743 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7745 outs() << " cmd LC_LINKER_OPTION\n";
7746 outs() << " cmdsize " << lo.cmdsize;
7747 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7748 outs() << " Incorrect size\n";
7751 outs() << " count " << lo.count << "\n";
7752 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7753 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7756 while (*string == '\0' && left > 0) {
7762 outs() << " string #" << i << " " << format("%.*s\n", left, string);
7763 uint32_t NullPos = StringRef(string, left).find('\0');
7764 uint32_t len = std::min(NullPos, left) + 1;
7770 outs() << " count " << lo.count << " does not match number of strings "
7774 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7776 outs() << " cmd LC_SUB_FRAMEWORK\n";
7777 outs() << " cmdsize " << sub.cmdsize;
7778 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7779 outs() << " Incorrect size\n";
7782 if (sub.umbrella < sub.cmdsize) {
7783 const char *P = Ptr + sub.umbrella;
7784 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7786 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7790 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7792 outs() << " cmd LC_SUB_UMBRELLA\n";
7793 outs() << " cmdsize " << sub.cmdsize;
7794 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7795 outs() << " Incorrect size\n";
7798 if (sub.sub_umbrella < sub.cmdsize) {
7799 const char *P = Ptr + sub.sub_umbrella;
7800 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7802 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7806 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
7808 outs() << " cmd LC_SUB_LIBRARY\n";
7809 outs() << " cmdsize " << sub.cmdsize;
7810 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7811 outs() << " Incorrect size\n";
7814 if (sub.sub_library < sub.cmdsize) {
7815 const char *P = Ptr + sub.sub_library;
7816 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7818 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7822 static void PrintSubClientCommand(MachO::sub_client_command sub,
7824 outs() << " cmd LC_SUB_CLIENT\n";
7825 outs() << " cmdsize " << sub.cmdsize;
7826 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7827 outs() << " Incorrect size\n";
7830 if (sub.client < sub.cmdsize) {
7831 const char *P = Ptr + sub.client;
7832 outs() << " client " << P << " (offset " << sub.client << ")\n";
7834 outs() << " client ?(bad offset " << sub.client << ")\n";
7838 static void PrintRoutinesCommand(MachO::routines_command r) {
7839 outs() << " cmd LC_ROUTINES\n";
7840 outs() << " cmdsize " << r.cmdsize;
7841 if (r.cmdsize != sizeof(struct MachO::routines_command))
7842 outs() << " Incorrect size\n";
7845 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7846 outs() << " init_module " << r.init_module << "\n";
7847 outs() << " reserved1 " << r.reserved1 << "\n";
7848 outs() << " reserved2 " << r.reserved2 << "\n";
7849 outs() << " reserved3 " << r.reserved3 << "\n";
7850 outs() << " reserved4 " << r.reserved4 << "\n";
7851 outs() << " reserved5 " << r.reserved5 << "\n";
7852 outs() << " reserved6 " << r.reserved6 << "\n";
7855 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7856 outs() << " cmd LC_ROUTINES_64\n";
7857 outs() << " cmdsize " << r.cmdsize;
7858 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
7859 outs() << " Incorrect size\n";
7862 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
7863 outs() << " init_module " << r.init_module << "\n";
7864 outs() << " reserved1 " << r.reserved1 << "\n";
7865 outs() << " reserved2 " << r.reserved2 << "\n";
7866 outs() << " reserved3 " << r.reserved3 << "\n";
7867 outs() << " reserved4 " << r.reserved4 << "\n";
7868 outs() << " reserved5 " << r.reserved5 << "\n";
7869 outs() << " reserved6 " << r.reserved6 << "\n";
7872 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
7873 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
7874 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
7875 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
7876 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
7877 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
7878 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
7879 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
7880 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
7881 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
7882 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
7883 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
7884 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
7885 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
7886 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
7887 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
7888 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
7889 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
7890 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
7891 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
7892 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
7893 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
7896 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
7898 outs() << "\t mmst_reg ";
7899 for (f = 0; f < 10; f++)
7900 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
7902 outs() << "\t mmst_rsrv ";
7903 for (f = 0; f < 6; f++)
7904 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
7908 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
7910 outs() << "\t xmm_reg ";
7911 for (f = 0; f < 16; f++)
7912 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
7916 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
7917 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
7918 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
7919 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
7920 outs() << " denorm " << fpu.fpu_fcw.denorm;
7921 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
7922 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
7923 outs() << " undfl " << fpu.fpu_fcw.undfl;
7924 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
7925 outs() << "\t\t pc ";
7926 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
7927 outs() << "FP_PREC_24B ";
7928 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
7929 outs() << "FP_PREC_53B ";
7930 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
7931 outs() << "FP_PREC_64B ";
7933 outs() << fpu.fpu_fcw.pc << " ";
7935 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
7936 outs() << "FP_RND_NEAR ";
7937 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
7938 outs() << "FP_RND_DOWN ";
7939 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
7940 outs() << "FP_RND_UP ";
7941 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
7942 outs() << "FP_CHOP ";
7944 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
7945 outs() << " denorm " << fpu.fpu_fsw.denorm;
7946 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
7947 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
7948 outs() << " undfl " << fpu.fpu_fsw.undfl;
7949 outs() << " precis " << fpu.fpu_fsw.precis;
7950 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
7951 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
7952 outs() << " c0 " << fpu.fpu_fsw.c0;
7953 outs() << " c1 " << fpu.fpu_fsw.c1;
7954 outs() << " c2 " << fpu.fpu_fsw.c2;
7955 outs() << " tos " << fpu.fpu_fsw.tos;
7956 outs() << " c3 " << fpu.fpu_fsw.c3;
7957 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
7958 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
7959 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
7960 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
7961 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
7962 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
7963 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
7964 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
7965 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
7966 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
7967 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
7968 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
7970 outs() << "\t fpu_stmm0:\n";
7971 Print_mmst_reg(fpu.fpu_stmm0);
7972 outs() << "\t fpu_stmm1:\n";
7973 Print_mmst_reg(fpu.fpu_stmm1);
7974 outs() << "\t fpu_stmm2:\n";
7975 Print_mmst_reg(fpu.fpu_stmm2);
7976 outs() << "\t fpu_stmm3:\n";
7977 Print_mmst_reg(fpu.fpu_stmm3);
7978 outs() << "\t fpu_stmm4:\n";
7979 Print_mmst_reg(fpu.fpu_stmm4);
7980 outs() << "\t fpu_stmm5:\n";
7981 Print_mmst_reg(fpu.fpu_stmm5);
7982 outs() << "\t fpu_stmm6:\n";
7983 Print_mmst_reg(fpu.fpu_stmm6);
7984 outs() << "\t fpu_stmm7:\n";
7985 Print_mmst_reg(fpu.fpu_stmm7);
7986 outs() << "\t fpu_xmm0:\n";
7987 Print_xmm_reg(fpu.fpu_xmm0);
7988 outs() << "\t fpu_xmm1:\n";
7989 Print_xmm_reg(fpu.fpu_xmm1);
7990 outs() << "\t fpu_xmm2:\n";
7991 Print_xmm_reg(fpu.fpu_xmm2);
7992 outs() << "\t fpu_xmm3:\n";
7993 Print_xmm_reg(fpu.fpu_xmm3);
7994 outs() << "\t fpu_xmm4:\n";
7995 Print_xmm_reg(fpu.fpu_xmm4);
7996 outs() << "\t fpu_xmm5:\n";
7997 Print_xmm_reg(fpu.fpu_xmm5);
7998 outs() << "\t fpu_xmm6:\n";
7999 Print_xmm_reg(fpu.fpu_xmm6);
8000 outs() << "\t fpu_xmm7:\n";
8001 Print_xmm_reg(fpu.fpu_xmm7);
8002 outs() << "\t fpu_xmm8:\n";
8003 Print_xmm_reg(fpu.fpu_xmm8);
8004 outs() << "\t fpu_xmm9:\n";
8005 Print_xmm_reg(fpu.fpu_xmm9);
8006 outs() << "\t fpu_xmm10:\n";
8007 Print_xmm_reg(fpu.fpu_xmm10);
8008 outs() << "\t fpu_xmm11:\n";
8009 Print_xmm_reg(fpu.fpu_xmm11);
8010 outs() << "\t fpu_xmm12:\n";
8011 Print_xmm_reg(fpu.fpu_xmm12);
8012 outs() << "\t fpu_xmm13:\n";
8013 Print_xmm_reg(fpu.fpu_xmm13);
8014 outs() << "\t fpu_xmm14:\n";
8015 Print_xmm_reg(fpu.fpu_xmm14);
8016 outs() << "\t fpu_xmm15:\n";
8017 Print_xmm_reg(fpu.fpu_xmm15);
8018 outs() << "\t fpu_rsrv4:\n";
8019 for (uint32_t f = 0; f < 6; f++) {
8021 for (uint32_t g = 0; g < 16; g++)
8022 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
8025 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8029 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8030 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8031 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8032 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8035 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8036 bool isLittleEndian, uint32_t cputype) {
8037 if (t.cmd == MachO::LC_THREAD)
8038 outs() << " cmd LC_THREAD\n";
8039 else if (t.cmd == MachO::LC_UNIXTHREAD)
8040 outs() << " cmd LC_UNIXTHREAD\n";
8042 outs() << " cmd " << t.cmd << " (unknown)\n";
8043 outs() << " cmdsize " << t.cmdsize;
8044 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8045 outs() << " Incorrect size\n";
8049 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8050 const char *end = Ptr + t.cmdsize;
8051 uint32_t flavor, count, left;
8052 if (cputype == MachO::CPU_TYPE_X86_64) {
8053 while (begin < end) {
8054 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8055 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8056 begin += sizeof(uint32_t);
8061 if (isLittleEndian != sys::IsLittleEndianHost)
8062 sys::swapByteOrder(flavor);
8063 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8064 memcpy((char *)&count, begin, sizeof(uint32_t));
8065 begin += sizeof(uint32_t);
8070 if (isLittleEndian != sys::IsLittleEndianHost)
8071 sys::swapByteOrder(count);
8072 if (flavor == MachO::x86_THREAD_STATE64) {
8073 outs() << " flavor x86_THREAD_STATE64\n";
8074 if (count == MachO::x86_THREAD_STATE64_COUNT)
8075 outs() << " count x86_THREAD_STATE64_COUNT\n";
8077 outs() << " count " << count
8078 << " (not x86_THREAD_STATE64_COUNT)\n";
8079 MachO::x86_thread_state64_t cpu64;
8081 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8082 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8083 begin += sizeof(MachO::x86_thread_state64_t);
8085 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8086 memcpy(&cpu64, begin, left);
8089 if (isLittleEndian != sys::IsLittleEndianHost)
8091 Print_x86_thread_state64_t(cpu64);
8092 } else if (flavor == MachO::x86_THREAD_STATE) {
8093 outs() << " flavor x86_THREAD_STATE\n";
8094 if (count == MachO::x86_THREAD_STATE_COUNT)
8095 outs() << " count x86_THREAD_STATE_COUNT\n";
8097 outs() << " count " << count
8098 << " (not x86_THREAD_STATE_COUNT)\n";
8099 struct MachO::x86_thread_state_t ts;
8101 if (left >= sizeof(MachO::x86_thread_state_t)) {
8102 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8103 begin += sizeof(MachO::x86_thread_state_t);
8105 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8106 memcpy(&ts, begin, left);
8109 if (isLittleEndian != sys::IsLittleEndianHost)
8111 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8112 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8113 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8114 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8116 outs() << "tsh.count " << ts.tsh.count
8117 << " (not x86_THREAD_STATE64_COUNT\n";
8118 Print_x86_thread_state64_t(ts.uts.ts64);
8120 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8121 << ts.tsh.count << "\n";
8123 } else if (flavor == MachO::x86_FLOAT_STATE) {
8124 outs() << " flavor x86_FLOAT_STATE\n";
8125 if (count == MachO::x86_FLOAT_STATE_COUNT)
8126 outs() << " count x86_FLOAT_STATE_COUNT\n";
8128 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
8129 struct MachO::x86_float_state_t fs;
8131 if (left >= sizeof(MachO::x86_float_state_t)) {
8132 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8133 begin += sizeof(MachO::x86_float_state_t);
8135 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8136 memcpy(&fs, begin, left);
8139 if (isLittleEndian != sys::IsLittleEndianHost)
8141 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8142 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
8143 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
8144 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8146 outs() << "fsh.count " << fs.fsh.count
8147 << " (not x86_FLOAT_STATE64_COUNT\n";
8148 Print_x86_float_state_t(fs.ufs.fs64);
8150 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8151 << fs.fsh.count << "\n";
8153 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8154 outs() << " flavor x86_EXCEPTION_STATE\n";
8155 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8156 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8158 outs() << " count " << count
8159 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8160 struct MachO::x86_exception_state_t es;
8162 if (left >= sizeof(MachO::x86_exception_state_t)) {
8163 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8164 begin += sizeof(MachO::x86_exception_state_t);
8166 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8167 memcpy(&es, begin, left);
8170 if (isLittleEndian != sys::IsLittleEndianHost)
8172 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8173 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
8174 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
8175 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8177 outs() << "\t esh.count " << es.esh.count
8178 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8179 Print_x86_exception_state_t(es.ues.es64);
8181 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8182 << es.esh.count << "\n";
8185 outs() << " flavor " << flavor << " (unknown)\n";
8186 outs() << " count " << count << "\n";
8187 outs() << " state (unknown)\n";
8188 begin += count * sizeof(uint32_t);
8192 while (begin < end) {
8193 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8194 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8195 begin += sizeof(uint32_t);
8200 if (isLittleEndian != sys::IsLittleEndianHost)
8201 sys::swapByteOrder(flavor);
8202 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8203 memcpy((char *)&count, begin, sizeof(uint32_t));
8204 begin += sizeof(uint32_t);
8209 if (isLittleEndian != sys::IsLittleEndianHost)
8210 sys::swapByteOrder(count);
8211 outs() << " flavor " << flavor << "\n";
8212 outs() << " count " << count << "\n";
8213 outs() << " state (Unknown cputype/cpusubtype)\n";
8214 begin += count * sizeof(uint32_t);
8219 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8220 if (dl.cmd == MachO::LC_ID_DYLIB)
8221 outs() << " cmd LC_ID_DYLIB\n";
8222 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8223 outs() << " cmd LC_LOAD_DYLIB\n";
8224 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8225 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8226 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8227 outs() << " cmd LC_REEXPORT_DYLIB\n";
8228 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8229 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8230 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8231 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8233 outs() << " cmd " << dl.cmd << " (unknown)\n";
8234 outs() << " cmdsize " << dl.cmdsize;
8235 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8236 outs() << " Incorrect size\n";
8239 if (dl.dylib.name < dl.cmdsize) {
8240 const char *P = (const char *)(Ptr) + dl.dylib.name;
8241 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8243 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8245 outs() << " time stamp " << dl.dylib.timestamp << " ";
8246 time_t t = dl.dylib.timestamp;
8247 outs() << ctime(&t);
8248 outs() << " current version ";
8249 if (dl.dylib.current_version == 0xffffffff)
8252 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8253 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8254 << (dl.dylib.current_version & 0xff) << "\n";
8255 outs() << "compatibility version ";
8256 if (dl.dylib.compatibility_version == 0xffffffff)
8259 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8260 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8261 << (dl.dylib.compatibility_version & 0xff) << "\n";
8264 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8265 uint32_t object_size) {
8266 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8267 outs() << " cmd LC_FUNCTION_STARTS\n";
8268 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8269 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8270 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8271 outs() << " cmd LC_FUNCTION_STARTS\n";
8272 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8273 outs() << " cmd LC_DATA_IN_CODE\n";
8274 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8275 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8276 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8277 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8279 outs() << " cmd " << ld.cmd << " (?)\n";
8280 outs() << " cmdsize " << ld.cmdsize;
8281 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8282 outs() << " Incorrect size\n";
8285 outs() << " dataoff " << ld.dataoff;
8286 if (ld.dataoff > object_size)
8287 outs() << " (past end of file)\n";
8290 outs() << " datasize " << ld.datasize;
8291 uint64_t big_size = ld.dataoff;
8292 big_size += ld.datasize;
8293 if (big_size > object_size)
8294 outs() << " (past end of file)\n";
8299 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8300 uint32_t cputype, bool verbose) {
8301 StringRef Buf = Obj->getData();
8303 for (const auto &Command : Obj->load_commands()) {
8304 outs() << "Load command " << Index++ << "\n";
8305 if (Command.C.cmd == MachO::LC_SEGMENT) {
8306 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8307 const char *sg_segname = SLC.segname;
8308 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8309 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8310 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8312 for (unsigned j = 0; j < SLC.nsects; j++) {
8313 MachO::section S = Obj->getSection(Command, j);
8314 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8315 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8316 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8318 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8319 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8320 const char *sg_segname = SLC_64.segname;
8321 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8322 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8323 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8324 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8325 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8326 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8327 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8328 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8329 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8330 sg_segname, filetype, Buf.size(), verbose);
8332 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8333 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8334 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
8335 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8336 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8337 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8338 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8340 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8341 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8342 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8343 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8344 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8345 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8346 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8347 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8348 PrintDyldLoadCommand(Dyld, Command.Ptr);
8349 } else if (Command.C.cmd == MachO::LC_UUID) {
8350 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8351 PrintUuidLoadCommand(Uuid);
8352 } else if (Command.C.cmd == MachO::LC_RPATH) {
8353 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8354 PrintRpathLoadCommand(Rpath, Command.Ptr);
8355 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
8356 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8357 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8358 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
8359 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8360 PrintVersionMinLoadCommand(Vd);
8361 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8362 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8363 PrintSourceVersionCommand(Sd);
8364 } else if (Command.C.cmd == MachO::LC_MAIN) {
8365 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8366 PrintEntryPointCommand(Ep);
8367 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
8368 MachO::encryption_info_command Ei =
8369 Obj->getEncryptionInfoCommand(Command);
8370 PrintEncryptionInfoCommand(Ei, Buf.size());
8371 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
8372 MachO::encryption_info_command_64 Ei =
8373 Obj->getEncryptionInfoCommand64(Command);
8374 PrintEncryptionInfoCommand64(Ei, Buf.size());
8375 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
8376 MachO::linker_option_command Lo =
8377 Obj->getLinkerOptionLoadCommand(Command);
8378 PrintLinkerOptionCommand(Lo, Command.Ptr);
8379 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8380 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8381 PrintSubFrameworkCommand(Sf, Command.Ptr);
8382 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8383 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8384 PrintSubUmbrellaCommand(Sf, Command.Ptr);
8385 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8386 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8387 PrintSubLibraryCommand(Sl, Command.Ptr);
8388 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8389 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8390 PrintSubClientCommand(Sc, Command.Ptr);
8391 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8392 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8393 PrintRoutinesCommand(Rc);
8394 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8395 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8396 PrintRoutinesCommand64(Rc);
8397 } else if (Command.C.cmd == MachO::LC_THREAD ||
8398 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8399 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8400 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
8401 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8402 Command.C.cmd == MachO::LC_ID_DYLIB ||
8403 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8404 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8405 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8406 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
8407 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8408 PrintDylibCommand(Dl, Command.Ptr);
8409 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8410 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8411 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8412 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8413 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8414 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8415 MachO::linkedit_data_command Ld =
8416 Obj->getLinkeditDataLoadCommand(Command);
8417 PrintLinkEditDataCommand(Ld, Buf.size());
8419 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8421 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8422 // TODO: get and print the raw bytes of the load command.
8424 // TODO: print all the other kinds of load commands.
8428 static void getAndPrintMachHeader(const MachOObjectFile *Obj,
8429 uint32_t &filetype, uint32_t &cputype,
8431 if (Obj->is64Bit()) {
8432 MachO::mach_header_64 H_64;
8433 H_64 = Obj->getHeader64();
8434 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8435 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8436 filetype = H_64.filetype;
8437 cputype = H_64.cputype;
8439 MachO::mach_header H;
8440 H = Obj->getHeader();
8441 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8442 H.sizeofcmds, H.flags, verbose);
8443 filetype = H.filetype;
8444 cputype = H.cputype;
8448 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8449 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
8450 uint32_t filetype = 0;
8451 uint32_t cputype = 0;
8452 getAndPrintMachHeader(file, filetype, cputype, !NonVerbose);
8453 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
8456 //===----------------------------------------------------------------------===//
8457 // export trie dumping
8458 //===----------------------------------------------------------------------===//
8460 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
8461 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8462 uint64_t Flags = Entry.flags();
8463 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8464 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8465 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8466 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8467 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8468 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8469 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8471 outs() << "[re-export] ";
8473 outs() << format("0x%08llX ",
8474 Entry.address()); // FIXME:add in base address
8475 outs() << Entry.name();
8476 if (WeakDef || ThreadLocal || Resolver || Abs) {
8477 bool NeedsComma = false;
8480 outs() << "weak_def";
8486 outs() << "per-thread";
8492 outs() << "absolute";
8498 outs() << format("resolver=0x%08llX", Entry.other());
8504 StringRef DylibName = "unknown";
8505 int Ordinal = Entry.other() - 1;
8506 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8507 if (Entry.otherName().empty())
8508 outs() << " (from " << DylibName << ")";
8510 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
8516 //===----------------------------------------------------------------------===//
8517 // rebase table dumping
8518 //===----------------------------------------------------------------------===//
8523 SegInfo(const object::MachOObjectFile *Obj);
8525 StringRef segmentName(uint32_t SegIndex);
8526 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8527 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
8528 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
8531 struct SectionInfo {
8534 StringRef SectionName;
8535 StringRef SegmentName;
8536 uint64_t OffsetInSegment;
8537 uint64_t SegmentStartAddress;
8538 uint32_t SegmentIndex;
8540 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8541 SmallVector<SectionInfo, 32> Sections;
8545 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8546 // Build table of sections so segIndex/offset pairs can be translated.
8547 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
8548 StringRef CurSegName;
8549 uint64_t CurSegAddress;
8550 for (const SectionRef &Section : Obj->sections()) {
8552 error(Section.getName(Info.SectionName));
8553 Info.Address = Section.getAddress();
8554 Info.Size = Section.getSize();
8556 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8557 if (!Info.SegmentName.equals(CurSegName)) {
8559 CurSegName = Info.SegmentName;
8560 CurSegAddress = Info.Address;
8562 Info.SegmentIndex = CurSegIndex - 1;
8563 Info.OffsetInSegment = Info.Address - CurSegAddress;
8564 Info.SegmentStartAddress = CurSegAddress;
8565 Sections.push_back(Info);
8569 StringRef SegInfo::segmentName(uint32_t SegIndex) {
8570 for (const SectionInfo &SI : Sections) {
8571 if (SI.SegmentIndex == SegIndex)
8572 return SI.SegmentName;
8574 llvm_unreachable("invalid segIndex");
8577 bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
8578 uint64_t OffsetInSeg) {
8579 for (const SectionInfo &SI : Sections) {
8580 if (SI.SegmentIndex != SegIndex)
8582 if (SI.OffsetInSegment > OffsetInSeg)
8584 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8591 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8592 uint64_t OffsetInSeg) {
8593 for (const SectionInfo &SI : Sections) {
8594 if (SI.SegmentIndex != SegIndex)
8596 if (SI.OffsetInSegment > OffsetInSeg)
8598 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8602 llvm_unreachable("segIndex and offset not in any section");
8605 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8606 return findSection(SegIndex, OffsetInSeg).SectionName;
8609 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8610 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8611 return SI.SegmentStartAddress + OffsetInSeg;
8614 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8615 // Build table of sections so names can used in final output.
8616 SegInfo sectionTable(Obj);
8618 outs() << "segment section address type\n";
8619 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8620 uint32_t SegIndex = Entry.segmentIndex();
8621 uint64_t OffsetInSeg = Entry.segmentOffset();
8622 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8623 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8624 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8626 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
8627 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8628 SegmentName.str().c_str(), SectionName.str().c_str(),
8629 Address, Entry.typeName().str().c_str());
8633 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8634 StringRef DylibName;
8636 case MachO::BIND_SPECIAL_DYLIB_SELF:
8637 return "this-image";
8638 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8639 return "main-executable";
8640 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8641 return "flat-namespace";
8644 std::error_code EC =
8645 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
8647 return "<<bad library ordinal>>";
8651 return "<<unknown special ordinal>>";
8654 //===----------------------------------------------------------------------===//
8655 // bind table dumping
8656 //===----------------------------------------------------------------------===//
8658 void llvm::printMachOBindTable(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 type "
8663 "addend dylib symbol\n";
8664 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
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 pointer 0 libSystem ___stack_chk_guard
8674 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
8675 Attr = " (weak_import)";
8676 outs() << left_justify(SegmentName, 8) << " "
8677 << left_justify(SectionName, 18) << " "
8678 << format_hex(Address, 10, true) << " "
8679 << left_justify(Entry.typeName(), 8) << " "
8680 << format_decimal(Entry.addend(), 8) << " "
8681 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8682 << Entry.symbolName() << Attr << "\n";
8686 //===----------------------------------------------------------------------===//
8687 // lazy bind table dumping
8688 //===----------------------------------------------------------------------===//
8690 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8691 // Build table of sections so names can used in final output.
8692 SegInfo sectionTable(Obj);
8694 outs() << "segment section address "
8696 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8697 uint32_t SegIndex = Entry.segmentIndex();
8698 uint64_t OffsetInSeg = Entry.segmentOffset();
8699 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8700 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8701 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8703 // Table lines look like:
8704 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
8705 outs() << left_justify(SegmentName, 8) << " "
8706 << left_justify(SectionName, 18) << " "
8707 << format_hex(Address, 10, true) << " "
8708 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8709 << Entry.symbolName() << "\n";
8713 //===----------------------------------------------------------------------===//
8714 // weak bind table dumping
8715 //===----------------------------------------------------------------------===//
8717 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8718 // Build table of sections so names can used in final output.
8719 SegInfo sectionTable(Obj);
8721 outs() << "segment section address "
8722 "type addend symbol\n";
8723 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8724 // Strong symbols don't have a location to update.
8725 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
8726 outs() << " strong "
8727 << Entry.symbolName() << "\n";
8730 uint32_t SegIndex = Entry.segmentIndex();
8731 uint64_t OffsetInSeg = Entry.segmentOffset();
8732 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8733 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8734 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8736 // Table lines look like:
8737 // __DATA __data 0x00001000 pointer 0 _foo
8738 outs() << left_justify(SegmentName, 8) << " "
8739 << left_justify(SectionName, 18) << " "
8740 << format_hex(Address, 10, true) << " "
8741 << left_justify(Entry.typeName(), 8) << " "
8742 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8747 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
8748 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8749 // information for that address. If the address is found its binding symbol
8750 // name is returned. If not nullptr is returned.
8751 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8752 struct DisassembleInfo *info) {
8753 if (info->bindtable == nullptr) {
8754 info->bindtable = new (BindTable);
8755 SegInfo sectionTable(info->O);
8756 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8757 uint32_t SegIndex = Entry.segmentIndex();
8758 uint64_t OffsetInSeg = Entry.segmentOffset();
8759 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8761 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8762 const char *SymbolName = nullptr;
8763 StringRef name = Entry.symbolName();
8765 SymbolName = name.data();
8766 info->bindtable->push_back(std::make_pair(Address, SymbolName));
8769 for (bind_table_iterator BI = info->bindtable->begin(),
8770 BE = info->bindtable->end();
8772 uint64_t Address = BI->first;
8773 if (ReferenceValue == Address) {
8774 const char *SymbolName = BI->second;