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"),
136 bool ArchAll = false;
138 static std::string ThumbTripleName;
140 static const Target *GetTarget(const MachOObjectFile *MachOObj,
141 const char **McpuDefault,
142 const Target **ThumbTarget) {
143 // Figure out the target triple.
144 if (TripleName.empty()) {
145 llvm::Triple TT("unknown-unknown-unknown");
146 llvm::Triple ThumbTriple = Triple();
147 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
148 TripleName = TT.str();
149 ThumbTripleName = ThumbTriple.str();
152 // Get the target specific parser.
154 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
155 if (TheTarget && ThumbTripleName.empty())
158 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
162 errs() << "llvm-objdump: error: unable to get target for '";
164 errs() << TripleName;
166 errs() << ThumbTripleName;
167 errs() << "', see --version and --triple.\n";
171 struct SymbolSorter {
172 bool operator()(const SymbolRef &A, const SymbolRef &B) {
173 uint64_t AAddr = (A.getType() != SymbolRef::ST_Function) ? 0 : A.getValue();
174 uint64_t BAddr = (B.getType() != SymbolRef::ST_Function) ? 0 : B.getValue();
175 return AAddr < BAddr;
179 // Types for the storted data in code table that is built before disassembly
180 // and the predicate function to sort them.
181 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
182 typedef std::vector<DiceTableEntry> DiceTable;
183 typedef DiceTable::iterator dice_table_iterator;
185 // This is used to search for a data in code table entry for the PC being
186 // disassembled. The j parameter has the PC in j.first. A single data in code
187 // table entry can cover many bytes for each of its Kind's. So if the offset,
188 // aka the i.first value, of the data in code table entry plus its Length
189 // covers the PC being searched for this will return true. If not it will
191 static bool compareDiceTableEntries(const DiceTableEntry &i,
192 const DiceTableEntry &j) {
194 i.second.getLength(Length);
196 return j.first >= i.first && j.first < i.first + Length;
199 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
200 unsigned short Kind) {
201 uint32_t Value, Size = 1;
205 case MachO::DICE_KIND_DATA:
208 dumpBytes(ArrayRef<uint8_t>(bytes, 4), outs());
209 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
210 outs() << "\t.long " << Value;
212 } else if (Length >= 2) {
214 dumpBytes(ArrayRef<uint8_t>(bytes, 2), outs());
215 Value = bytes[1] << 8 | bytes[0];
216 outs() << "\t.short " << Value;
220 dumpBytes(ArrayRef<uint8_t>(bytes, 2), outs());
222 outs() << "\t.byte " << Value;
225 if (Kind == MachO::DICE_KIND_DATA)
226 outs() << "\t@ KIND_DATA\n";
228 outs() << "\t@ data in code kind = " << Kind << "\n";
230 case MachO::DICE_KIND_JUMP_TABLE8:
232 dumpBytes(ArrayRef<uint8_t>(bytes, 1), outs());
234 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
237 case MachO::DICE_KIND_JUMP_TABLE16:
239 dumpBytes(ArrayRef<uint8_t>(bytes, 2), outs());
240 Value = bytes[1] << 8 | bytes[0];
241 outs() << "\t.short " << format("%5u", Value & 0xffff)
242 << "\t@ KIND_JUMP_TABLE16\n";
245 case MachO::DICE_KIND_JUMP_TABLE32:
246 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
248 dumpBytes(ArrayRef<uint8_t>(bytes, 4), outs());
249 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
250 outs() << "\t.long " << Value;
251 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
252 outs() << "\t@ KIND_JUMP_TABLE32\n";
254 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
261 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
262 std::vector<SectionRef> &Sections,
263 std::vector<SymbolRef> &Symbols,
264 SmallVectorImpl<uint64_t> &FoundFns,
265 uint64_t &BaseSegmentAddress) {
266 for (const SymbolRef &Symbol : MachOObj->symbols()) {
267 ErrorOr<StringRef> SymName = Symbol.getName();
268 if (std::error_code EC = SymName.getError())
269 report_fatal_error(EC.message());
270 if (!SymName->startswith("ltmp"))
271 Symbols.push_back(Symbol);
274 for (const SectionRef &Section : MachOObj->sections()) {
276 Section.getName(SectName);
277 Sections.push_back(Section);
280 bool BaseSegmentAddressSet = false;
281 for (const auto &Command : MachOObj->load_commands()) {
282 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
283 // We found a function starts segment, parse the addresses for later
285 MachO::linkedit_data_command LLC =
286 MachOObj->getLinkeditDataLoadCommand(Command);
288 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
289 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
290 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
291 StringRef SegName = SLC.segname;
292 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
293 BaseSegmentAddressSet = true;
294 BaseSegmentAddress = SLC.vmaddr;
300 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
301 uint32_t n, uint32_t count,
302 uint32_t stride, uint64_t addr) {
303 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
304 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
305 if (n > nindirectsyms)
306 outs() << " (entries start past the end of the indirect symbol "
307 "table) (reserved1 field greater than the table size)";
308 else if (n + count > nindirectsyms)
309 outs() << " (entries extends past the end of the indirect symbol "
312 uint32_t cputype = O->getHeader().cputype;
313 if (cputype & MachO::CPU_ARCH_ABI64)
314 outs() << "address index";
316 outs() << "address index";
321 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
322 if (cputype & MachO::CPU_ARCH_ABI64)
323 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
325 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
326 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
327 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
328 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
332 if (indirect_symbol ==
333 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
334 outs() << "LOCAL ABSOLUTE\n";
337 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
338 outs() << "ABSOLUTE\n";
341 outs() << format("%5u ", indirect_symbol);
343 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
344 if (indirect_symbol < Symtab.nsyms) {
345 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
346 SymbolRef Symbol = *Sym;
347 ErrorOr<StringRef> SymName = Symbol.getName();
348 if (std::error_code EC = SymName.getError())
349 report_fatal_error(EC.message());
359 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
360 for (const auto &Load : O->load_commands()) {
361 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
362 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
363 for (unsigned J = 0; J < Seg.nsects; ++J) {
364 MachO::section_64 Sec = O->getSection64(Load, J);
365 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
366 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
367 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
368 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
369 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
370 section_type == MachO::S_SYMBOL_STUBS) {
372 if (section_type == MachO::S_SYMBOL_STUBS)
373 stride = Sec.reserved2;
377 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
378 << Sec.sectname << ") "
379 << "(size of stubs in reserved2 field is zero)\n";
382 uint32_t count = Sec.size / stride;
383 outs() << "Indirect symbols for (" << Sec.segname << ","
384 << Sec.sectname << ") " << count << " entries";
385 uint32_t n = Sec.reserved1;
386 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
389 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
390 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
391 for (unsigned J = 0; J < Seg.nsects; ++J) {
392 MachO::section Sec = O->getSection(Load, J);
393 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
394 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
395 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
396 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
397 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
398 section_type == MachO::S_SYMBOL_STUBS) {
400 if (section_type == MachO::S_SYMBOL_STUBS)
401 stride = Sec.reserved2;
405 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
406 << Sec.sectname << ") "
407 << "(size of stubs in reserved2 field is zero)\n";
410 uint32_t count = Sec.size / stride;
411 outs() << "Indirect symbols for (" << Sec.segname << ","
412 << Sec.sectname << ") " << count << " entries";
413 uint32_t n = Sec.reserved1;
414 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
421 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
422 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
423 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
424 outs() << "Data in code table (" << nentries << " entries)\n";
425 outs() << "offset length kind\n";
426 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
429 DI->getOffset(Offset);
430 outs() << format("0x%08" PRIx32, Offset) << " ";
432 DI->getLength(Length);
433 outs() << format("%6u", Length) << " ";
438 case MachO::DICE_KIND_DATA:
441 case MachO::DICE_KIND_JUMP_TABLE8:
442 outs() << "JUMP_TABLE8";
444 case MachO::DICE_KIND_JUMP_TABLE16:
445 outs() << "JUMP_TABLE16";
447 case MachO::DICE_KIND_JUMP_TABLE32:
448 outs() << "JUMP_TABLE32";
450 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
451 outs() << "ABS_JUMP_TABLE32";
454 outs() << format("0x%04" PRIx32, Kind);
458 outs() << format("0x%04" PRIx32, Kind);
463 static void PrintLinkOptHints(MachOObjectFile *O) {
464 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
465 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
466 uint32_t nloh = LohLC.datasize;
467 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
468 for (uint32_t i = 0; i < nloh;) {
470 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
472 outs() << " identifier " << identifier << " ";
475 switch (identifier) {
477 outs() << "AdrpAdrp\n";
480 outs() << "AdrpLdr\n";
483 outs() << "AdrpAddLdr\n";
486 outs() << "AdrpLdrGotLdr\n";
489 outs() << "AdrpAddStr\n";
492 outs() << "AdrpLdrGotStr\n";
495 outs() << "AdrpAdd\n";
498 outs() << "AdrpLdrGot\n";
501 outs() << "Unknown identifier value\n";
504 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
506 outs() << " narguments " << narguments << "\n";
510 for (uint32_t j = 0; j < narguments; j++) {
511 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
513 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
520 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
522 for (const auto &Load : O->load_commands()) {
523 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
524 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
525 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
526 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
527 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
528 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
529 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
530 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
531 if (dl.dylib.name < dl.cmdsize) {
532 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
537 outs() << " (compatibility version "
538 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
539 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
540 << (dl.dylib.compatibility_version & 0xff) << ",";
541 outs() << " current version "
542 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
543 << ((dl.dylib.current_version >> 8) & 0xff) << "."
544 << (dl.dylib.current_version & 0xff) << ")\n";
547 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
548 if (Load.C.cmd == MachO::LC_ID_DYLIB)
549 outs() << "LC_ID_DYLIB ";
550 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
551 outs() << "LC_LOAD_DYLIB ";
552 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
553 outs() << "LC_LOAD_WEAK_DYLIB ";
554 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
555 outs() << "LC_LAZY_LOAD_DYLIB ";
556 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
557 outs() << "LC_REEXPORT_DYLIB ";
558 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
559 outs() << "LC_LOAD_UPWARD_DYLIB ";
562 outs() << "command " << Index++ << "\n";
568 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
570 static void CreateSymbolAddressMap(MachOObjectFile *O,
571 SymbolAddressMap *AddrMap) {
572 // Create a map of symbol addresses to symbol names.
573 for (const SymbolRef &Symbol : O->symbols()) {
574 SymbolRef::Type ST = Symbol.getType();
575 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
576 ST == SymbolRef::ST_Other) {
577 uint64_t Address = Symbol.getValue();
578 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
579 if (std::error_code EC = SymNameOrErr.getError())
580 report_fatal_error(EC.message());
581 StringRef SymName = *SymNameOrErr;
582 if (!SymName.startswith(".objc"))
583 (*AddrMap)[Address] = SymName;
588 // GuessSymbolName is passed the address of what might be a symbol and a
589 // pointer to the SymbolAddressMap. It returns the name of a symbol
590 // with that address or nullptr if no symbol is found with that address.
591 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
592 const char *SymbolName = nullptr;
593 // A DenseMap can't lookup up some values.
594 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
595 StringRef name = AddrMap->lookup(value);
597 SymbolName = name.data();
602 static void DumpCstringChar(const char c) {
606 outs().write_escaped(p);
609 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
610 uint32_t sect_size, uint64_t sect_addr,
611 bool print_addresses) {
612 for (uint32_t i = 0; i < sect_size; i++) {
613 if (print_addresses) {
615 outs() << format("%016" PRIx64, sect_addr + i) << " ";
617 outs() << format("%08" PRIx64, sect_addr + i) << " ";
619 for (; i < sect_size && sect[i] != '\0'; i++)
620 DumpCstringChar(sect[i]);
621 if (i < sect_size && sect[i] == '\0')
626 static void DumpLiteral4(uint32_t l, float f) {
627 outs() << format("0x%08" PRIx32, l);
628 if ((l & 0x7f800000) != 0x7f800000)
629 outs() << format(" (%.16e)\n", f);
632 outs() << " (+Infinity)\n";
633 else if (l == 0xff800000)
634 outs() << " (-Infinity)\n";
635 else if ((l & 0x00400000) == 0x00400000)
636 outs() << " (non-signaling Not-a-Number)\n";
638 outs() << " (signaling Not-a-Number)\n";
642 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
643 uint32_t sect_size, uint64_t sect_addr,
644 bool print_addresses) {
645 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
646 if (print_addresses) {
648 outs() << format("%016" PRIx64, sect_addr + i) << " ";
650 outs() << format("%08" PRIx64, sect_addr + i) << " ";
653 memcpy(&f, sect + i, sizeof(float));
654 if (O->isLittleEndian() != sys::IsLittleEndianHost)
655 sys::swapByteOrder(f);
657 memcpy(&l, sect + i, sizeof(uint32_t));
658 if (O->isLittleEndian() != sys::IsLittleEndianHost)
659 sys::swapByteOrder(l);
664 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
666 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
668 if (O->isLittleEndian()) {
675 // Hi is the high word, so this is equivalent to if(isfinite(d))
676 if ((Hi & 0x7ff00000) != 0x7ff00000)
677 outs() << format(" (%.16e)\n", d);
679 if (Hi == 0x7ff00000 && Lo == 0)
680 outs() << " (+Infinity)\n";
681 else if (Hi == 0xfff00000 && Lo == 0)
682 outs() << " (-Infinity)\n";
683 else if ((Hi & 0x00080000) == 0x00080000)
684 outs() << " (non-signaling Not-a-Number)\n";
686 outs() << " (signaling Not-a-Number)\n";
690 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
691 uint32_t sect_size, uint64_t sect_addr,
692 bool print_addresses) {
693 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
694 if (print_addresses) {
696 outs() << format("%016" PRIx64, sect_addr + i) << " ";
698 outs() << format("%08" PRIx64, sect_addr + i) << " ";
701 memcpy(&d, sect + i, sizeof(double));
702 if (O->isLittleEndian() != sys::IsLittleEndianHost)
703 sys::swapByteOrder(d);
705 memcpy(&l0, sect + i, sizeof(uint32_t));
706 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
707 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
708 sys::swapByteOrder(l0);
709 sys::swapByteOrder(l1);
711 DumpLiteral8(O, l0, l1, d);
715 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
716 outs() << format("0x%08" PRIx32, l0) << " ";
717 outs() << format("0x%08" PRIx32, l1) << " ";
718 outs() << format("0x%08" PRIx32, l2) << " ";
719 outs() << format("0x%08" PRIx32, l3) << "\n";
722 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
723 uint32_t sect_size, uint64_t sect_addr,
724 bool print_addresses) {
725 for (uint32_t i = 0; i < sect_size; i += 16) {
726 if (print_addresses) {
728 outs() << format("%016" PRIx64, sect_addr + i) << " ";
730 outs() << format("%08" PRIx64, sect_addr + i) << " ";
732 uint32_t l0, l1, l2, l3;
733 memcpy(&l0, sect + i, sizeof(uint32_t));
734 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
735 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
736 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
737 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
738 sys::swapByteOrder(l0);
739 sys::swapByteOrder(l1);
740 sys::swapByteOrder(l2);
741 sys::swapByteOrder(l3);
743 DumpLiteral16(l0, l1, l2, l3);
747 static void DumpLiteralPointerSection(MachOObjectFile *O,
748 const SectionRef &Section,
749 const char *sect, uint32_t sect_size,
751 bool print_addresses) {
752 // Collect the literal sections in this Mach-O file.
753 std::vector<SectionRef> LiteralSections;
754 for (const SectionRef &Section : O->sections()) {
755 DataRefImpl Ref = Section.getRawDataRefImpl();
756 uint32_t section_type;
758 const MachO::section_64 Sec = O->getSection64(Ref);
759 section_type = Sec.flags & MachO::SECTION_TYPE;
761 const MachO::section Sec = O->getSection(Ref);
762 section_type = Sec.flags & MachO::SECTION_TYPE;
764 if (section_type == MachO::S_CSTRING_LITERALS ||
765 section_type == MachO::S_4BYTE_LITERALS ||
766 section_type == MachO::S_8BYTE_LITERALS ||
767 section_type == MachO::S_16BYTE_LITERALS)
768 LiteralSections.push_back(Section);
771 // Set the size of the literal pointer.
772 uint32_t lp_size = O->is64Bit() ? 8 : 4;
774 // Collect the external relocation symbols for the literal pointers.
775 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
776 for (const RelocationRef &Reloc : Section.relocations()) {
778 MachO::any_relocation_info RE;
779 bool isExtern = false;
780 Rel = Reloc.getRawDataRefImpl();
781 RE = O->getRelocation(Rel);
782 isExtern = O->getPlainRelocationExternal(RE);
784 uint64_t RelocOffset = Reloc.getOffset();
785 symbol_iterator RelocSym = Reloc.getSymbol();
786 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
789 array_pod_sort(Relocs.begin(), Relocs.end());
791 // Dump each literal pointer.
792 for (uint32_t i = 0; i < sect_size; i += lp_size) {
793 if (print_addresses) {
795 outs() << format("%016" PRIx64, sect_addr + i) << " ";
797 outs() << format("%08" PRIx64, sect_addr + i) << " ";
801 memcpy(&lp, sect + i, sizeof(uint64_t));
802 if (O->isLittleEndian() != sys::IsLittleEndianHost)
803 sys::swapByteOrder(lp);
806 memcpy(&li, sect + i, sizeof(uint32_t));
807 if (O->isLittleEndian() != sys::IsLittleEndianHost)
808 sys::swapByteOrder(li);
812 // First look for an external relocation entry for this literal pointer.
813 auto Reloc = std::find_if(
814 Relocs.begin(), Relocs.end(),
815 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
816 if (Reloc != Relocs.end()) {
817 symbol_iterator RelocSym = Reloc->second;
818 ErrorOr<StringRef> SymName = RelocSym->getName();
819 if (std::error_code EC = SymName.getError())
820 report_fatal_error(EC.message());
821 outs() << "external relocation entry for symbol:" << *SymName << "\n";
825 // For local references see what the section the literal pointer points to.
826 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
827 [&](const SectionRef &R) {
828 return lp >= R.getAddress() &&
829 lp < R.getAddress() + R.getSize();
831 if (Sect == LiteralSections.end()) {
832 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
836 uint64_t SectAddress = Sect->getAddress();
837 uint64_t SectSize = Sect->getSize();
840 Sect->getName(SectName);
841 DataRefImpl Ref = Sect->getRawDataRefImpl();
842 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
843 outs() << SegmentName << ":" << SectName << ":";
845 uint32_t section_type;
847 const MachO::section_64 Sec = O->getSection64(Ref);
848 section_type = Sec.flags & MachO::SECTION_TYPE;
850 const MachO::section Sec = O->getSection(Ref);
851 section_type = Sec.flags & MachO::SECTION_TYPE;
855 Sect->getContents(BytesStr);
856 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
858 switch (section_type) {
859 case MachO::S_CSTRING_LITERALS:
860 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
862 DumpCstringChar(Contents[i]);
866 case MachO::S_4BYTE_LITERALS:
868 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
870 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
871 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
872 sys::swapByteOrder(f);
873 sys::swapByteOrder(l);
877 case MachO::S_8BYTE_LITERALS: {
879 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
881 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
882 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
884 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
885 sys::swapByteOrder(f);
886 sys::swapByteOrder(l0);
887 sys::swapByteOrder(l1);
889 DumpLiteral8(O, l0, l1, d);
892 case MachO::S_16BYTE_LITERALS: {
893 uint32_t l0, l1, l2, l3;
894 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
895 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
897 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
899 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
901 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
902 sys::swapByteOrder(l0);
903 sys::swapByteOrder(l1);
904 sys::swapByteOrder(l2);
905 sys::swapByteOrder(l3);
907 DumpLiteral16(l0, l1, l2, l3);
914 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
915 uint32_t sect_size, uint64_t sect_addr,
916 SymbolAddressMap *AddrMap,
920 stride = sizeof(uint64_t);
922 stride = sizeof(uint32_t);
923 for (uint32_t i = 0; i < sect_size; i += stride) {
924 const char *SymbolName = nullptr;
926 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
927 uint64_t pointer_value;
928 memcpy(&pointer_value, sect + i, stride);
929 if (O->isLittleEndian() != sys::IsLittleEndianHost)
930 sys::swapByteOrder(pointer_value);
931 outs() << format("0x%016" PRIx64, pointer_value);
933 SymbolName = GuessSymbolName(pointer_value, AddrMap);
935 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
936 uint32_t pointer_value;
937 memcpy(&pointer_value, sect + i, stride);
938 if (O->isLittleEndian() != sys::IsLittleEndianHost)
939 sys::swapByteOrder(pointer_value);
940 outs() << format("0x%08" PRIx32, pointer_value);
942 SymbolName = GuessSymbolName(pointer_value, AddrMap);
945 outs() << " " << SymbolName;
950 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
951 uint32_t size, uint64_t addr) {
952 uint32_t cputype = O->getHeader().cputype;
953 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
955 for (uint32_t i = 0; i < size; i += j, addr += j) {
957 outs() << format("%016" PRIx64, addr) << "\t";
959 outs() << format("%08" PRIx64, addr) << "\t";
960 for (j = 0; j < 16 && i + j < size; j++) {
961 uint8_t byte_word = *(sect + i + j);
962 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
968 for (uint32_t i = 0; i < size; i += j, addr += j) {
970 outs() << format("%016" PRIx64, addr) << "\t";
972 outs() << format("%08" PRIx64, sect) << "\t";
973 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
974 j += sizeof(int32_t)) {
975 if (i + j + sizeof(int32_t) < size) {
977 memcpy(&long_word, sect + i + j, sizeof(int32_t));
978 if (O->isLittleEndian() != sys::IsLittleEndianHost)
979 sys::swapByteOrder(long_word);
980 outs() << format("%08" PRIx32, long_word) << " ";
982 for (uint32_t k = 0; i + j + k < size; k++) {
983 uint8_t byte_word = *(sect + i + j);
984 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
993 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
994 StringRef DisSegName, StringRef DisSectName);
995 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
996 uint32_t size, uint32_t addr);
998 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1000 SymbolAddressMap AddrMap;
1002 CreateSymbolAddressMap(O, &AddrMap);
1004 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1005 StringRef DumpSection = FilterSections[i];
1006 std::pair<StringRef, StringRef> DumpSegSectName;
1007 DumpSegSectName = DumpSection.split(',');
1008 StringRef DumpSegName, DumpSectName;
1009 if (DumpSegSectName.second.size()) {
1010 DumpSegName = DumpSegSectName.first;
1011 DumpSectName = DumpSegSectName.second;
1014 DumpSectName = DumpSegSectName.first;
1016 for (const SectionRef &Section : O->sections()) {
1018 Section.getName(SectName);
1019 DataRefImpl Ref = Section.getRawDataRefImpl();
1020 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1021 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1022 (SectName == DumpSectName)) {
1024 uint32_t section_flags;
1026 const MachO::section_64 Sec = O->getSection64(Ref);
1027 section_flags = Sec.flags;
1030 const MachO::section Sec = O->getSection(Ref);
1031 section_flags = Sec.flags;
1033 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1036 Section.getContents(BytesStr);
1037 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1038 uint32_t sect_size = BytesStr.size();
1039 uint64_t sect_addr = Section.getAddress();
1041 outs() << "Contents of (" << SegName << "," << SectName
1045 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1046 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1047 DisassembleMachO(Filename, O, SegName, SectName);
1050 if (SegName == "__TEXT" && SectName == "__info_plist") {
1054 if (SegName == "__OBJC" && SectName == "__protocol") {
1055 DumpProtocolSection(O, sect, sect_size, sect_addr);
1058 switch (section_type) {
1059 case MachO::S_REGULAR:
1060 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1062 case MachO::S_ZEROFILL:
1063 outs() << "zerofill section and has no contents in the file\n";
1065 case MachO::S_CSTRING_LITERALS:
1066 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1068 case MachO::S_4BYTE_LITERALS:
1069 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1071 case MachO::S_8BYTE_LITERALS:
1072 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1074 case MachO::S_16BYTE_LITERALS:
1075 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1077 case MachO::S_LITERAL_POINTERS:
1078 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1081 case MachO::S_MOD_INIT_FUNC_POINTERS:
1082 case MachO::S_MOD_TERM_FUNC_POINTERS:
1083 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1087 outs() << "Unknown section type ("
1088 << format("0x%08" PRIx32, section_type) << ")\n";
1089 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1093 if (section_type == MachO::S_ZEROFILL)
1094 outs() << "zerofill section and has no contents in the file\n";
1096 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1103 static void DumpInfoPlistSectionContents(StringRef Filename,
1104 MachOObjectFile *O) {
1105 for (const SectionRef &Section : O->sections()) {
1107 Section.getName(SectName);
1108 DataRefImpl Ref = Section.getRawDataRefImpl();
1109 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1110 if (SegName == "__TEXT" && SectName == "__info_plist") {
1111 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1113 Section.getContents(BytesStr);
1114 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1121 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1122 // and if it is and there is a list of architecture flags is specified then
1123 // check to make sure this Mach-O file is one of those architectures or all
1124 // architectures were specified. If not then an error is generated and this
1125 // routine returns false. Else it returns true.
1126 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1127 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1128 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1129 bool ArchFound = false;
1130 MachO::mach_header H;
1131 MachO::mach_header_64 H_64;
1133 if (MachO->is64Bit()) {
1134 H_64 = MachO->MachOObjectFile::getHeader64();
1135 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1137 H = MachO->MachOObjectFile::getHeader();
1138 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1141 for (i = 0; i < ArchFlags.size(); ++i) {
1142 if (ArchFlags[i] == T.getArchName())
1147 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1148 << "architecture: " + ArchFlags[i] + "\n";
1155 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1157 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1158 // archive member and or in a slice of a universal file. It prints the
1159 // the file name and header info and then processes it according to the
1160 // command line options.
1161 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1162 StringRef ArchiveMemberName = StringRef(),
1163 StringRef ArchitectureName = StringRef()) {
1164 // If we are doing some processing here on the Mach-O file print the header
1165 // info. And don't print it otherwise like in the case of printing the
1166 // UniversalHeaders or ArchiveHeaders.
1167 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
1168 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1169 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
1171 if (!ArchiveMemberName.empty())
1172 outs() << '(' << ArchiveMemberName << ')';
1173 if (!ArchitectureName.empty())
1174 outs() << " (architecture " << ArchitectureName << ")";
1179 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1180 if (IndirectSymbols)
1181 PrintIndirectSymbols(MachOOF, !NonVerbose);
1183 PrintDataInCodeTable(MachOOF, !NonVerbose);
1185 PrintLinkOptHints(MachOOF);
1187 PrintRelocations(MachOOF);
1189 PrintSectionHeaders(MachOOF);
1190 if (SectionContents)
1191 PrintSectionContents(MachOOF);
1192 if (FilterSections.size() != 0)
1193 DumpSectionContents(Filename, MachOOF, !NonVerbose);
1195 DumpInfoPlistSectionContents(Filename, MachOOF);
1197 PrintDylibs(MachOOF, false);
1199 PrintDylibs(MachOOF, true);
1201 PrintSymbolTable(MachOOF);
1203 printMachOUnwindInfo(MachOOF);
1205 printMachOFileHeader(MachOOF);
1207 printObjcMetaData(MachOOF, !NonVerbose);
1209 printExportsTrie(MachOOF);
1211 printRebaseTable(MachOOF);
1213 printBindTable(MachOOF);
1215 printLazyBindTable(MachOOF);
1217 printWeakBindTable(MachOOF);
1220 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1221 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1222 outs() << " cputype (" << cputype << ")\n";
1223 outs() << " cpusubtype (" << cpusubtype << ")\n";
1226 // printCPUType() helps print_fat_headers by printing the cputype and
1227 // pusubtype (symbolically for the one's it knows about).
1228 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1230 case MachO::CPU_TYPE_I386:
1231 switch (cpusubtype) {
1232 case MachO::CPU_SUBTYPE_I386_ALL:
1233 outs() << " cputype CPU_TYPE_I386\n";
1234 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1237 printUnknownCPUType(cputype, cpusubtype);
1241 case MachO::CPU_TYPE_X86_64:
1242 switch (cpusubtype) {
1243 case MachO::CPU_SUBTYPE_X86_64_ALL:
1244 outs() << " cputype CPU_TYPE_X86_64\n";
1245 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1247 case MachO::CPU_SUBTYPE_X86_64_H:
1248 outs() << " cputype CPU_TYPE_X86_64\n";
1249 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1252 printUnknownCPUType(cputype, cpusubtype);
1256 case MachO::CPU_TYPE_ARM:
1257 switch (cpusubtype) {
1258 case MachO::CPU_SUBTYPE_ARM_ALL:
1259 outs() << " cputype CPU_TYPE_ARM\n";
1260 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1262 case MachO::CPU_SUBTYPE_ARM_V4T:
1263 outs() << " cputype CPU_TYPE_ARM\n";
1264 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1266 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1267 outs() << " cputype CPU_TYPE_ARM\n";
1268 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1270 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1271 outs() << " cputype CPU_TYPE_ARM\n";
1272 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1274 case MachO::CPU_SUBTYPE_ARM_V6:
1275 outs() << " cputype CPU_TYPE_ARM\n";
1276 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1278 case MachO::CPU_SUBTYPE_ARM_V6M:
1279 outs() << " cputype CPU_TYPE_ARM\n";
1280 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1282 case MachO::CPU_SUBTYPE_ARM_V7:
1283 outs() << " cputype CPU_TYPE_ARM\n";
1284 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1286 case MachO::CPU_SUBTYPE_ARM_V7EM:
1287 outs() << " cputype CPU_TYPE_ARM\n";
1288 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1290 case MachO::CPU_SUBTYPE_ARM_V7K:
1291 outs() << " cputype CPU_TYPE_ARM\n";
1292 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1294 case MachO::CPU_SUBTYPE_ARM_V7M:
1295 outs() << " cputype CPU_TYPE_ARM\n";
1296 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1298 case MachO::CPU_SUBTYPE_ARM_V7S:
1299 outs() << " cputype CPU_TYPE_ARM\n";
1300 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1303 printUnknownCPUType(cputype, cpusubtype);
1307 case MachO::CPU_TYPE_ARM64:
1308 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1309 case MachO::CPU_SUBTYPE_ARM64_ALL:
1310 outs() << " cputype CPU_TYPE_ARM64\n";
1311 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1314 printUnknownCPUType(cputype, cpusubtype);
1319 printUnknownCPUType(cputype, cpusubtype);
1324 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1326 outs() << "Fat headers\n";
1328 outs() << "fat_magic FAT_MAGIC\n";
1330 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1332 uint32_t nfat_arch = UB->getNumberOfObjects();
1333 StringRef Buf = UB->getData();
1334 uint64_t size = Buf.size();
1335 uint64_t big_size = sizeof(struct MachO::fat_header) +
1336 nfat_arch * sizeof(struct MachO::fat_arch);
1337 outs() << "nfat_arch " << UB->getNumberOfObjects();
1339 outs() << " (malformed, contains zero architecture types)\n";
1340 else if (big_size > size)
1341 outs() << " (malformed, architectures past end of file)\n";
1345 for (uint32_t i = 0; i < nfat_arch; ++i) {
1346 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1347 uint32_t cputype = OFA.getCPUType();
1348 uint32_t cpusubtype = OFA.getCPUSubType();
1349 outs() << "architecture ";
1350 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1351 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1352 uint32_t other_cputype = other_OFA.getCPUType();
1353 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1354 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1355 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1356 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1357 outs() << "(illegal duplicate architecture) ";
1362 outs() << OFA.getArchTypeName() << "\n";
1363 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1365 outs() << i << "\n";
1366 outs() << " cputype " << cputype << "\n";
1367 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1371 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1372 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1374 outs() << " capabilities "
1375 << format("0x%" PRIx32,
1376 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1377 outs() << " offset " << OFA.getOffset();
1378 if (OFA.getOffset() > size)
1379 outs() << " (past end of file)";
1380 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1381 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1383 outs() << " size " << OFA.getSize();
1384 big_size = OFA.getOffset() + OFA.getSize();
1385 if (big_size > size)
1386 outs() << " (past end of file)";
1388 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1393 static void printArchiveChild(Archive::Child &C, bool verbose,
1394 bool print_offset) {
1396 outs() << C.getChildOffset() << "\t";
1397 sys::fs::perms Mode = C.getAccessMode();
1399 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1400 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1402 if (Mode & sys::fs::owner_read)
1406 if (Mode & sys::fs::owner_write)
1410 if (Mode & sys::fs::owner_exe)
1414 if (Mode & sys::fs::group_read)
1418 if (Mode & sys::fs::group_write)
1422 if (Mode & sys::fs::group_exe)
1426 if (Mode & sys::fs::others_read)
1430 if (Mode & sys::fs::others_write)
1434 if (Mode & sys::fs::others_exe)
1439 outs() << format("0%o ", Mode);
1442 unsigned UID = C.getUID();
1443 outs() << format("%3d/", UID);
1444 unsigned GID = C.getGID();
1445 outs() << format("%-3d ", GID);
1446 uint64_t Size = C.getRawSize();
1447 outs() << format("%5" PRId64, Size) << " ";
1449 StringRef RawLastModified = C.getRawLastModified();
1452 if (RawLastModified.getAsInteger(10, Seconds))
1453 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1455 // Since cime(3) returns a 26 character string of the form:
1456 // "Sun Sep 16 01:03:52 1973\n\0"
1457 // just print 24 characters.
1459 outs() << format("%.24s ", ctime(&t));
1462 outs() << RawLastModified << " ";
1466 ErrorOr<StringRef> NameOrErr = C.getName();
1467 if (NameOrErr.getError()) {
1468 StringRef RawName = C.getRawName();
1469 outs() << RawName << "\n";
1471 StringRef Name = NameOrErr.get();
1472 outs() << Name << "\n";
1475 StringRef RawName = C.getRawName();
1476 outs() << RawName << "\n";
1480 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1481 if (A->hasSymbolTable()) {
1482 Archive::child_iterator S = A->getSymbolTableChild();
1483 Archive::Child C = *S;
1484 printArchiveChild(C, verbose, print_offset);
1486 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1488 Archive::Child C = *I;
1489 printArchiveChild(C, verbose, print_offset);
1493 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1494 // -arch flags selecting just those slices as specified by them and also parses
1495 // archive files. Then for each individual Mach-O file ProcessMachO() is
1496 // called to process the file based on the command line options.
1497 void llvm::ParseInputMachO(StringRef Filename) {
1498 // Check for -arch all and verifiy the -arch flags are valid.
1499 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1500 if (ArchFlags[i] == "all") {
1503 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1504 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1505 "'for the -arch option\n";
1511 // Attempt to open the binary.
1512 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1513 if (std::error_code EC = BinaryOrErr.getError()) {
1514 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
1517 Binary &Bin = *BinaryOrErr.get().getBinary();
1519 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1520 outs() << "Archive : " << Filename << "\n";
1522 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
1523 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1525 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1526 if (ChildOrErr.getError())
1528 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1529 if (!checkMachOAndArchFlags(O, Filename))
1531 ProcessMachO(Filename, O, O->getFileName());
1536 if (UniversalHeaders) {
1537 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1538 printMachOUniversalHeaders(UB, !NonVerbose);
1540 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1541 // If we have a list of architecture flags specified dump only those.
1542 if (!ArchAll && ArchFlags.size() != 0) {
1543 // Look for a slice in the universal binary that matches each ArchFlag.
1545 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1547 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1548 E = UB->end_objects();
1550 if (ArchFlags[i] == I->getArchTypeName()) {
1552 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1553 I->getAsObjectFile();
1554 std::string ArchitectureName = "";
1555 if (ArchFlags.size() > 1)
1556 ArchitectureName = I->getArchTypeName();
1558 ObjectFile &O = *ObjOrErr.get();
1559 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1560 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1561 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1562 I->getAsArchive()) {
1563 std::unique_ptr<Archive> &A = *AOrErr;
1564 outs() << "Archive : " << Filename;
1565 if (!ArchitectureName.empty())
1566 outs() << " (architecture " << ArchitectureName << ")";
1569 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1570 for (Archive::child_iterator AI = A->child_begin(),
1571 AE = A->child_end();
1573 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1574 if (ChildOrErr.getError())
1576 if (MachOObjectFile *O =
1577 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1578 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1584 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1585 << "architecture: " + ArchFlags[i] + "\n";
1591 // No architecture flags were specified so if this contains a slice that
1592 // matches the host architecture dump only that.
1594 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1595 E = UB->end_objects();
1597 if (MachOObjectFile::getHostArch().getArchName() ==
1598 I->getArchTypeName()) {
1599 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1600 std::string ArchiveName;
1601 ArchiveName.clear();
1603 ObjectFile &O = *ObjOrErr.get();
1604 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1605 ProcessMachO(Filename, MachOOF);
1606 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1607 I->getAsArchive()) {
1608 std::unique_ptr<Archive> &A = *AOrErr;
1609 outs() << "Archive : " << Filename << "\n";
1611 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1612 for (Archive::child_iterator AI = A->child_begin(),
1613 AE = A->child_end();
1615 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1616 if (ChildOrErr.getError())
1618 if (MachOObjectFile *O =
1619 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1620 ProcessMachO(Filename, O, O->getFileName());
1627 // Either all architectures have been specified or none have been specified
1628 // and this does not contain the host architecture so dump all the slices.
1629 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1630 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1631 E = UB->end_objects();
1633 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1634 std::string ArchitectureName = "";
1635 if (moreThanOneArch)
1636 ArchitectureName = I->getArchTypeName();
1638 ObjectFile &Obj = *ObjOrErr.get();
1639 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1640 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1641 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1642 std::unique_ptr<Archive> &A = *AOrErr;
1643 outs() << "Archive : " << Filename;
1644 if (!ArchitectureName.empty())
1645 outs() << " (architecture " << ArchitectureName << ")";
1648 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1649 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1651 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1652 if (ChildOrErr.getError())
1654 if (MachOObjectFile *O =
1655 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1656 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1657 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1665 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1666 if (!checkMachOAndArchFlags(O, Filename))
1668 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1669 ProcessMachO(Filename, MachOOF);
1671 errs() << "llvm-objdump: '" << Filename << "': "
1672 << "Object is not a Mach-O file type.\n";
1674 errs() << "llvm-objdump: '" << Filename << "': "
1675 << "Unrecognized file type.\n";
1678 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1679 typedef std::vector<BindInfoEntry> BindTable;
1680 typedef BindTable::iterator bind_table_iterator;
1682 // The block of info used by the Symbolizer call backs.
1683 struct DisassembleInfo {
1687 SymbolAddressMap *AddrMap;
1688 std::vector<SectionRef> *Sections;
1689 const char *class_name;
1690 const char *selector_name;
1692 char *demangled_name;
1695 BindTable *bindtable;
1698 // SymbolizerGetOpInfo() is the operand information call back function.
1699 // This is called to get the symbolic information for operand(s) of an
1700 // instruction when it is being done. This routine does this from
1701 // the relocation information, symbol table, etc. That block of information
1702 // is a pointer to the struct DisassembleInfo that was passed when the
1703 // disassembler context was created and passed to back to here when
1704 // called back by the disassembler for instruction operands that could have
1705 // relocation information. The address of the instruction containing operand is
1706 // at the Pc parameter. The immediate value the operand has is passed in
1707 // op_info->Value and is at Offset past the start of the instruction and has a
1708 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1709 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1710 // names and addends of the symbolic expression to add for the operand. The
1711 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1712 // information is returned then this function returns 1 else it returns 0.
1713 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1714 uint64_t Size, int TagType, void *TagBuf) {
1715 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1716 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1717 uint64_t value = op_info->Value;
1719 // Make sure all fields returned are zero if we don't set them.
1720 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1721 op_info->Value = value;
1723 // If the TagType is not the value 1 which it code knows about or if no
1724 // verbose symbolic information is wanted then just return 0, indicating no
1725 // information is being returned.
1726 if (TagType != 1 || !info->verbose)
1729 unsigned int Arch = info->O->getArch();
1730 if (Arch == Triple::x86) {
1731 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1733 // First search the section's relocation entries (if any) for an entry
1734 // for this section offset.
1735 uint32_t sect_addr = info->S.getAddress();
1736 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1737 bool reloc_found = false;
1739 MachO::any_relocation_info RE;
1740 bool isExtern = false;
1742 bool r_scattered = false;
1743 uint32_t r_value, pair_r_value, r_type;
1744 for (const RelocationRef &Reloc : info->S.relocations()) {
1745 uint64_t RelocOffset = Reloc.getOffset();
1746 if (RelocOffset == sect_offset) {
1747 Rel = Reloc.getRawDataRefImpl();
1748 RE = info->O->getRelocation(Rel);
1749 r_type = info->O->getAnyRelocationType(RE);
1750 r_scattered = info->O->isRelocationScattered(RE);
1752 r_value = info->O->getScatteredRelocationValue(RE);
1753 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1754 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1755 DataRefImpl RelNext = Rel;
1756 info->O->moveRelocationNext(RelNext);
1757 MachO::any_relocation_info RENext;
1758 RENext = info->O->getRelocation(RelNext);
1759 if (info->O->isRelocationScattered(RENext))
1760 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1765 isExtern = info->O->getPlainRelocationExternal(RE);
1767 symbol_iterator RelocSym = Reloc.getSymbol();
1775 if (reloc_found && isExtern) {
1776 ErrorOr<StringRef> SymName = Symbol.getName();
1777 if (std::error_code EC = SymName.getError())
1778 report_fatal_error(EC.message());
1779 const char *name = SymName->data();
1780 op_info->AddSymbol.Present = 1;
1781 op_info->AddSymbol.Name = name;
1782 // For i386 extern relocation entries the value in the instruction is
1783 // the offset from the symbol, and value is already set in op_info->Value.
1786 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1787 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1788 const char *add = GuessSymbolName(r_value, info->AddrMap);
1789 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1790 uint32_t offset = value - (r_value - pair_r_value);
1791 op_info->AddSymbol.Present = 1;
1793 op_info->AddSymbol.Name = add;
1795 op_info->AddSymbol.Value = r_value;
1796 op_info->SubtractSymbol.Present = 1;
1798 op_info->SubtractSymbol.Name = sub;
1800 op_info->SubtractSymbol.Value = pair_r_value;
1801 op_info->Value = offset;
1805 // Second search the external relocation entries of a fully linked image
1806 // (if any) for an entry that matches this segment offset.
1807 // uint32_t seg_offset = (Pc + Offset);
1810 if (Arch == Triple::x86_64) {
1811 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1813 // First search the section's relocation entries (if any) for an entry
1814 // for this section offset.
1815 uint64_t sect_addr = info->S.getAddress();
1816 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1817 bool reloc_found = false;
1819 MachO::any_relocation_info RE;
1820 bool isExtern = false;
1822 for (const RelocationRef &Reloc : info->S.relocations()) {
1823 uint64_t RelocOffset = Reloc.getOffset();
1824 if (RelocOffset == sect_offset) {
1825 Rel = Reloc.getRawDataRefImpl();
1826 RE = info->O->getRelocation(Rel);
1827 // NOTE: Scattered relocations don't exist on x86_64.
1828 isExtern = info->O->getPlainRelocationExternal(RE);
1830 symbol_iterator RelocSym = Reloc.getSymbol();
1837 if (reloc_found && isExtern) {
1838 // The Value passed in will be adjusted by the Pc if the instruction
1839 // adds the Pc. But for x86_64 external relocation entries the Value
1840 // is the offset from the external symbol.
1841 if (info->O->getAnyRelocationPCRel(RE))
1842 op_info->Value -= Pc + Offset + Size;
1843 ErrorOr<StringRef> SymName = Symbol.getName();
1844 if (std::error_code EC = SymName.getError())
1845 report_fatal_error(EC.message());
1846 const char *name = SymName->data();
1847 unsigned Type = info->O->getAnyRelocationType(RE);
1848 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1849 DataRefImpl RelNext = Rel;
1850 info->O->moveRelocationNext(RelNext);
1851 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1852 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1853 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1854 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1855 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1856 op_info->SubtractSymbol.Present = 1;
1857 op_info->SubtractSymbol.Name = name;
1858 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1859 Symbol = *RelocSymNext;
1860 ErrorOr<StringRef> SymNameNext = Symbol.getName();
1861 if (std::error_code EC = SymNameNext.getError())
1862 report_fatal_error(EC.message());
1863 name = SymNameNext->data();
1866 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1867 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1868 op_info->AddSymbol.Present = 1;
1869 op_info->AddSymbol.Name = name;
1873 // Second search the external relocation entries of a fully linked image
1874 // (if any) for an entry that matches this segment offset.
1875 // uint64_t seg_offset = (Pc + Offset);
1878 if (Arch == Triple::arm) {
1879 if (Offset != 0 || (Size != 4 && Size != 2))
1881 // First search the section's relocation entries (if any) for an entry
1882 // for this section offset.
1883 uint32_t sect_addr = info->S.getAddress();
1884 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1886 MachO::any_relocation_info RE;
1887 bool isExtern = false;
1889 bool r_scattered = false;
1890 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1892 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1893 [&](const RelocationRef &Reloc) {
1894 uint64_t RelocOffset = Reloc.getOffset();
1895 return RelocOffset == sect_offset;
1898 if (Reloc == info->S.relocations().end())
1901 Rel = Reloc->getRawDataRefImpl();
1902 RE = info->O->getRelocation(Rel);
1903 r_length = info->O->getAnyRelocationLength(RE);
1904 r_scattered = info->O->isRelocationScattered(RE);
1906 r_value = info->O->getScatteredRelocationValue(RE);
1907 r_type = info->O->getScatteredRelocationType(RE);
1909 r_type = info->O->getAnyRelocationType(RE);
1910 isExtern = info->O->getPlainRelocationExternal(RE);
1912 symbol_iterator RelocSym = Reloc->getSymbol();
1916 if (r_type == MachO::ARM_RELOC_HALF ||
1917 r_type == MachO::ARM_RELOC_SECTDIFF ||
1918 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1919 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1920 DataRefImpl RelNext = Rel;
1921 info->O->moveRelocationNext(RelNext);
1922 MachO::any_relocation_info RENext;
1923 RENext = info->O->getRelocation(RelNext);
1924 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1925 if (info->O->isRelocationScattered(RENext))
1926 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1930 ErrorOr<StringRef> SymName = Symbol.getName();
1931 if (std::error_code EC = SymName.getError())
1932 report_fatal_error(EC.message());
1933 const char *name = SymName->data();
1934 op_info->AddSymbol.Present = 1;
1935 op_info->AddSymbol.Name = name;
1937 case MachO::ARM_RELOC_HALF:
1938 if ((r_length & 0x1) == 1) {
1939 op_info->Value = value << 16 | other_half;
1940 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1942 op_info->Value = other_half << 16 | value;
1943 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1951 // If we have a branch that is not an external relocation entry then
1952 // return 0 so the code in tryAddingSymbolicOperand() can use the
1953 // SymbolLookUp call back with the branch target address to look up the
1954 // symbol and possiblity add an annotation for a symbol stub.
1955 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1956 r_type == MachO::ARM_THUMB_RELOC_BR22))
1959 uint32_t offset = 0;
1960 if (r_type == MachO::ARM_RELOC_HALF ||
1961 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1962 if ((r_length & 0x1) == 1)
1963 value = value << 16 | other_half;
1965 value = other_half << 16 | value;
1967 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1968 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1969 offset = value - r_value;
1973 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1974 if ((r_length & 0x1) == 1)
1975 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1977 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1978 const char *add = GuessSymbolName(r_value, info->AddrMap);
1979 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1980 int32_t offset = value - (r_value - pair_r_value);
1981 op_info->AddSymbol.Present = 1;
1983 op_info->AddSymbol.Name = add;
1985 op_info->AddSymbol.Value = r_value;
1986 op_info->SubtractSymbol.Present = 1;
1988 op_info->SubtractSymbol.Name = sub;
1990 op_info->SubtractSymbol.Value = pair_r_value;
1991 op_info->Value = offset;
1995 op_info->AddSymbol.Present = 1;
1996 op_info->Value = offset;
1997 if (r_type == MachO::ARM_RELOC_HALF) {
1998 if ((r_length & 0x1) == 1)
1999 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2001 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2003 const char *add = GuessSymbolName(value, info->AddrMap);
2004 if (add != nullptr) {
2005 op_info->AddSymbol.Name = add;
2008 op_info->AddSymbol.Value = value;
2011 if (Arch == Triple::aarch64) {
2012 if (Offset != 0 || Size != 4)
2014 // First search the section's relocation entries (if any) for an entry
2015 // for this section offset.
2016 uint64_t sect_addr = info->S.getAddress();
2017 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2019 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2020 [&](const RelocationRef &Reloc) {
2021 uint64_t RelocOffset = Reloc.getOffset();
2022 return RelocOffset == sect_offset;
2025 if (Reloc == info->S.relocations().end())
2028 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2029 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2030 uint32_t r_type = info->O->getAnyRelocationType(RE);
2031 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2032 DataRefImpl RelNext = Rel;
2033 info->O->moveRelocationNext(RelNext);
2034 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2036 value = info->O->getPlainRelocationSymbolNum(RENext);
2037 op_info->Value = value;
2040 // NOTE: Scattered relocations don't exist on arm64.
2041 if (!info->O->getPlainRelocationExternal(RE))
2043 ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
2044 if (std::error_code EC = SymName.getError())
2045 report_fatal_error(EC.message());
2046 const char *name = SymName->data();
2047 op_info->AddSymbol.Present = 1;
2048 op_info->AddSymbol.Name = name;
2051 case MachO::ARM64_RELOC_PAGE21:
2053 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2055 case MachO::ARM64_RELOC_PAGEOFF12:
2057 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2059 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2061 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2063 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2065 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2067 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2068 /* @tvlppage is not implemented in llvm-mc */
2069 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2071 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2072 /* @tvlppageoff is not implemented in llvm-mc */
2073 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2076 case MachO::ARM64_RELOC_BRANCH26:
2077 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2085 // GuessCstringPointer is passed the address of what might be a pointer to a
2086 // literal string in a cstring section. If that address is in a cstring section
2087 // it returns a pointer to that string. Else it returns nullptr.
2088 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2089 struct DisassembleInfo *info) {
2090 for (const auto &Load : info->O->load_commands()) {
2091 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2092 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2093 for (unsigned J = 0; J < Seg.nsects; ++J) {
2094 MachO::section_64 Sec = info->O->getSection64(Load, J);
2095 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2096 if (section_type == MachO::S_CSTRING_LITERALS &&
2097 ReferenceValue >= Sec.addr &&
2098 ReferenceValue < Sec.addr + Sec.size) {
2099 uint64_t sect_offset = ReferenceValue - Sec.addr;
2100 uint64_t object_offset = Sec.offset + sect_offset;
2101 StringRef MachOContents = info->O->getData();
2102 uint64_t object_size = MachOContents.size();
2103 const char *object_addr = (const char *)MachOContents.data();
2104 if (object_offset < object_size) {
2105 const char *name = object_addr + object_offset;
2112 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2113 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2114 for (unsigned J = 0; J < Seg.nsects; ++J) {
2115 MachO::section Sec = info->O->getSection(Load, J);
2116 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2117 if (section_type == MachO::S_CSTRING_LITERALS &&
2118 ReferenceValue >= Sec.addr &&
2119 ReferenceValue < Sec.addr + Sec.size) {
2120 uint64_t sect_offset = ReferenceValue - Sec.addr;
2121 uint64_t object_offset = Sec.offset + sect_offset;
2122 StringRef MachOContents = info->O->getData();
2123 uint64_t object_size = MachOContents.size();
2124 const char *object_addr = (const char *)MachOContents.data();
2125 if (object_offset < object_size) {
2126 const char *name = object_addr + object_offset;
2138 // GuessIndirectSymbol returns the name of the indirect symbol for the
2139 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2140 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2141 // symbol name being referenced by the stub or pointer.
2142 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2143 struct DisassembleInfo *info) {
2144 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2145 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2146 for (const auto &Load : info->O->load_commands()) {
2147 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2148 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2149 for (unsigned J = 0; J < Seg.nsects; ++J) {
2150 MachO::section_64 Sec = info->O->getSection64(Load, J);
2151 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2152 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2153 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2154 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2155 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2156 section_type == MachO::S_SYMBOL_STUBS) &&
2157 ReferenceValue >= Sec.addr &&
2158 ReferenceValue < Sec.addr + Sec.size) {
2160 if (section_type == MachO::S_SYMBOL_STUBS)
2161 stride = Sec.reserved2;
2166 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2167 if (index < Dysymtab.nindirectsyms) {
2168 uint32_t indirect_symbol =
2169 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2170 if (indirect_symbol < Symtab.nsyms) {
2171 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2172 SymbolRef Symbol = *Sym;
2173 ErrorOr<StringRef> SymName = Symbol.getName();
2174 if (std::error_code EC = SymName.getError())
2175 report_fatal_error(EC.message());
2176 const char *name = SymName->data();
2182 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2183 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2184 for (unsigned J = 0; J < Seg.nsects; ++J) {
2185 MachO::section Sec = info->O->getSection(Load, J);
2186 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2187 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2188 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2189 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2190 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2191 section_type == MachO::S_SYMBOL_STUBS) &&
2192 ReferenceValue >= Sec.addr &&
2193 ReferenceValue < Sec.addr + Sec.size) {
2195 if (section_type == MachO::S_SYMBOL_STUBS)
2196 stride = Sec.reserved2;
2201 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2202 if (index < Dysymtab.nindirectsyms) {
2203 uint32_t indirect_symbol =
2204 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2205 if (indirect_symbol < Symtab.nsyms) {
2206 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2207 SymbolRef Symbol = *Sym;
2208 ErrorOr<StringRef> SymName = Symbol.getName();
2209 if (std::error_code EC = SymName.getError())
2210 report_fatal_error(EC.message());
2211 const char *name = SymName->data();
2222 // method_reference() is called passing it the ReferenceName that might be
2223 // a reference it to an Objective-C method call. If so then it allocates and
2224 // assembles a method call string with the values last seen and saved in
2225 // the DisassembleInfo's class_name and selector_name fields. This is saved
2226 // into the method field of the info and any previous string is free'ed.
2227 // Then the class_name field in the info is set to nullptr. The method call
2228 // string is set into ReferenceName and ReferenceType is set to
2229 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2230 // then both ReferenceType and ReferenceName are left unchanged.
2231 static void method_reference(struct DisassembleInfo *info,
2232 uint64_t *ReferenceType,
2233 const char **ReferenceName) {
2234 unsigned int Arch = info->O->getArch();
2235 if (*ReferenceName != nullptr) {
2236 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2237 if (info->selector_name != nullptr) {
2238 if (info->method != nullptr)
2240 if (info->class_name != nullptr) {
2241 info->method = (char *)malloc(5 + strlen(info->class_name) +
2242 strlen(info->selector_name));
2243 if (info->method != nullptr) {
2244 strcpy(info->method, "+[");
2245 strcat(info->method, info->class_name);
2246 strcat(info->method, " ");
2247 strcat(info->method, info->selector_name);
2248 strcat(info->method, "]");
2249 *ReferenceName = info->method;
2250 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2253 info->method = (char *)malloc(9 + strlen(info->selector_name));
2254 if (info->method != nullptr) {
2255 if (Arch == Triple::x86_64)
2256 strcpy(info->method, "-[%rdi ");
2257 else if (Arch == Triple::aarch64)
2258 strcpy(info->method, "-[x0 ");
2260 strcpy(info->method, "-[r? ");
2261 strcat(info->method, info->selector_name);
2262 strcat(info->method, "]");
2263 *ReferenceName = info->method;
2264 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2267 info->class_name = nullptr;
2269 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2270 if (info->selector_name != nullptr) {
2271 if (info->method != nullptr)
2273 info->method = (char *)malloc(17 + strlen(info->selector_name));
2274 if (info->method != nullptr) {
2275 if (Arch == Triple::x86_64)
2276 strcpy(info->method, "-[[%rdi super] ");
2277 else if (Arch == Triple::aarch64)
2278 strcpy(info->method, "-[[x0 super] ");
2280 strcpy(info->method, "-[[r? super] ");
2281 strcat(info->method, info->selector_name);
2282 strcat(info->method, "]");
2283 *ReferenceName = info->method;
2284 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2286 info->class_name = nullptr;
2292 // GuessPointerPointer() is passed the address of what might be a pointer to
2293 // a reference to an Objective-C class, selector, message ref or cfstring.
2294 // If so the value of the pointer is returned and one of the booleans are set
2295 // to true. If not zero is returned and all the booleans are set to false.
2296 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2297 struct DisassembleInfo *info,
2298 bool &classref, bool &selref, bool &msgref,
2304 for (const auto &Load : info->O->load_commands()) {
2305 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2306 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2307 for (unsigned J = 0; J < Seg.nsects; ++J) {
2308 MachO::section_64 Sec = info->O->getSection64(Load, J);
2309 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2310 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2311 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2312 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2313 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2314 ReferenceValue >= Sec.addr &&
2315 ReferenceValue < Sec.addr + Sec.size) {
2316 uint64_t sect_offset = ReferenceValue - Sec.addr;
2317 uint64_t object_offset = Sec.offset + sect_offset;
2318 StringRef MachOContents = info->O->getData();
2319 uint64_t object_size = MachOContents.size();
2320 const char *object_addr = (const char *)MachOContents.data();
2321 if (object_offset < object_size) {
2322 uint64_t pointer_value;
2323 memcpy(&pointer_value, object_addr + object_offset,
2325 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2326 sys::swapByteOrder(pointer_value);
2327 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2329 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2330 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2332 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2333 ReferenceValue + 8 < Sec.addr + Sec.size) {
2335 memcpy(&pointer_value, object_addr + object_offset + 8,
2337 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2338 sys::swapByteOrder(pointer_value);
2339 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2341 return pointer_value;
2348 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2353 // get_pointer_64 returns a pointer to the bytes in the object file at the
2354 // Address from a section in the Mach-O file. And indirectly returns the
2355 // offset into the section, number of bytes left in the section past the offset
2356 // and which section is was being referenced. If the Address is not in a
2357 // section nullptr is returned.
2358 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2359 uint32_t &left, SectionRef &S,
2360 DisassembleInfo *info,
2361 bool objc_only = false) {
2365 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2366 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2367 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2370 ((*(info->Sections))[SectIdx]).getName(SectName);
2371 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2372 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2373 if (SegName != "__OBJC" && SectName != "__cstring")
2376 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2377 S = (*(info->Sections))[SectIdx];
2378 offset = Address - SectAddress;
2379 left = SectSize - offset;
2380 StringRef SectContents;
2381 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2382 return SectContents.data() + offset;
2388 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2389 uint32_t &left, SectionRef &S,
2390 DisassembleInfo *info,
2391 bool objc_only = false) {
2392 return get_pointer_64(Address, offset, left, S, info, objc_only);
2395 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2396 // the symbol indirectly through n_value. Based on the relocation information
2397 // for the specified section offset in the specified section reference.
2398 // If no relocation information is found and a non-zero ReferenceValue for the
2399 // symbol is passed, look up that address in the info's AddrMap.
2400 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2401 DisassembleInfo *info, uint64_t &n_value,
2402 uint64_t ReferenceValue = 0) {
2407 // See if there is an external relocation entry at the sect_offset.
2408 bool reloc_found = false;
2410 MachO::any_relocation_info RE;
2411 bool isExtern = false;
2413 for (const RelocationRef &Reloc : S.relocations()) {
2414 uint64_t RelocOffset = Reloc.getOffset();
2415 if (RelocOffset == sect_offset) {
2416 Rel = Reloc.getRawDataRefImpl();
2417 RE = info->O->getRelocation(Rel);
2418 if (info->O->isRelocationScattered(RE))
2420 isExtern = info->O->getPlainRelocationExternal(RE);
2422 symbol_iterator RelocSym = Reloc.getSymbol();
2429 // If there is an external relocation entry for a symbol in this section
2430 // at this section_offset then use that symbol's value for the n_value
2431 // and return its name.
2432 const char *SymbolName = nullptr;
2433 if (reloc_found && isExtern) {
2434 n_value = Symbol.getValue();
2435 ErrorOr<StringRef> NameOrError = Symbol.getName();
2436 if (std::error_code EC = NameOrError.getError())
2437 report_fatal_error(EC.message());
2438 StringRef Name = *NameOrError;
2439 if (!Name.empty()) {
2440 SymbolName = Name.data();
2445 // TODO: For fully linked images, look through the external relocation
2446 // entries off the dynamic symtab command. For these the r_offset is from the
2447 // start of the first writeable segment in the Mach-O file. So the offset
2448 // to this section from that segment is passed to this routine by the caller,
2449 // as the database_offset. Which is the difference of the section's starting
2450 // address and the first writable segment.
2452 // NOTE: need add passing the database_offset to this routine.
2454 // We did not find an external relocation entry so look up the ReferenceValue
2455 // as an address of a symbol and if found return that symbol's name.
2456 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2461 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2462 DisassembleInfo *info,
2463 uint32_t ReferenceValue) {
2465 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2468 // These are structs in the Objective-C meta data and read to produce the
2469 // comments for disassembly. While these are part of the ABI they are no
2470 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2472 // The cfstring object in a 64-bit Mach-O file.
2473 struct cfstring64_t {
2474 uint64_t isa; // class64_t * (64-bit pointer)
2475 uint64_t flags; // flag bits
2476 uint64_t characters; // char * (64-bit pointer)
2477 uint64_t length; // number of non-NULL characters in above
2480 // The class object in a 64-bit Mach-O file.
2482 uint64_t isa; // class64_t * (64-bit pointer)
2483 uint64_t superclass; // class64_t * (64-bit pointer)
2484 uint64_t cache; // Cache (64-bit pointer)
2485 uint64_t vtable; // IMP * (64-bit pointer)
2486 uint64_t data; // class_ro64_t * (64-bit pointer)
2490 uint32_t isa; /* class32_t * (32-bit pointer) */
2491 uint32_t superclass; /* class32_t * (32-bit pointer) */
2492 uint32_t cache; /* Cache (32-bit pointer) */
2493 uint32_t vtable; /* IMP * (32-bit pointer) */
2494 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2497 struct class_ro64_t {
2499 uint32_t instanceStart;
2500 uint32_t instanceSize;
2502 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2503 uint64_t name; // const char * (64-bit pointer)
2504 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2505 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2506 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2507 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2508 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2511 struct class_ro32_t {
2513 uint32_t instanceStart;
2514 uint32_t instanceSize;
2515 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2516 uint32_t name; /* const char * (32-bit pointer) */
2517 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2518 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2519 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2520 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2521 uint32_t baseProperties; /* const struct objc_property_list *
2525 /* Values for class_ro{64,32}_t->flags */
2526 #define RO_META (1 << 0)
2527 #define RO_ROOT (1 << 1)
2528 #define RO_HAS_CXX_STRUCTORS (1 << 2)
2530 struct method_list64_t {
2533 /* struct method64_t first; These structures follow inline */
2536 struct method_list32_t {
2539 /* struct method32_t first; These structures follow inline */
2543 uint64_t name; /* SEL (64-bit pointer) */
2544 uint64_t types; /* const char * (64-bit pointer) */
2545 uint64_t imp; /* IMP (64-bit pointer) */
2549 uint32_t name; /* SEL (32-bit pointer) */
2550 uint32_t types; /* const char * (32-bit pointer) */
2551 uint32_t imp; /* IMP (32-bit pointer) */
2554 struct protocol_list64_t {
2555 uint64_t count; /* uintptr_t (a 64-bit value) */
2556 /* struct protocol64_t * list[0]; These pointers follow inline */
2559 struct protocol_list32_t {
2560 uint32_t count; /* uintptr_t (a 32-bit value) */
2561 /* struct protocol32_t * list[0]; These pointers follow inline */
2564 struct protocol64_t {
2565 uint64_t isa; /* id * (64-bit pointer) */
2566 uint64_t name; /* const char * (64-bit pointer) */
2567 uint64_t protocols; /* struct protocol_list64_t *
2569 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2570 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2571 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2572 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2573 uint64_t instanceProperties; /* struct objc_property_list *
2577 struct protocol32_t {
2578 uint32_t isa; /* id * (32-bit pointer) */
2579 uint32_t name; /* const char * (32-bit pointer) */
2580 uint32_t protocols; /* struct protocol_list_t *
2582 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2583 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2584 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2585 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2586 uint32_t instanceProperties; /* struct objc_property_list *
2590 struct ivar_list64_t {
2593 /* struct ivar64_t first; These structures follow inline */
2596 struct ivar_list32_t {
2599 /* struct ivar32_t first; These structures follow inline */
2603 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2604 uint64_t name; /* const char * (64-bit pointer) */
2605 uint64_t type; /* const char * (64-bit pointer) */
2611 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2612 uint32_t name; /* const char * (32-bit pointer) */
2613 uint32_t type; /* const char * (32-bit pointer) */
2618 struct objc_property_list64 {
2621 /* struct objc_property64 first; These structures follow inline */
2624 struct objc_property_list32 {
2627 /* struct objc_property32 first; These structures follow inline */
2630 struct objc_property64 {
2631 uint64_t name; /* const char * (64-bit pointer) */
2632 uint64_t attributes; /* const char * (64-bit pointer) */
2635 struct objc_property32 {
2636 uint32_t name; /* const char * (32-bit pointer) */
2637 uint32_t attributes; /* const char * (32-bit pointer) */
2640 struct category64_t {
2641 uint64_t name; /* const char * (64-bit pointer) */
2642 uint64_t cls; /* struct class_t * (64-bit pointer) */
2643 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2644 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2645 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2646 uint64_t instanceProperties; /* struct objc_property_list *
2650 struct category32_t {
2651 uint32_t name; /* const char * (32-bit pointer) */
2652 uint32_t cls; /* struct class_t * (32-bit pointer) */
2653 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2654 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2655 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2656 uint32_t instanceProperties; /* struct objc_property_list *
2660 struct objc_image_info64 {
2664 struct objc_image_info32 {
2668 struct imageInfo_t {
2672 /* masks for objc_image_info.flags */
2673 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2674 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2676 struct message_ref64 {
2677 uint64_t imp; /* IMP (64-bit pointer) */
2678 uint64_t sel; /* SEL (64-bit pointer) */
2681 struct message_ref32 {
2682 uint32_t imp; /* IMP (32-bit pointer) */
2683 uint32_t sel; /* SEL (32-bit pointer) */
2686 // Objective-C 1 (32-bit only) meta data structs.
2688 struct objc_module_t {
2691 uint32_t name; /* char * (32-bit pointer) */
2692 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2695 struct objc_symtab_t {
2696 uint32_t sel_ref_cnt;
2697 uint32_t refs; /* SEL * (32-bit pointer) */
2698 uint16_t cls_def_cnt;
2699 uint16_t cat_def_cnt;
2700 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2703 struct objc_class_t {
2704 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2705 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2706 uint32_t name; /* const char * (32-bit pointer) */
2709 int32_t instance_size;
2710 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2711 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2712 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2713 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2716 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2717 // class is not a metaclass
2718 #define CLS_CLASS 0x1
2719 // class is a metaclass
2720 #define CLS_META 0x2
2722 struct objc_category_t {
2723 uint32_t category_name; /* char * (32-bit pointer) */
2724 uint32_t class_name; /* char * (32-bit pointer) */
2725 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2726 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2727 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2730 struct objc_ivar_t {
2731 uint32_t ivar_name; /* char * (32-bit pointer) */
2732 uint32_t ivar_type; /* char * (32-bit pointer) */
2733 int32_t ivar_offset;
2736 struct objc_ivar_list_t {
2738 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2741 struct objc_method_list_t {
2742 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2743 int32_t method_count;
2744 // struct objc_method_t method_list[1]; /* variable length structure */
2747 struct objc_method_t {
2748 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2749 uint32_t method_types; /* char * (32-bit pointer) */
2750 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2754 struct objc_protocol_list_t {
2755 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2757 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2758 // (32-bit pointer) */
2761 struct objc_protocol_t {
2762 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2763 uint32_t protocol_name; /* char * (32-bit pointer) */
2764 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2765 uint32_t instance_methods; /* struct objc_method_description_list *
2767 uint32_t class_methods; /* struct objc_method_description_list *
2771 struct objc_method_description_list_t {
2773 // struct objc_method_description_t list[1];
2776 struct objc_method_description_t {
2777 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2778 uint32_t types; /* char * (32-bit pointer) */
2781 inline void swapStruct(struct cfstring64_t &cfs) {
2782 sys::swapByteOrder(cfs.isa);
2783 sys::swapByteOrder(cfs.flags);
2784 sys::swapByteOrder(cfs.characters);
2785 sys::swapByteOrder(cfs.length);
2788 inline void swapStruct(struct class64_t &c) {
2789 sys::swapByteOrder(c.isa);
2790 sys::swapByteOrder(c.superclass);
2791 sys::swapByteOrder(c.cache);
2792 sys::swapByteOrder(c.vtable);
2793 sys::swapByteOrder(c.data);
2796 inline void swapStruct(struct class32_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 class_ro64_t &cro) {
2805 sys::swapByteOrder(cro.flags);
2806 sys::swapByteOrder(cro.instanceStart);
2807 sys::swapByteOrder(cro.instanceSize);
2808 sys::swapByteOrder(cro.reserved);
2809 sys::swapByteOrder(cro.ivarLayout);
2810 sys::swapByteOrder(cro.name);
2811 sys::swapByteOrder(cro.baseMethods);
2812 sys::swapByteOrder(cro.baseProtocols);
2813 sys::swapByteOrder(cro.ivars);
2814 sys::swapByteOrder(cro.weakIvarLayout);
2815 sys::swapByteOrder(cro.baseProperties);
2818 inline void swapStruct(struct class_ro32_t &cro) {
2819 sys::swapByteOrder(cro.flags);
2820 sys::swapByteOrder(cro.instanceStart);
2821 sys::swapByteOrder(cro.instanceSize);
2822 sys::swapByteOrder(cro.ivarLayout);
2823 sys::swapByteOrder(cro.name);
2824 sys::swapByteOrder(cro.baseMethods);
2825 sys::swapByteOrder(cro.baseProtocols);
2826 sys::swapByteOrder(cro.ivars);
2827 sys::swapByteOrder(cro.weakIvarLayout);
2828 sys::swapByteOrder(cro.baseProperties);
2831 inline void swapStruct(struct method_list64_t &ml) {
2832 sys::swapByteOrder(ml.entsize);
2833 sys::swapByteOrder(ml.count);
2836 inline void swapStruct(struct method_list32_t &ml) {
2837 sys::swapByteOrder(ml.entsize);
2838 sys::swapByteOrder(ml.count);
2841 inline void swapStruct(struct method64_t &m) {
2842 sys::swapByteOrder(m.name);
2843 sys::swapByteOrder(m.types);
2844 sys::swapByteOrder(m.imp);
2847 inline void swapStruct(struct method32_t &m) {
2848 sys::swapByteOrder(m.name);
2849 sys::swapByteOrder(m.types);
2850 sys::swapByteOrder(m.imp);
2853 inline void swapStruct(struct protocol_list64_t &pl) {
2854 sys::swapByteOrder(pl.count);
2857 inline void swapStruct(struct protocol_list32_t &pl) {
2858 sys::swapByteOrder(pl.count);
2861 inline void swapStruct(struct protocol64_t &p) {
2862 sys::swapByteOrder(p.isa);
2863 sys::swapByteOrder(p.name);
2864 sys::swapByteOrder(p.protocols);
2865 sys::swapByteOrder(p.instanceMethods);
2866 sys::swapByteOrder(p.classMethods);
2867 sys::swapByteOrder(p.optionalInstanceMethods);
2868 sys::swapByteOrder(p.optionalClassMethods);
2869 sys::swapByteOrder(p.instanceProperties);
2872 inline void swapStruct(struct protocol32_t &p) {
2873 sys::swapByteOrder(p.isa);
2874 sys::swapByteOrder(p.name);
2875 sys::swapByteOrder(p.protocols);
2876 sys::swapByteOrder(p.instanceMethods);
2877 sys::swapByteOrder(p.classMethods);
2878 sys::swapByteOrder(p.optionalInstanceMethods);
2879 sys::swapByteOrder(p.optionalClassMethods);
2880 sys::swapByteOrder(p.instanceProperties);
2883 inline void swapStruct(struct ivar_list64_t &il) {
2884 sys::swapByteOrder(il.entsize);
2885 sys::swapByteOrder(il.count);
2888 inline void swapStruct(struct ivar_list32_t &il) {
2889 sys::swapByteOrder(il.entsize);
2890 sys::swapByteOrder(il.count);
2893 inline void swapStruct(struct ivar64_t &i) {
2894 sys::swapByteOrder(i.offset);
2895 sys::swapByteOrder(i.name);
2896 sys::swapByteOrder(i.type);
2897 sys::swapByteOrder(i.alignment);
2898 sys::swapByteOrder(i.size);
2901 inline void swapStruct(struct ivar32_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 objc_property_list64 &pl) {
2910 sys::swapByteOrder(pl.entsize);
2911 sys::swapByteOrder(pl.count);
2914 inline void swapStruct(struct objc_property_list32 &pl) {
2915 sys::swapByteOrder(pl.entsize);
2916 sys::swapByteOrder(pl.count);
2919 inline void swapStruct(struct objc_property64 &op) {
2920 sys::swapByteOrder(op.name);
2921 sys::swapByteOrder(op.attributes);
2924 inline void swapStruct(struct objc_property32 &op) {
2925 sys::swapByteOrder(op.name);
2926 sys::swapByteOrder(op.attributes);
2929 inline void swapStruct(struct category64_t &c) {
2930 sys::swapByteOrder(c.name);
2931 sys::swapByteOrder(c.cls);
2932 sys::swapByteOrder(c.instanceMethods);
2933 sys::swapByteOrder(c.classMethods);
2934 sys::swapByteOrder(c.protocols);
2935 sys::swapByteOrder(c.instanceProperties);
2938 inline void swapStruct(struct category32_t &c) {
2939 sys::swapByteOrder(c.name);
2940 sys::swapByteOrder(c.cls);
2941 sys::swapByteOrder(c.instanceMethods);
2942 sys::swapByteOrder(c.classMethods);
2943 sys::swapByteOrder(c.protocols);
2944 sys::swapByteOrder(c.instanceProperties);
2947 inline void swapStruct(struct objc_image_info64 &o) {
2948 sys::swapByteOrder(o.version);
2949 sys::swapByteOrder(o.flags);
2952 inline void swapStruct(struct objc_image_info32 &o) {
2953 sys::swapByteOrder(o.version);
2954 sys::swapByteOrder(o.flags);
2957 inline void swapStruct(struct imageInfo_t &o) {
2958 sys::swapByteOrder(o.version);
2959 sys::swapByteOrder(o.flags);
2962 inline void swapStruct(struct message_ref64 &mr) {
2963 sys::swapByteOrder(mr.imp);
2964 sys::swapByteOrder(mr.sel);
2967 inline void swapStruct(struct message_ref32 &mr) {
2968 sys::swapByteOrder(mr.imp);
2969 sys::swapByteOrder(mr.sel);
2972 inline void swapStruct(struct objc_module_t &module) {
2973 sys::swapByteOrder(module.version);
2974 sys::swapByteOrder(module.size);
2975 sys::swapByteOrder(module.name);
2976 sys::swapByteOrder(module.symtab);
2979 inline void swapStruct(struct objc_symtab_t &symtab) {
2980 sys::swapByteOrder(symtab.sel_ref_cnt);
2981 sys::swapByteOrder(symtab.refs);
2982 sys::swapByteOrder(symtab.cls_def_cnt);
2983 sys::swapByteOrder(symtab.cat_def_cnt);
2986 inline void swapStruct(struct objc_class_t &objc_class) {
2987 sys::swapByteOrder(objc_class.isa);
2988 sys::swapByteOrder(objc_class.super_class);
2989 sys::swapByteOrder(objc_class.name);
2990 sys::swapByteOrder(objc_class.version);
2991 sys::swapByteOrder(objc_class.info);
2992 sys::swapByteOrder(objc_class.instance_size);
2993 sys::swapByteOrder(objc_class.ivars);
2994 sys::swapByteOrder(objc_class.methodLists);
2995 sys::swapByteOrder(objc_class.cache);
2996 sys::swapByteOrder(objc_class.protocols);
2999 inline void swapStruct(struct objc_category_t &objc_category) {
3000 sys::swapByteOrder(objc_category.category_name);
3001 sys::swapByteOrder(objc_category.class_name);
3002 sys::swapByteOrder(objc_category.instance_methods);
3003 sys::swapByteOrder(objc_category.class_methods);
3004 sys::swapByteOrder(objc_category.protocols);
3007 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3008 sys::swapByteOrder(objc_ivar_list.ivar_count);
3011 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3012 sys::swapByteOrder(objc_ivar.ivar_name);
3013 sys::swapByteOrder(objc_ivar.ivar_type);
3014 sys::swapByteOrder(objc_ivar.ivar_offset);
3017 inline void swapStruct(struct objc_method_list_t &method_list) {
3018 sys::swapByteOrder(method_list.obsolete);
3019 sys::swapByteOrder(method_list.method_count);
3022 inline void swapStruct(struct objc_method_t &method) {
3023 sys::swapByteOrder(method.method_name);
3024 sys::swapByteOrder(method.method_types);
3025 sys::swapByteOrder(method.method_imp);
3028 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3029 sys::swapByteOrder(protocol_list.next);
3030 sys::swapByteOrder(protocol_list.count);
3033 inline void swapStruct(struct objc_protocol_t &protocol) {
3034 sys::swapByteOrder(protocol.isa);
3035 sys::swapByteOrder(protocol.protocol_name);
3036 sys::swapByteOrder(protocol.protocol_list);
3037 sys::swapByteOrder(protocol.instance_methods);
3038 sys::swapByteOrder(protocol.class_methods);
3041 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3042 sys::swapByteOrder(mdl.count);
3045 inline void swapStruct(struct objc_method_description_t &md) {
3046 sys::swapByteOrder(md.name);
3047 sys::swapByteOrder(md.types);
3050 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3051 struct DisassembleInfo *info);
3053 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3054 // to an Objective-C class and returns the class name. It is also passed the
3055 // address of the pointer, so when the pointer is zero as it can be in an .o
3056 // file, that is used to look for an external relocation entry with a symbol
3058 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3059 uint64_t ReferenceValue,
3060 struct DisassembleInfo *info) {
3062 uint32_t offset, left;
3065 // The pointer_value can be 0 in an object file and have a relocation
3066 // entry for the class symbol at the ReferenceValue (the address of the
3068 if (pointer_value == 0) {
3069 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3070 if (r == nullptr || left < sizeof(uint64_t))
3073 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3074 if (symbol_name == nullptr)
3076 const char *class_name = strrchr(symbol_name, '$');
3077 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3078 return class_name + 2;
3083 // The case were the pointer_value is non-zero and points to a class defined
3084 // in this Mach-O file.
3085 r = get_pointer_64(pointer_value, offset, left, S, info);
3086 if (r == nullptr || left < sizeof(struct class64_t))
3089 memcpy(&c, r, sizeof(struct class64_t));
3090 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3094 r = get_pointer_64(c.data, offset, left, S, info);
3095 if (r == nullptr || left < sizeof(struct class_ro64_t))
3097 struct class_ro64_t cro;
3098 memcpy(&cro, r, sizeof(struct class_ro64_t));
3099 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3103 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3107 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3108 // pointer to a cfstring and returns its name or nullptr.
3109 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3110 struct DisassembleInfo *info) {
3111 const char *r, *name;
3112 uint32_t offset, left;
3114 struct cfstring64_t cfs;
3115 uint64_t cfs_characters;
3117 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3118 if (r == nullptr || left < sizeof(struct cfstring64_t))
3120 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3121 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3123 if (cfs.characters == 0) {
3125 const char *symbol_name = get_symbol_64(
3126 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3127 if (symbol_name == nullptr)
3129 cfs_characters = n_value;
3131 cfs_characters = cfs.characters;
3132 name = get_pointer_64(cfs_characters, offset, left, S, info);
3137 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
3138 // of a pointer to an Objective-C selector reference when the pointer value is
3139 // zero as in a .o file and is likely to have a external relocation entry with
3140 // who's symbol's n_value is the real pointer to the selector name. If that is
3141 // the case the real pointer to the selector name is returned else 0 is
3143 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3144 struct DisassembleInfo *info) {
3145 uint32_t offset, left;
3148 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3149 if (r == nullptr || left < sizeof(uint64_t))
3152 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3153 if (symbol_name == nullptr)
3158 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3159 const char *sectname) {
3160 for (const SectionRef &Section : O->sections()) {
3162 Section.getName(SectName);
3163 DataRefImpl Ref = Section.getRawDataRefImpl();
3164 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3165 if (SegName == segname && SectName == sectname)
3168 return SectionRef();
3172 walk_pointer_list_64(const char *listname, const SectionRef S,
3173 MachOObjectFile *O, struct DisassembleInfo *info,
3174 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3175 if (S == SectionRef())
3179 S.getName(SectName);
3180 DataRefImpl Ref = S.getRawDataRefImpl();
3181 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3182 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3185 S.getContents(BytesStr);
3186 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3188 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3189 uint32_t left = S.getSize() - i;
3190 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3192 memcpy(&p, Contents + i, size);
3193 if (i + sizeof(uint64_t) > S.getSize())
3194 outs() << listname << " list pointer extends past end of (" << SegName
3195 << "," << SectName << ") section\n";
3196 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3198 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3199 sys::swapByteOrder(p);
3201 uint64_t n_value = 0;
3202 const char *name = get_symbol_64(i, S, info, n_value, p);
3203 if (name == nullptr)
3204 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3207 outs() << format("0x%" PRIx64, n_value);
3209 outs() << " + " << format("0x%" PRIx64, p);
3211 outs() << format("0x%" PRIx64, p);
3212 if (name != nullptr)
3213 outs() << " " << name;
3223 walk_pointer_list_32(const char *listname, const SectionRef S,
3224 MachOObjectFile *O, struct DisassembleInfo *info,
3225 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3226 if (S == SectionRef())
3230 S.getName(SectName);
3231 DataRefImpl Ref = S.getRawDataRefImpl();
3232 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3233 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3236 S.getContents(BytesStr);
3237 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3239 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3240 uint32_t left = S.getSize() - i;
3241 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3243 memcpy(&p, Contents + i, size);
3244 if (i + sizeof(uint32_t) > S.getSize())
3245 outs() << listname << " list pointer extends past end of (" << SegName
3246 << "," << SectName << ") section\n";
3247 uint32_t Address = S.getAddress() + i;
3248 outs() << format("%08" PRIx32, Address) << " ";
3250 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3251 sys::swapByteOrder(p);
3252 outs() << format("0x%" PRIx32, p);
3254 const char *name = get_symbol_32(i, S, info, p);
3255 if (name != nullptr)
3256 outs() << " " << name;
3264 static void print_layout_map(const char *layout_map, uint32_t left) {
3265 outs() << " layout map: ";
3267 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3270 } while (*layout_map != '\0' && left != 0);
3274 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3275 uint32_t offset, left;
3277 const char *layout_map;
3281 layout_map = get_pointer_64(p, offset, left, S, info);
3282 print_layout_map(layout_map, left);
3285 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3286 uint32_t offset, left;
3288 const char *layout_map;
3292 layout_map = get_pointer_32(p, offset, left, S, info);
3293 print_layout_map(layout_map, left);
3296 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3297 const char *indent) {
3298 struct method_list64_t ml;
3299 struct method64_t m;
3301 uint32_t offset, xoffset, left, i;
3303 const char *name, *sym_name;
3306 r = get_pointer_64(p, offset, left, S, info);
3309 memset(&ml, '\0', sizeof(struct method_list64_t));
3310 if (left < sizeof(struct method_list64_t)) {
3311 memcpy(&ml, r, left);
3312 outs() << " (method_list_t entends past the end of the section)\n";
3314 memcpy(&ml, r, sizeof(struct method_list64_t));
3315 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3317 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3318 outs() << indent << "\t\t count " << ml.count << "\n";
3320 p += sizeof(struct method_list64_t);
3321 offset += sizeof(struct method_list64_t);
3322 for (i = 0; i < ml.count; i++) {
3323 r = get_pointer_64(p, offset, left, S, info);
3326 memset(&m, '\0', sizeof(struct method64_t));
3327 if (left < sizeof(struct method64_t)) {
3328 memcpy(&ml, r, left);
3329 outs() << indent << " (method_t entends past the end of the section)\n";
3331 memcpy(&m, r, sizeof(struct method64_t));
3332 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3335 outs() << indent << "\t\t name ";
3336 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3337 info, n_value, m.name);
3339 if (info->verbose && sym_name != nullptr)
3342 outs() << format("0x%" PRIx64, n_value);
3344 outs() << " + " << format("0x%" PRIx64, m.name);
3346 outs() << format("0x%" PRIx64, m.name);
3347 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3348 if (name != nullptr)
3349 outs() << format(" %.*s", left, name);
3352 outs() << indent << "\t\t types ";
3353 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3354 info, n_value, m.types);
3356 if (info->verbose && sym_name != nullptr)
3359 outs() << format("0x%" PRIx64, n_value);
3361 outs() << " + " << format("0x%" PRIx64, m.types);
3363 outs() << format("0x%" PRIx64, m.types);
3364 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3365 if (name != nullptr)
3366 outs() << format(" %.*s", left, name);
3369 outs() << indent << "\t\t imp ";
3370 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3372 if (info->verbose && name == nullptr) {
3374 outs() << format("0x%" PRIx64, n_value) << " ";
3376 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3378 outs() << format("0x%" PRIx64, m.imp) << " ";
3380 if (name != nullptr)
3384 p += sizeof(struct method64_t);
3385 offset += sizeof(struct method64_t);
3389 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3390 const char *indent) {
3391 struct method_list32_t ml;
3392 struct method32_t m;
3393 const char *r, *name;
3394 uint32_t offset, xoffset, left, i;
3397 r = get_pointer_32(p, offset, left, S, info);
3400 memset(&ml, '\0', sizeof(struct method_list32_t));
3401 if (left < sizeof(struct method_list32_t)) {
3402 memcpy(&ml, r, left);
3403 outs() << " (method_list_t entends past the end of the section)\n";
3405 memcpy(&ml, r, sizeof(struct method_list32_t));
3406 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3408 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3409 outs() << indent << "\t\t count " << ml.count << "\n";
3411 p += sizeof(struct method_list32_t);
3412 offset += sizeof(struct method_list32_t);
3413 for (i = 0; i < ml.count; i++) {
3414 r = get_pointer_32(p, offset, left, S, info);
3417 memset(&m, '\0', sizeof(struct method32_t));
3418 if (left < sizeof(struct method32_t)) {
3419 memcpy(&ml, r, left);
3420 outs() << indent << " (method_t entends past the end of the section)\n";
3422 memcpy(&m, r, sizeof(struct method32_t));
3423 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3426 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3427 name = get_pointer_32(m.name, xoffset, left, xS, info);
3428 if (name != nullptr)
3429 outs() << format(" %.*s", left, name);
3432 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3433 name = get_pointer_32(m.types, xoffset, left, xS, info);
3434 if (name != nullptr)
3435 outs() << format(" %.*s", left, name);
3438 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3439 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3441 if (name != nullptr)
3442 outs() << " " << name;
3445 p += sizeof(struct method32_t);
3446 offset += sizeof(struct method32_t);
3450 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3451 uint32_t offset, left, xleft;
3453 struct objc_method_list_t method_list;
3454 struct objc_method_t method;
3455 const char *r, *methods, *name, *SymbolName;
3458 r = get_pointer_32(p, offset, left, S, info, true);
3463 if (left > sizeof(struct objc_method_list_t)) {
3464 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3466 outs() << "\t\t objc_method_list extends past end of the section\n";
3467 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3468 memcpy(&method_list, r, left);
3470 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3471 swapStruct(method_list);
3473 outs() << "\t\t obsolete "
3474 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3475 outs() << "\t\t method_count " << method_list.method_count << "\n";
3477 methods = r + sizeof(struct objc_method_list_t);
3478 for (i = 0; i < method_list.method_count; i++) {
3479 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3480 outs() << "\t\t remaining method's extend past the of the section\n";
3483 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3484 sizeof(struct objc_method_t));
3485 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3488 outs() << "\t\t method_name "
3489 << format("0x%08" PRIx32, method.method_name);
3490 if (info->verbose) {
3491 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3492 if (name != nullptr)
3493 outs() << format(" %.*s", xleft, name);
3495 outs() << " (not in an __OBJC section)";
3499 outs() << "\t\t method_types "
3500 << format("0x%08" PRIx32, method.method_types);
3501 if (info->verbose) {
3502 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3503 if (name != nullptr)
3504 outs() << format(" %.*s", xleft, name);
3506 outs() << " (not in an __OBJC section)";
3510 outs() << "\t\t method_imp "
3511 << format("0x%08" PRIx32, method.method_imp) << " ";
3512 if (info->verbose) {
3513 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3514 if (SymbolName != nullptr)
3515 outs() << SymbolName;
3522 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3523 struct protocol_list64_t pl;
3524 uint64_t q, n_value;
3525 struct protocol64_t pc;
3527 uint32_t offset, xoffset, left, i;
3529 const char *name, *sym_name;
3531 r = get_pointer_64(p, offset, left, S, info);
3534 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3535 if (left < sizeof(struct protocol_list64_t)) {
3536 memcpy(&pl, r, left);
3537 outs() << " (protocol_list_t entends past the end of the section)\n";
3539 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3540 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3542 outs() << " count " << pl.count << "\n";
3544 p += sizeof(struct protocol_list64_t);
3545 offset += sizeof(struct protocol_list64_t);
3546 for (i = 0; i < pl.count; i++) {
3547 r = get_pointer_64(p, offset, left, S, info);
3551 if (left < sizeof(uint64_t)) {
3552 memcpy(&q, r, left);
3553 outs() << " (protocol_t * entends past the end of the section)\n";
3555 memcpy(&q, r, sizeof(uint64_t));
3556 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3557 sys::swapByteOrder(q);
3559 outs() << "\t\t list[" << i << "] ";
3560 sym_name = get_symbol_64(offset, S, info, n_value, q);
3562 if (info->verbose && sym_name != nullptr)
3565 outs() << format("0x%" PRIx64, n_value);
3567 outs() << " + " << format("0x%" PRIx64, q);
3569 outs() << format("0x%" PRIx64, q);
3570 outs() << " (struct protocol_t *)\n";
3572 r = get_pointer_64(q + n_value, offset, left, S, info);
3575 memset(&pc, '\0', sizeof(struct protocol64_t));
3576 if (left < sizeof(struct protocol64_t)) {
3577 memcpy(&pc, r, left);
3578 outs() << " (protocol_t entends past the end of the section)\n";
3580 memcpy(&pc, r, sizeof(struct protocol64_t));
3581 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3584 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3586 outs() << "\t\t\t name ";
3587 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3588 info, n_value, pc.name);
3590 if (info->verbose && sym_name != nullptr)
3593 outs() << format("0x%" PRIx64, n_value);
3595 outs() << " + " << format("0x%" PRIx64, pc.name);
3597 outs() << format("0x%" PRIx64, pc.name);
3598 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3599 if (name != nullptr)
3600 outs() << format(" %.*s", left, name);
3603 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3605 outs() << "\t\t instanceMethods ";
3607 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3608 S, info, n_value, pc.instanceMethods);
3610 if (info->verbose && sym_name != nullptr)
3613 outs() << format("0x%" PRIx64, n_value);
3614 if (pc.instanceMethods != 0)
3615 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3617 outs() << format("0x%" PRIx64, pc.instanceMethods);
3618 outs() << " (struct method_list_t *)\n";
3619 if (pc.instanceMethods + n_value != 0)
3620 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3622 outs() << "\t\t classMethods ";
3624 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3625 info, n_value, pc.classMethods);
3627 if (info->verbose && sym_name != nullptr)
3630 outs() << format("0x%" PRIx64, n_value);
3631 if (pc.classMethods != 0)
3632 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3634 outs() << format("0x%" PRIx64, pc.classMethods);
3635 outs() << " (struct method_list_t *)\n";
3636 if (pc.classMethods + n_value != 0)
3637 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3639 outs() << "\t optionalInstanceMethods "
3640 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3641 outs() << "\t optionalClassMethods "
3642 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3643 outs() << "\t instanceProperties "
3644 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3646 p += sizeof(uint64_t);
3647 offset += sizeof(uint64_t);
3651 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3652 struct protocol_list32_t pl;
3654 struct protocol32_t pc;
3656 uint32_t offset, xoffset, left, i;
3660 r = get_pointer_32(p, offset, left, S, info);
3663 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3664 if (left < sizeof(struct protocol_list32_t)) {
3665 memcpy(&pl, r, left);
3666 outs() << " (protocol_list_t entends past the end of the section)\n";
3668 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3669 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3671 outs() << " count " << pl.count << "\n";
3673 p += sizeof(struct protocol_list32_t);
3674 offset += sizeof(struct protocol_list32_t);
3675 for (i = 0; i < pl.count; i++) {
3676 r = get_pointer_32(p, offset, left, S, info);
3680 if (left < sizeof(uint32_t)) {
3681 memcpy(&q, r, left);
3682 outs() << " (protocol_t * entends past the end of the section)\n";
3684 memcpy(&q, r, sizeof(uint32_t));
3685 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3686 sys::swapByteOrder(q);
3687 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3688 << " (struct protocol_t *)\n";
3689 r = get_pointer_32(q, offset, left, S, info);
3692 memset(&pc, '\0', sizeof(struct protocol32_t));
3693 if (left < sizeof(struct protocol32_t)) {
3694 memcpy(&pc, r, left);
3695 outs() << " (protocol_t entends past the end of the section)\n";
3697 memcpy(&pc, r, sizeof(struct protocol32_t));
3698 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3700 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3701 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3702 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3703 if (name != nullptr)
3704 outs() << format(" %.*s", left, name);
3706 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3707 outs() << "\t\t instanceMethods "
3708 << format("0x%" PRIx32, pc.instanceMethods)
3709 << " (struct method_list_t *)\n";
3710 if (pc.instanceMethods != 0)
3711 print_method_list32_t(pc.instanceMethods, info, "\t");
3712 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3713 << " (struct method_list_t *)\n";
3714 if (pc.classMethods != 0)
3715 print_method_list32_t(pc.classMethods, info, "\t");
3716 outs() << "\t optionalInstanceMethods "
3717 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3718 outs() << "\t optionalClassMethods "
3719 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3720 outs() << "\t instanceProperties "
3721 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3722 p += sizeof(uint32_t);
3723 offset += sizeof(uint32_t);
3727 static void print_indent(uint32_t indent) {
3728 for (uint32_t i = 0; i < indent;) {
3729 if (indent - i >= 8) {
3733 for (uint32_t j = i; j < indent; j++)
3740 static bool print_method_description_list(uint32_t p, uint32_t indent,
3741 struct DisassembleInfo *info) {
3742 uint32_t offset, left, xleft;
3744 struct objc_method_description_list_t mdl;
3745 struct objc_method_description_t md;
3746 const char *r, *list, *name;
3749 r = get_pointer_32(p, offset, left, S, info, true);
3754 if (left > sizeof(struct objc_method_description_list_t)) {
3755 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3757 print_indent(indent);
3758 outs() << " objc_method_description_list extends past end of the section\n";
3759 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3760 memcpy(&mdl, r, left);
3762 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3765 print_indent(indent);
3766 outs() << " count " << mdl.count << "\n";
3768 list = r + sizeof(struct objc_method_description_list_t);
3769 for (i = 0; i < mdl.count; i++) {
3770 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3771 print_indent(indent);
3772 outs() << " remaining list entries extend past the of the section\n";
3775 print_indent(indent);
3776 outs() << " list[" << i << "]\n";
3777 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3778 sizeof(struct objc_method_description_t));
3779 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3782 print_indent(indent);
3783 outs() << " name " << format("0x%08" PRIx32, md.name);
3784 if (info->verbose) {
3785 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3786 if (name != nullptr)
3787 outs() << format(" %.*s", xleft, name);
3789 outs() << " (not in an __OBJC section)";
3793 print_indent(indent);
3794 outs() << " types " << format("0x%08" PRIx32, md.types);
3795 if (info->verbose) {
3796 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3797 if (name != nullptr)
3798 outs() << format(" %.*s", xleft, name);
3800 outs() << " (not in an __OBJC section)";
3807 static bool print_protocol_list(uint32_t p, uint32_t indent,
3808 struct DisassembleInfo *info);
3810 static bool print_protocol(uint32_t p, uint32_t indent,
3811 struct DisassembleInfo *info) {
3812 uint32_t offset, left;
3814 struct objc_protocol_t protocol;
3815 const char *r, *name;
3817 r = get_pointer_32(p, offset, left, S, info, true);
3822 if (left >= sizeof(struct objc_protocol_t)) {
3823 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3825 print_indent(indent);
3826 outs() << " Protocol extends past end of the section\n";
3827 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3828 memcpy(&protocol, r, left);
3830 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3831 swapStruct(protocol);
3833 print_indent(indent);
3834 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3837 print_indent(indent);
3838 outs() << " protocol_name "
3839 << format("0x%08" PRIx32, protocol.protocol_name);
3840 if (info->verbose) {
3841 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3842 if (name != nullptr)
3843 outs() << format(" %.*s", left, name);
3845 outs() << " (not in an __OBJC section)";
3849 print_indent(indent);
3850 outs() << " protocol_list "
3851 << format("0x%08" PRIx32, protocol.protocol_list);
3852 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3853 outs() << " (not in an __OBJC section)\n";
3855 print_indent(indent);
3856 outs() << " instance_methods "
3857 << format("0x%08" PRIx32, protocol.instance_methods);
3858 if (print_method_description_list(protocol.instance_methods, indent, info))
3859 outs() << " (not in an __OBJC section)\n";
3861 print_indent(indent);
3862 outs() << " class_methods "
3863 << format("0x%08" PRIx32, protocol.class_methods);
3864 if (print_method_description_list(protocol.class_methods, indent, info))
3865 outs() << " (not in an __OBJC section)\n";
3870 static bool print_protocol_list(uint32_t p, uint32_t indent,
3871 struct DisassembleInfo *info) {
3872 uint32_t offset, left, l;
3874 struct objc_protocol_list_t protocol_list;
3875 const char *r, *list;
3878 r = get_pointer_32(p, offset, left, S, info, true);
3883 if (left > sizeof(struct objc_protocol_list_t)) {
3884 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3886 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3887 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3888 memcpy(&protocol_list, r, left);
3890 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3891 swapStruct(protocol_list);
3893 print_indent(indent);
3894 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3896 print_indent(indent);
3897 outs() << " count " << protocol_list.count << "\n";
3899 list = r + sizeof(struct objc_protocol_list_t);
3900 for (i = 0; i < protocol_list.count; i++) {
3901 if ((i + 1) * sizeof(uint32_t) > left) {
3902 outs() << "\t\t remaining list entries extend past the of the section\n";
3905 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3906 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3907 sys::swapByteOrder(l);
3909 print_indent(indent);
3910 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3911 if (print_protocol(l, indent, info))
3912 outs() << "(not in an __OBJC section)\n";
3917 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3918 struct ivar_list64_t il;
3921 uint32_t offset, xoffset, left, j;
3923 const char *name, *sym_name, *ivar_offset_p;
3924 uint64_t ivar_offset, n_value;
3926 r = get_pointer_64(p, offset, left, S, info);
3929 memset(&il, '\0', sizeof(struct ivar_list64_t));
3930 if (left < sizeof(struct ivar_list64_t)) {
3931 memcpy(&il, r, left);
3932 outs() << " (ivar_list_t entends past the end of the section)\n";
3934 memcpy(&il, r, sizeof(struct ivar_list64_t));
3935 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3937 outs() << " entsize " << il.entsize << "\n";
3938 outs() << " count " << il.count << "\n";
3940 p += sizeof(struct ivar_list64_t);
3941 offset += sizeof(struct ivar_list64_t);
3942 for (j = 0; j < il.count; j++) {
3943 r = get_pointer_64(p, offset, left, S, info);
3946 memset(&i, '\0', sizeof(struct ivar64_t));
3947 if (left < sizeof(struct ivar64_t)) {
3948 memcpy(&i, r, left);
3949 outs() << " (ivar_t entends past the end of the section)\n";
3951 memcpy(&i, r, sizeof(struct ivar64_t));
3952 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3955 outs() << "\t\t\t offset ";
3956 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3957 info, n_value, i.offset);
3959 if (info->verbose && sym_name != nullptr)
3962 outs() << format("0x%" PRIx64, n_value);
3964 outs() << " + " << format("0x%" PRIx64, i.offset);
3966 outs() << format("0x%" PRIx64, i.offset);
3967 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3968 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3969 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3970 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3971 sys::swapByteOrder(ivar_offset);
3972 outs() << " " << ivar_offset << "\n";
3976 outs() << "\t\t\t name ";
3977 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
3980 if (info->verbose && sym_name != nullptr)
3983 outs() << format("0x%" PRIx64, n_value);
3985 outs() << " + " << format("0x%" PRIx64, i.name);
3987 outs() << format("0x%" PRIx64, i.name);
3988 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
3989 if (name != nullptr)
3990 outs() << format(" %.*s", left, name);
3993 outs() << "\t\t\t type ";
3994 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
3996 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
3998 if (info->verbose && sym_name != nullptr)
4001 outs() << format("0x%" PRIx64, n_value);
4003 outs() << " + " << format("0x%" PRIx64, i.type);
4005 outs() << format("0x%" PRIx64, i.type);
4006 if (name != nullptr)
4007 outs() << format(" %.*s", left, name);
4010 outs() << "\t\t\talignment " << i.alignment << "\n";
4011 outs() << "\t\t\t size " << i.size << "\n";
4013 p += sizeof(struct ivar64_t);
4014 offset += sizeof(struct ivar64_t);
4018 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4019 struct ivar_list32_t il;
4022 uint32_t offset, xoffset, left, j;
4024 const char *name, *ivar_offset_p;
4025 uint32_t ivar_offset;
4027 r = get_pointer_32(p, offset, left, S, info);
4030 memset(&il, '\0', sizeof(struct ivar_list32_t));
4031 if (left < sizeof(struct ivar_list32_t)) {
4032 memcpy(&il, r, left);
4033 outs() << " (ivar_list_t entends past the end of the section)\n";
4035 memcpy(&il, r, sizeof(struct ivar_list32_t));
4036 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4038 outs() << " entsize " << il.entsize << "\n";
4039 outs() << " count " << il.count << "\n";
4041 p += sizeof(struct ivar_list32_t);
4042 offset += sizeof(struct ivar_list32_t);
4043 for (j = 0; j < il.count; j++) {
4044 r = get_pointer_32(p, offset, left, S, info);
4047 memset(&i, '\0', sizeof(struct ivar32_t));
4048 if (left < sizeof(struct ivar32_t)) {
4049 memcpy(&i, r, left);
4050 outs() << " (ivar_t entends past the end of the section)\n";
4052 memcpy(&i, r, sizeof(struct ivar32_t));
4053 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4056 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4057 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4058 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4059 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4060 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4061 sys::swapByteOrder(ivar_offset);
4062 outs() << " " << ivar_offset << "\n";
4066 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4067 name = get_pointer_32(i.name, xoffset, left, xS, info);
4068 if (name != nullptr)
4069 outs() << format(" %.*s", left, name);
4072 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4073 name = get_pointer_32(i.type, xoffset, left, xS, info);
4074 if (name != nullptr)
4075 outs() << format(" %.*s", left, name);
4078 outs() << "\t\t\talignment " << i.alignment << "\n";
4079 outs() << "\t\t\t size " << i.size << "\n";
4081 p += sizeof(struct ivar32_t);
4082 offset += sizeof(struct ivar32_t);
4086 static void print_objc_property_list64(uint64_t p,
4087 struct DisassembleInfo *info) {
4088 struct objc_property_list64 opl;
4089 struct objc_property64 op;
4091 uint32_t offset, xoffset, left, j;
4093 const char *name, *sym_name;
4096 r = get_pointer_64(p, offset, left, S, info);
4099 memset(&opl, '\0', sizeof(struct objc_property_list64));
4100 if (left < sizeof(struct objc_property_list64)) {
4101 memcpy(&opl, r, left);
4102 outs() << " (objc_property_list entends past the end of the section)\n";
4104 memcpy(&opl, r, sizeof(struct objc_property_list64));
4105 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4107 outs() << " entsize " << opl.entsize << "\n";
4108 outs() << " count " << opl.count << "\n";
4110 p += sizeof(struct objc_property_list64);
4111 offset += sizeof(struct objc_property_list64);
4112 for (j = 0; j < opl.count; j++) {
4113 r = get_pointer_64(p, offset, left, S, info);
4116 memset(&op, '\0', sizeof(struct objc_property64));
4117 if (left < sizeof(struct objc_property64)) {
4118 memcpy(&op, r, left);
4119 outs() << " (objc_property entends past the end of the section)\n";
4121 memcpy(&op, r, sizeof(struct objc_property64));
4122 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4125 outs() << "\t\t\t name ";
4126 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4127 info, n_value, op.name);
4129 if (info->verbose && sym_name != nullptr)
4132 outs() << format("0x%" PRIx64, n_value);
4134 outs() << " + " << format("0x%" PRIx64, op.name);
4136 outs() << format("0x%" PRIx64, op.name);
4137 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4138 if (name != nullptr)
4139 outs() << format(" %.*s", left, name);
4142 outs() << "\t\t\tattributes ";
4144 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4145 info, n_value, op.attributes);
4147 if (info->verbose && sym_name != nullptr)
4150 outs() << format("0x%" PRIx64, n_value);
4151 if (op.attributes != 0)
4152 outs() << " + " << format("0x%" PRIx64, op.attributes);
4154 outs() << format("0x%" PRIx64, op.attributes);
4155 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4156 if (name != nullptr)
4157 outs() << format(" %.*s", left, name);
4160 p += sizeof(struct objc_property64);
4161 offset += sizeof(struct objc_property64);
4165 static void print_objc_property_list32(uint32_t p,
4166 struct DisassembleInfo *info) {
4167 struct objc_property_list32 opl;
4168 struct objc_property32 op;
4170 uint32_t offset, xoffset, left, j;
4174 r = get_pointer_32(p, offset, left, S, info);
4177 memset(&opl, '\0', sizeof(struct objc_property_list32));
4178 if (left < sizeof(struct objc_property_list32)) {
4179 memcpy(&opl, r, left);
4180 outs() << " (objc_property_list entends past the end of the section)\n";
4182 memcpy(&opl, r, sizeof(struct objc_property_list32));
4183 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4185 outs() << " entsize " << opl.entsize << "\n";
4186 outs() << " count " << opl.count << "\n";
4188 p += sizeof(struct objc_property_list32);
4189 offset += sizeof(struct objc_property_list32);
4190 for (j = 0; j < opl.count; j++) {
4191 r = get_pointer_32(p, offset, left, S, info);
4194 memset(&op, '\0', sizeof(struct objc_property32));
4195 if (left < sizeof(struct objc_property32)) {
4196 memcpy(&op, r, left);
4197 outs() << " (objc_property entends past the end of the section)\n";
4199 memcpy(&op, r, sizeof(struct objc_property32));
4200 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4203 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4204 name = get_pointer_32(op.name, xoffset, left, xS, info);
4205 if (name != nullptr)
4206 outs() << format(" %.*s", left, name);
4209 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4210 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4211 if (name != nullptr)
4212 outs() << format(" %.*s", left, name);
4215 p += sizeof(struct objc_property32);
4216 offset += sizeof(struct objc_property32);
4220 static void print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
4221 bool &is_meta_class) {
4222 struct class_ro64_t cro;
4224 uint32_t offset, xoffset, left;
4226 const char *name, *sym_name;
4229 r = get_pointer_64(p, offset, left, S, info);
4230 if (r == nullptr || left < sizeof(struct class_ro64_t))
4232 memset(&cro, '\0', sizeof(struct class_ro64_t));
4233 if (left < sizeof(struct class_ro64_t)) {
4234 memcpy(&cro, r, left);
4235 outs() << " (class_ro_t entends past the end of the section)\n";
4237 memcpy(&cro, r, sizeof(struct class_ro64_t));
4238 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4240 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4241 if (cro.flags & RO_META)
4242 outs() << " RO_META";
4243 if (cro.flags & RO_ROOT)
4244 outs() << " RO_ROOT";
4245 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4246 outs() << " RO_HAS_CXX_STRUCTORS";
4248 outs() << " instanceStart " << cro.instanceStart << "\n";
4249 outs() << " instanceSize " << cro.instanceSize << "\n";
4250 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4252 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4254 print_layout_map64(cro.ivarLayout, info);
4257 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4258 info, n_value, cro.name);
4260 if (info->verbose && sym_name != nullptr)
4263 outs() << format("0x%" PRIx64, n_value);
4265 outs() << " + " << format("0x%" PRIx64, cro.name);
4267 outs() << format("0x%" PRIx64, cro.name);
4268 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4269 if (name != nullptr)
4270 outs() << format(" %.*s", left, name);
4273 outs() << " baseMethods ";
4274 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4275 S, info, n_value, cro.baseMethods);
4277 if (info->verbose && sym_name != nullptr)
4280 outs() << format("0x%" PRIx64, n_value);
4281 if (cro.baseMethods != 0)
4282 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4284 outs() << format("0x%" PRIx64, cro.baseMethods);
4285 outs() << " (struct method_list_t *)\n";
4286 if (cro.baseMethods + n_value != 0)
4287 print_method_list64_t(cro.baseMethods + n_value, info, "");
4289 outs() << " baseProtocols ";
4291 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4292 info, n_value, cro.baseProtocols);
4294 if (info->verbose && sym_name != nullptr)
4297 outs() << format("0x%" PRIx64, n_value);
4298 if (cro.baseProtocols != 0)
4299 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4301 outs() << format("0x%" PRIx64, cro.baseProtocols);
4303 if (cro.baseProtocols + n_value != 0)
4304 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4306 outs() << " ivars ";
4307 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
4308 info, n_value, cro.ivars);
4310 if (info->verbose && sym_name != nullptr)
4313 outs() << format("0x%" PRIx64, n_value);
4315 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4317 outs() << format("0x%" PRIx64, cro.ivars);
4319 if (cro.ivars + n_value != 0)
4320 print_ivar_list64_t(cro.ivars + n_value, info);
4322 outs() << " weakIvarLayout ";
4324 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4325 info, n_value, cro.weakIvarLayout);
4327 if (info->verbose && sym_name != nullptr)
4330 outs() << format("0x%" PRIx64, n_value);
4331 if (cro.weakIvarLayout != 0)
4332 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4334 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4336 print_layout_map64(cro.weakIvarLayout + n_value, info);
4338 outs() << " baseProperties ";
4340 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4341 info, n_value, cro.baseProperties);
4343 if (info->verbose && sym_name != nullptr)
4346 outs() << format("0x%" PRIx64, n_value);
4347 if (cro.baseProperties != 0)
4348 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4350 outs() << format("0x%" PRIx64, cro.baseProperties);
4352 if (cro.baseProperties + n_value != 0)
4353 print_objc_property_list64(cro.baseProperties + n_value, info);
4355 is_meta_class = (cro.flags & RO_META) ? true : false;
4358 static void print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
4359 bool &is_meta_class) {
4360 struct class_ro32_t cro;
4362 uint32_t offset, xoffset, left;
4366 r = get_pointer_32(p, offset, left, S, info);
4369 memset(&cro, '\0', sizeof(struct class_ro32_t));
4370 if (left < sizeof(struct class_ro32_t)) {
4371 memcpy(&cro, r, left);
4372 outs() << " (class_ro_t entends past the end of the section)\n";
4374 memcpy(&cro, r, sizeof(struct class_ro32_t));
4375 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4377 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4378 if (cro.flags & RO_META)
4379 outs() << " RO_META";
4380 if (cro.flags & RO_ROOT)
4381 outs() << " RO_ROOT";
4382 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4383 outs() << " RO_HAS_CXX_STRUCTORS";
4385 outs() << " instanceStart " << cro.instanceStart << "\n";
4386 outs() << " instanceSize " << cro.instanceSize << "\n";
4387 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4389 print_layout_map32(cro.ivarLayout, info);
4391 outs() << " name " << format("0x%" PRIx32, cro.name);
4392 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4393 if (name != nullptr)
4394 outs() << format(" %.*s", left, name);
4397 outs() << " baseMethods "
4398 << format("0x%" PRIx32, cro.baseMethods)
4399 << " (struct method_list_t *)\n";
4400 if (cro.baseMethods != 0)
4401 print_method_list32_t(cro.baseMethods, info, "");
4403 outs() << " baseProtocols "
4404 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4405 if (cro.baseProtocols != 0)
4406 print_protocol_list32_t(cro.baseProtocols, info);
4407 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4410 print_ivar_list32_t(cro.ivars, info);
4411 outs() << " weakIvarLayout "
4412 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4413 print_layout_map32(cro.weakIvarLayout, info);
4414 outs() << " baseProperties "
4415 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4416 if (cro.baseProperties != 0)
4417 print_objc_property_list32(cro.baseProperties, info);
4418 is_meta_class = (cro.flags & RO_META) ? true : false;
4421 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4424 uint32_t offset, left;
4427 uint64_t isa_n_value, n_value;
4429 r = get_pointer_64(p, offset, left, S, info);
4430 if (r == nullptr || left < sizeof(struct class64_t))
4432 memset(&c, '\0', sizeof(struct class64_t));
4433 if (left < sizeof(struct class64_t)) {
4434 memcpy(&c, r, left);
4435 outs() << " (class_t entends past the end of the section)\n";
4437 memcpy(&c, r, sizeof(struct class64_t));
4438 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4441 outs() << " isa " << format("0x%" PRIx64, c.isa);
4442 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4443 isa_n_value, c.isa);
4444 if (name != nullptr)
4445 outs() << " " << name;
4448 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4449 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4450 n_value, c.superclass);
4451 if (name != nullptr)
4452 outs() << " " << name;
4455 outs() << " cache " << format("0x%" PRIx64, c.cache);
4456 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4458 if (name != nullptr)
4459 outs() << " " << name;
4462 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4463 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4465 if (name != nullptr)
4466 outs() << " " << name;
4469 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4473 if (info->verbose && name != nullptr)
4476 outs() << format("0x%" PRIx64, n_value);
4478 outs() << " + " << format("0x%" PRIx64, c.data);
4480 outs() << format("0x%" PRIx64, c.data);
4481 outs() << " (struct class_ro_t *)";
4483 // This is a Swift class if some of the low bits of the pointer are set.
4484 if ((c.data + n_value) & 0x7)
4485 outs() << " Swift class";
4488 print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class);
4490 if (is_meta_class == false) {
4491 outs() << "Meta Class\n";
4492 print_class64_t(c.isa + isa_n_value, info);
4496 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4499 uint32_t offset, left;
4503 r = get_pointer_32(p, offset, left, S, info);
4506 memset(&c, '\0', sizeof(struct class32_t));
4507 if (left < sizeof(struct class32_t)) {
4508 memcpy(&c, r, left);
4509 outs() << " (class_t entends past the end of the section)\n";
4511 memcpy(&c, r, sizeof(struct class32_t));
4512 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4515 outs() << " isa " << format("0x%" PRIx32, c.isa);
4517 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4518 if (name != nullptr)
4519 outs() << " " << name;
4522 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4523 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4525 if (name != nullptr)
4526 outs() << " " << name;
4529 outs() << " cache " << format("0x%" PRIx32, c.cache);
4530 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4532 if (name != nullptr)
4533 outs() << " " << name;
4536 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4537 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4539 if (name != nullptr)
4540 outs() << " " << name;
4544 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4545 outs() << " data " << format("0x%" PRIx32, c.data)
4546 << " (struct class_ro_t *)";
4548 // This is a Swift class if some of the low bits of the pointer are set.
4550 outs() << " Swift class";
4553 print_class_ro32_t(c.data & ~0x3, info, is_meta_class);
4555 if (is_meta_class == false) {
4556 outs() << "Meta Class\n";
4557 print_class32_t(c.isa, info);
4561 static void print_objc_class_t(struct objc_class_t *objc_class,
4562 struct DisassembleInfo *info) {
4563 uint32_t offset, left, xleft;
4564 const char *name, *p, *ivar_list;
4567 struct objc_ivar_list_t objc_ivar_list;
4568 struct objc_ivar_t ivar;
4570 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4571 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4572 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4573 if (name != nullptr)
4574 outs() << format(" %.*s", left, name);
4576 outs() << " (not in an __OBJC section)";
4580 outs() << "\t super_class "
4581 << format("0x%08" PRIx32, objc_class->super_class);
4582 if (info->verbose) {
4583 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4584 if (name != nullptr)
4585 outs() << format(" %.*s", left, name);
4587 outs() << " (not in an __OBJC section)";
4591 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4592 if (info->verbose) {
4593 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4594 if (name != nullptr)
4595 outs() << format(" %.*s", left, name);
4597 outs() << " (not in an __OBJC section)";
4601 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4604 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4605 if (info->verbose) {
4606 if (CLS_GETINFO(objc_class, CLS_CLASS))
4607 outs() << " CLS_CLASS";
4608 else if (CLS_GETINFO(objc_class, CLS_META))
4609 outs() << " CLS_META";
4613 outs() << "\t instance_size "
4614 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4616 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4617 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4619 if (left > sizeof(struct objc_ivar_list_t)) {
4621 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4623 outs() << " (entends past the end of the section)\n";
4624 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4625 memcpy(&objc_ivar_list, p, left);
4627 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4628 swapStruct(objc_ivar_list);
4629 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4630 ivar_list = p + sizeof(struct objc_ivar_list_t);
4631 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4632 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4633 outs() << "\t\t remaining ivar's extend past the of the section\n";
4636 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4637 sizeof(struct objc_ivar_t));
4638 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4641 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4642 if (info->verbose) {
4643 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4644 if (name != nullptr)
4645 outs() << format(" %.*s", xleft, name);
4647 outs() << " (not in an __OBJC section)";
4651 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4652 if (info->verbose) {
4653 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4654 if (name != nullptr)
4655 outs() << format(" %.*s", xleft, name);
4657 outs() << " (not in an __OBJC section)";
4661 outs() << "\t\t ivar_offset "
4662 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4665 outs() << " (not in an __OBJC section)\n";
4668 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4669 if (print_method_list(objc_class->methodLists, info))
4670 outs() << " (not in an __OBJC section)\n";
4672 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4675 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4676 if (print_protocol_list(objc_class->protocols, 16, info))
4677 outs() << " (not in an __OBJC section)\n";
4680 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4681 struct DisassembleInfo *info) {
4682 uint32_t offset, left;
4686 outs() << "\t category name "
4687 << format("0x%08" PRIx32, objc_category->category_name);
4688 if (info->verbose) {
4689 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4691 if (name != nullptr)
4692 outs() << format(" %.*s", left, name);
4694 outs() << " (not in an __OBJC section)";
4698 outs() << "\t\t class name "
4699 << format("0x%08" PRIx32, objc_category->class_name);
4700 if (info->verbose) {
4702 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4703 if (name != nullptr)
4704 outs() << format(" %.*s", left, name);
4706 outs() << " (not in an __OBJC section)";
4710 outs() << "\t instance methods "
4711 << format("0x%08" PRIx32, objc_category->instance_methods);
4712 if (print_method_list(objc_category->instance_methods, info))
4713 outs() << " (not in an __OBJC section)\n";
4715 outs() << "\t class methods "
4716 << format("0x%08" PRIx32, objc_category->class_methods);
4717 if (print_method_list(objc_category->class_methods, info))
4718 outs() << " (not in an __OBJC section)\n";
4721 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4722 struct category64_t c;
4724 uint32_t offset, xoffset, left;
4726 const char *name, *sym_name;
4729 r = get_pointer_64(p, offset, left, S, info);
4732 memset(&c, '\0', sizeof(struct category64_t));
4733 if (left < sizeof(struct category64_t)) {
4734 memcpy(&c, r, left);
4735 outs() << " (category_t entends past the end of the section)\n";
4737 memcpy(&c, r, sizeof(struct category64_t));
4738 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4742 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4743 info, n_value, c.name);
4745 if (info->verbose && sym_name != nullptr)
4748 outs() << format("0x%" PRIx64, n_value);
4750 outs() << " + " << format("0x%" PRIx64, c.name);
4752 outs() << format("0x%" PRIx64, c.name);
4753 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4754 if (name != nullptr)
4755 outs() << format(" %.*s", left, name);
4759 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4762 if (info->verbose && sym_name != nullptr)
4765 outs() << format("0x%" PRIx64, n_value);
4767 outs() << " + " << format("0x%" PRIx64, c.cls);
4769 outs() << format("0x%" PRIx64, c.cls);
4771 if (c.cls + n_value != 0)
4772 print_class64_t(c.cls + n_value, info);
4774 outs() << " instanceMethods ";
4776 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4777 info, n_value, c.instanceMethods);
4779 if (info->verbose && sym_name != nullptr)
4782 outs() << format("0x%" PRIx64, n_value);
4783 if (c.instanceMethods != 0)
4784 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4786 outs() << format("0x%" PRIx64, c.instanceMethods);
4788 if (c.instanceMethods + n_value != 0)
4789 print_method_list64_t(c.instanceMethods + n_value, info, "");
4791 outs() << " classMethods ";
4792 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4793 S, info, n_value, c.classMethods);
4795 if (info->verbose && sym_name != nullptr)
4798 outs() << format("0x%" PRIx64, n_value);
4799 if (c.classMethods != 0)
4800 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4802 outs() << format("0x%" PRIx64, c.classMethods);
4804 if (c.classMethods + n_value != 0)
4805 print_method_list64_t(c.classMethods + n_value, info, "");
4807 outs() << " protocols ";
4808 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4809 info, n_value, c.protocols);
4811 if (info->verbose && sym_name != nullptr)
4814 outs() << format("0x%" PRIx64, n_value);
4815 if (c.protocols != 0)
4816 outs() << " + " << format("0x%" PRIx64, c.protocols);
4818 outs() << format("0x%" PRIx64, c.protocols);
4820 if (c.protocols + n_value != 0)
4821 print_protocol_list64_t(c.protocols + n_value, info);
4823 outs() << "instanceProperties ";
4825 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4826 S, info, n_value, c.instanceProperties);
4828 if (info->verbose && sym_name != nullptr)
4831 outs() << format("0x%" PRIx64, n_value);
4832 if (c.instanceProperties != 0)
4833 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4835 outs() << format("0x%" PRIx64, c.instanceProperties);
4837 if (c.instanceProperties + n_value != 0)
4838 print_objc_property_list64(c.instanceProperties + n_value, info);
4841 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4842 struct category32_t c;
4844 uint32_t offset, left;
4848 r = get_pointer_32(p, offset, left, S, info);
4851 memset(&c, '\0', sizeof(struct category32_t));
4852 if (left < sizeof(struct category32_t)) {
4853 memcpy(&c, r, left);
4854 outs() << " (category_t entends past the end of the section)\n";
4856 memcpy(&c, r, sizeof(struct category32_t));
4857 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4860 outs() << " name " << format("0x%" PRIx32, c.name);
4861 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4864 outs() << " " << name;
4867 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4869 print_class32_t(c.cls, info);
4870 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4872 if (c.instanceMethods != 0)
4873 print_method_list32_t(c.instanceMethods, info, "");
4874 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4876 if (c.classMethods != 0)
4877 print_method_list32_t(c.classMethods, info, "");
4878 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4879 if (c.protocols != 0)
4880 print_protocol_list32_t(c.protocols, info);
4881 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4883 if (c.instanceProperties != 0)
4884 print_objc_property_list32(c.instanceProperties, info);
4887 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4888 uint32_t i, left, offset, xoffset;
4889 uint64_t p, n_value;
4890 struct message_ref64 mr;
4891 const char *name, *sym_name;
4895 if (S == SectionRef())
4899 S.getName(SectName);
4900 DataRefImpl Ref = S.getRawDataRefImpl();
4901 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4902 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4904 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4905 p = S.getAddress() + i;
4906 r = get_pointer_64(p, offset, left, S, info);
4909 memset(&mr, '\0', sizeof(struct message_ref64));
4910 if (left < sizeof(struct message_ref64)) {
4911 memcpy(&mr, r, left);
4912 outs() << " (message_ref entends past the end of the section)\n";
4914 memcpy(&mr, r, sizeof(struct message_ref64));
4915 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4919 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4922 outs() << format("0x%" PRIx64, n_value) << " ";
4924 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4926 outs() << format("0x%" PRIx64, mr.imp) << " ";
4927 if (name != nullptr)
4928 outs() << " " << name;
4932 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4933 info, n_value, mr.sel);
4935 if (info->verbose && sym_name != nullptr)
4938 outs() << format("0x%" PRIx64, n_value);
4940 outs() << " + " << format("0x%" PRIx64, mr.sel);
4942 outs() << format("0x%" PRIx64, mr.sel);
4943 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4944 if (name != nullptr)
4945 outs() << format(" %.*s", left, name);
4948 offset += sizeof(struct message_ref64);
4952 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
4953 uint32_t i, left, offset, xoffset, p;
4954 struct message_ref32 mr;
4955 const char *name, *r;
4958 if (S == SectionRef())
4962 S.getName(SectName);
4963 DataRefImpl Ref = S.getRawDataRefImpl();
4964 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4965 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4967 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4968 p = S.getAddress() + i;
4969 r = get_pointer_32(p, offset, left, S, info);
4972 memset(&mr, '\0', sizeof(struct message_ref32));
4973 if (left < sizeof(struct message_ref32)) {
4974 memcpy(&mr, r, left);
4975 outs() << " (message_ref entends past the end of the section)\n";
4977 memcpy(&mr, r, sizeof(struct message_ref32));
4978 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4981 outs() << " imp " << format("0x%" PRIx32, mr.imp);
4982 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
4984 if (name != nullptr)
4985 outs() << " " << name;
4988 outs() << " sel " << format("0x%" PRIx32, mr.sel);
4989 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
4990 if (name != nullptr)
4991 outs() << " " << name;
4994 offset += sizeof(struct message_ref32);
4998 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
4999 uint32_t left, offset, swift_version;
5001 struct objc_image_info64 o;
5005 S.getName(SectName);
5006 DataRefImpl Ref = S.getRawDataRefImpl();
5007 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5008 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5010 r = get_pointer_64(p, offset, left, S, info);
5013 memset(&o, '\0', sizeof(struct objc_image_info64));
5014 if (left < sizeof(struct objc_image_info64)) {
5015 memcpy(&o, r, left);
5016 outs() << " (objc_image_info entends past the end of the section)\n";
5018 memcpy(&o, r, sizeof(struct objc_image_info64));
5019 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5021 outs() << " version " << o.version << "\n";
5022 outs() << " flags " << format("0x%" PRIx32, o.flags);
5023 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5024 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5025 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5026 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5027 swift_version = (o.flags >> 8) & 0xff;
5028 if (swift_version != 0) {
5029 if (swift_version == 1)
5030 outs() << " Swift 1.0";
5031 else if (swift_version == 2)
5032 outs() << " Swift 1.1";
5034 outs() << " unknown future Swift version (" << swift_version << ")";
5039 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5040 uint32_t left, offset, swift_version, p;
5041 struct objc_image_info32 o;
5045 S.getName(SectName);
5046 DataRefImpl Ref = S.getRawDataRefImpl();
5047 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5048 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5050 r = get_pointer_32(p, offset, left, S, info);
5053 memset(&o, '\0', sizeof(struct objc_image_info32));
5054 if (left < sizeof(struct objc_image_info32)) {
5055 memcpy(&o, r, left);
5056 outs() << " (objc_image_info entends past the end of the section)\n";
5058 memcpy(&o, r, sizeof(struct objc_image_info32));
5059 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5061 outs() << " version " << o.version << "\n";
5062 outs() << " flags " << format("0x%" PRIx32, o.flags);
5063 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5064 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5065 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5066 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5067 swift_version = (o.flags >> 8) & 0xff;
5068 if (swift_version != 0) {
5069 if (swift_version == 1)
5070 outs() << " Swift 1.0";
5071 else if (swift_version == 2)
5072 outs() << " Swift 1.1";
5074 outs() << " unknown future Swift version (" << swift_version << ")";
5079 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5080 uint32_t left, offset, p;
5081 struct imageInfo_t o;
5085 S.getName(SectName);
5086 DataRefImpl Ref = S.getRawDataRefImpl();
5087 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5088 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5090 r = get_pointer_32(p, offset, left, S, info);
5093 memset(&o, '\0', sizeof(struct imageInfo_t));
5094 if (left < sizeof(struct imageInfo_t)) {
5095 memcpy(&o, r, left);
5096 outs() << " (imageInfo entends past the end of the section)\n";
5098 memcpy(&o, r, sizeof(struct imageInfo_t));
5099 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5101 outs() << " version " << o.version << "\n";
5102 outs() << " flags " << format("0x%" PRIx32, o.flags);
5108 outs() << " GC-only";
5114 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5115 SymbolAddressMap AddrMap;
5117 CreateSymbolAddressMap(O, &AddrMap);
5119 std::vector<SectionRef> Sections;
5120 for (const SectionRef &Section : O->sections()) {
5122 Section.getName(SectName);
5123 Sections.push_back(Section);
5126 struct DisassembleInfo info;
5127 // Set up the block of info used by the Symbolizer call backs.
5128 info.verbose = verbose;
5130 info.AddrMap = &AddrMap;
5131 info.Sections = &Sections;
5132 info.class_name = nullptr;
5133 info.selector_name = nullptr;
5134 info.method = nullptr;
5135 info.demangled_name = nullptr;
5136 info.bindtable = nullptr;
5140 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5141 if (CL != SectionRef()) {
5143 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5145 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5147 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5150 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5151 if (CR != SectionRef()) {
5153 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5155 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5157 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5160 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5161 if (SR != SectionRef()) {
5163 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5165 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5167 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5170 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5171 if (CA != SectionRef()) {
5173 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5175 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5177 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5180 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5181 if (PL != SectionRef()) {
5183 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5185 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5187 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5190 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5191 if (MR != SectionRef()) {
5193 print_message_refs64(MR, &info);
5195 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5197 print_message_refs64(MR, &info);
5200 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5201 if (II != SectionRef()) {
5203 print_image_info64(II, &info);
5205 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5207 print_image_info64(II, &info);
5210 if (info.bindtable != nullptr)
5211 delete info.bindtable;
5214 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5215 SymbolAddressMap AddrMap;
5217 CreateSymbolAddressMap(O, &AddrMap);
5219 std::vector<SectionRef> Sections;
5220 for (const SectionRef &Section : O->sections()) {
5222 Section.getName(SectName);
5223 Sections.push_back(Section);
5226 struct DisassembleInfo info;
5227 // Set up the block of info used by the Symbolizer call backs.
5228 info.verbose = verbose;
5230 info.AddrMap = &AddrMap;
5231 info.Sections = &Sections;
5232 info.class_name = nullptr;
5233 info.selector_name = nullptr;
5234 info.method = nullptr;
5235 info.demangled_name = nullptr;
5236 info.bindtable = nullptr;
5240 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5241 if (CL != SectionRef()) {
5243 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5245 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5247 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5250 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5251 if (CR != SectionRef()) {
5253 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5255 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5257 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5260 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5261 if (SR != SectionRef()) {
5263 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5265 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5267 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5270 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5271 if (CA != SectionRef()) {
5273 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5275 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5277 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5280 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5281 if (PL != SectionRef()) {
5283 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5285 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5287 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5290 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5291 if (MR != SectionRef()) {
5293 print_message_refs32(MR, &info);
5295 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5297 print_message_refs32(MR, &info);
5300 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5301 if (II != SectionRef()) {
5303 print_image_info32(II, &info);
5305 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5307 print_image_info32(II, &info);
5311 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5312 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5313 const char *r, *name, *defs;
5314 struct objc_module_t module;
5316 struct objc_symtab_t symtab;
5317 struct objc_class_t objc_class;
5318 struct objc_category_t objc_category;
5320 outs() << "Objective-C segment\n";
5321 S = get_section(O, "__OBJC", "__module_info");
5322 if (S == SectionRef())
5325 SymbolAddressMap AddrMap;
5327 CreateSymbolAddressMap(O, &AddrMap);
5329 std::vector<SectionRef> Sections;
5330 for (const SectionRef &Section : O->sections()) {
5332 Section.getName(SectName);
5333 Sections.push_back(Section);
5336 struct DisassembleInfo info;
5337 // Set up the block of info used by the Symbolizer call backs.
5338 info.verbose = verbose;
5340 info.AddrMap = &AddrMap;
5341 info.Sections = &Sections;
5342 info.class_name = nullptr;
5343 info.selector_name = nullptr;
5344 info.method = nullptr;
5345 info.demangled_name = nullptr;
5346 info.bindtable = nullptr;
5350 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5351 p = S.getAddress() + i;
5352 r = get_pointer_32(p, offset, left, S, &info, true);
5355 memset(&module, '\0', sizeof(struct objc_module_t));
5356 if (left < sizeof(struct objc_module_t)) {
5357 memcpy(&module, r, left);
5358 outs() << " (module extends past end of __module_info section)\n";
5360 memcpy(&module, r, sizeof(struct objc_module_t));
5361 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5364 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5365 outs() << " version " << module.version << "\n";
5366 outs() << " size " << module.size << "\n";
5368 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5369 if (name != nullptr)
5370 outs() << format("%.*s", left, name);
5372 outs() << format("0x%08" PRIx32, module.name)
5373 << "(not in an __OBJC section)";
5376 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5377 if (module.symtab == 0 || r == nullptr) {
5378 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5379 << " (not in an __OBJC section)\n";
5382 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5383 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5386 if (left < sizeof(struct objc_symtab_t)) {
5387 memcpy(&symtab, r, left);
5388 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5390 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5391 if (left > sizeof(struct objc_symtab_t)) {
5392 defs_left = left - sizeof(struct objc_symtab_t);
5393 defs = r + sizeof(struct objc_symtab_t);
5396 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5399 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5400 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5401 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5403 outs() << " (not in an __OBJC section)";
5405 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5406 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5407 if (symtab.cls_def_cnt > 0)
5408 outs() << "\tClass Definitions\n";
5409 for (j = 0; j < symtab.cls_def_cnt; j++) {
5410 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5411 outs() << "\t(remaining class defs entries entends past the end of the "
5415 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5416 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5417 sys::swapByteOrder(def);
5419 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5420 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5422 if (left > sizeof(struct objc_class_t)) {
5424 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5426 outs() << " (entends past the end of the section)\n";
5427 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5428 memcpy(&objc_class, r, left);
5430 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5431 swapStruct(objc_class);
5432 print_objc_class_t(&objc_class, &info);
5434 outs() << "(not in an __OBJC section)\n";
5437 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5438 outs() << "\tMeta Class";
5439 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5441 if (left > sizeof(struct objc_class_t)) {
5443 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5445 outs() << " (entends past the end of the section)\n";
5446 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5447 memcpy(&objc_class, r, left);
5449 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5450 swapStruct(objc_class);
5451 print_objc_class_t(&objc_class, &info);
5453 outs() << "(not in an __OBJC section)\n";
5457 if (symtab.cat_def_cnt > 0)
5458 outs() << "\tCategory Definitions\n";
5459 for (j = 0; j < symtab.cat_def_cnt; j++) {
5460 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5461 outs() << "\t(remaining category defs entries entends past the end of "
5462 << "the section)\n";
5465 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5467 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5468 sys::swapByteOrder(def);
5470 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5471 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5472 << format("0x%08" PRIx32, def);
5474 if (left > sizeof(struct objc_category_t)) {
5476 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5478 outs() << " (entends past the end of the section)\n";
5479 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5480 memcpy(&objc_category, r, left);
5482 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5483 swapStruct(objc_category);
5484 print_objc_objc_category_t(&objc_category, &info);
5486 outs() << "(not in an __OBJC section)\n";
5490 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5491 if (II != SectionRef())
5492 print_image_info(II, &info);
5497 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5498 uint32_t size, uint32_t addr) {
5499 SymbolAddressMap AddrMap;
5500 CreateSymbolAddressMap(O, &AddrMap);
5502 std::vector<SectionRef> Sections;
5503 for (const SectionRef &Section : O->sections()) {
5505 Section.getName(SectName);
5506 Sections.push_back(Section);
5509 struct DisassembleInfo info;
5510 // Set up the block of info used by the Symbolizer call backs.
5511 info.verbose = true;
5513 info.AddrMap = &AddrMap;
5514 info.Sections = &Sections;
5515 info.class_name = nullptr;
5516 info.selector_name = nullptr;
5517 info.method = nullptr;
5518 info.demangled_name = nullptr;
5519 info.bindtable = nullptr;
5524 struct objc_protocol_t protocol;
5525 uint32_t left, paddr;
5526 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5527 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5528 left = size - (p - sect);
5529 if (left < sizeof(struct objc_protocol_t)) {
5530 outs() << "Protocol extends past end of __protocol section\n";
5531 memcpy(&protocol, p, left);
5533 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5534 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5535 swapStruct(protocol);
5536 paddr = addr + (p - sect);
5537 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5538 if (print_protocol(paddr, 0, &info))
5539 outs() << "(not in an __OBJC section)\n";
5543 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5545 printObjc2_64bit_MetaData(O, verbose);
5547 MachO::mach_header H;
5549 if (H.cputype == MachO::CPU_TYPE_ARM)
5550 printObjc2_32bit_MetaData(O, verbose);
5552 // This is the 32-bit non-arm cputype case. Which is normally
5553 // the first Objective-C ABI. But it may be the case of a
5554 // binary for the iOS simulator which is the second Objective-C
5555 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5556 // and return false.
5557 if (printObjc1_32bit_MetaData(O, verbose) == false)
5558 printObjc2_32bit_MetaData(O, verbose);
5563 // GuessLiteralPointer returns a string which for the item in the Mach-O file
5564 // for the address passed in as ReferenceValue for printing as a comment with
5565 // the instruction and also returns the corresponding type of that item
5566 // indirectly through ReferenceType.
5568 // If ReferenceValue is an address of literal cstring then a pointer to the
5569 // cstring is returned and ReferenceType is set to
5570 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5572 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5573 // Class ref that name is returned and the ReferenceType is set accordingly.
5575 // Lastly, literals which are Symbol address in a literal pool are looked for
5576 // and if found the symbol name is returned and ReferenceType is set to
5577 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5579 // If there is no item in the Mach-O file for the address passed in as
5580 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
5581 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5582 uint64_t ReferencePC,
5583 uint64_t *ReferenceType,
5584 struct DisassembleInfo *info) {
5585 // First see if there is an external relocation entry at the ReferencePC.
5586 uint64_t sect_addr = info->S.getAddress();
5587 uint64_t sect_offset = ReferencePC - sect_addr;
5588 bool reloc_found = false;
5590 MachO::any_relocation_info RE;
5591 bool isExtern = false;
5593 for (const RelocationRef &Reloc : info->S.relocations()) {
5594 uint64_t RelocOffset = Reloc.getOffset();
5595 if (RelocOffset == sect_offset) {
5596 Rel = Reloc.getRawDataRefImpl();
5597 RE = info->O->getRelocation(Rel);
5598 if (info->O->isRelocationScattered(RE))
5600 isExtern = info->O->getPlainRelocationExternal(RE);
5602 symbol_iterator RelocSym = Reloc.getSymbol();
5609 // If there is an external relocation entry for a symbol in a section
5610 // then used that symbol's value for the value of the reference.
5611 if (reloc_found && isExtern) {
5612 if (info->O->getAnyRelocationPCRel(RE)) {
5613 unsigned Type = info->O->getAnyRelocationType(RE);
5614 if (Type == MachO::X86_64_RELOC_SIGNED) {
5615 ReferenceValue = Symbol.getValue();
5620 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5621 // Message refs and Class refs.
5622 bool classref, selref, msgref, cfstring;
5623 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5624 selref, msgref, cfstring);
5625 if (classref && pointer_value == 0) {
5626 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5627 // And the pointer_value in that section is typically zero as it will be
5628 // set by dyld as part of the "bind information".
5629 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5630 if (name != nullptr) {
5631 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5632 const char *class_name = strrchr(name, '$');
5633 if (class_name != nullptr && class_name[1] == '_' &&
5634 class_name[2] != '\0') {
5635 info->class_name = class_name + 2;
5642 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5644 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5645 if (name != nullptr)
5646 info->class_name = name;
5648 name = "bad class ref";
5653 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5654 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5658 if (selref && pointer_value == 0)
5659 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5661 if (pointer_value != 0)
5662 ReferenceValue = pointer_value;
5664 const char *name = GuessCstringPointer(ReferenceValue, info);
5666 if (pointer_value != 0 && selref) {
5667 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5668 info->selector_name = name;
5669 } else if (pointer_value != 0 && msgref) {
5670 info->class_name = nullptr;
5671 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5672 info->selector_name = name;
5674 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5678 // Lastly look for an indirect symbol with this ReferenceValue which is in
5679 // a literal pool. If found return that symbol name.
5680 name = GuessIndirectSymbol(ReferenceValue, info);
5682 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5689 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
5690 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
5691 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5692 // is created and returns the symbol name that matches the ReferenceValue or
5693 // nullptr if none. The ReferenceType is passed in for the IN type of
5694 // reference the instruction is making from the values in defined in the header
5695 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5696 // Out type and the ReferenceName will also be set which is added as a comment
5697 // to the disassembled instruction.
5700 // If the symbol name is a C++ mangled name then the demangled name is
5701 // returned through ReferenceName and ReferenceType is set to
5702 // LLVMDisassembler_ReferenceType_DeMangled_Name .
5705 // When this is called to get a symbol name for a branch target then the
5706 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5707 // SymbolValue will be looked for in the indirect symbol table to determine if
5708 // it is an address for a symbol stub. If so then the symbol name for that
5709 // stub is returned indirectly through ReferenceName and then ReferenceType is
5710 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5712 // When this is called with an value loaded via a PC relative load then
5713 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5714 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
5715 // or an Objective-C meta data reference. If so the output ReferenceType is
5716 // set to correspond to that as well as setting the ReferenceName.
5717 static const char *SymbolizerSymbolLookUp(void *DisInfo,
5718 uint64_t ReferenceValue,
5719 uint64_t *ReferenceType,
5720 uint64_t ReferencePC,
5721 const char **ReferenceName) {
5722 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
5723 // If no verbose symbolic information is wanted then just return nullptr.
5724 if (!info->verbose) {
5725 *ReferenceName = nullptr;
5726 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5730 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
5732 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5733 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
5734 if (*ReferenceName != nullptr) {
5735 method_reference(info, ReferenceType, ReferenceName);
5736 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5737 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5740 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5741 if (info->demangled_name != nullptr)
5742 free(info->demangled_name);
5744 info->demangled_name =
5745 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5746 if (info->demangled_name != nullptr) {
5747 *ReferenceName = info->demangled_name;
5748 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5750 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5753 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5754 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5756 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5758 method_reference(info, ReferenceType, ReferenceName);
5760 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5761 // If this is arm64 and the reference is an adrp instruction save the
5762 // instruction, passed in ReferenceValue and the address of the instruction
5763 // for use later if we see and add immediate instruction.
5764 } else if (info->O->getArch() == Triple::aarch64 &&
5765 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5766 info->adrp_inst = ReferenceValue;
5767 info->adrp_addr = ReferencePC;
5768 SymbolName = nullptr;
5769 *ReferenceName = nullptr;
5770 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5771 // If this is arm64 and reference is an add immediate instruction and we
5773 // seen an adrp instruction just before it and the adrp's Xd register
5775 // this add's Xn register reconstruct the value being referenced and look to
5776 // see if it is a literal pointer. Note the add immediate instruction is
5777 // passed in ReferenceValue.
5778 } else if (info->O->getArch() == Triple::aarch64 &&
5779 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5780 ReferencePC - 4 == info->adrp_addr &&
5781 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5782 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5783 uint32_t addxri_inst;
5784 uint64_t adrp_imm, addxri_imm;
5787 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5788 if (info->adrp_inst & 0x0200000)
5789 adrp_imm |= 0xfffffffffc000000LL;
5791 addxri_inst = ReferenceValue;
5792 addxri_imm = (addxri_inst >> 10) & 0xfff;
5793 if (((addxri_inst >> 22) & 0x3) == 1)
5796 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5797 (adrp_imm << 12) + addxri_imm;
5800 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5801 if (*ReferenceName == nullptr)
5802 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5803 // If this is arm64 and the reference is a load register instruction and we
5804 // have seen an adrp instruction just before it and the adrp's Xd register
5805 // matches this add's Xn register reconstruct the value being referenced and
5806 // look to see if it is a literal pointer. Note the load register
5807 // instruction is passed in ReferenceValue.
5808 } else if (info->O->getArch() == Triple::aarch64 &&
5809 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5810 ReferencePC - 4 == info->adrp_addr &&
5811 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5812 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5813 uint32_t ldrxui_inst;
5814 uint64_t adrp_imm, ldrxui_imm;
5817 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5818 if (info->adrp_inst & 0x0200000)
5819 adrp_imm |= 0xfffffffffc000000LL;
5821 ldrxui_inst = ReferenceValue;
5822 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5824 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5825 (adrp_imm << 12) + (ldrxui_imm << 3);
5828 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5829 if (*ReferenceName == nullptr)
5830 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5832 // If this arm64 and is an load register (PC-relative) instruction the
5833 // ReferenceValue is the PC plus the immediate value.
5834 else if (info->O->getArch() == Triple::aarch64 &&
5835 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5836 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5838 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5839 if (*ReferenceName == nullptr)
5840 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5843 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5844 if (info->demangled_name != nullptr)
5845 free(info->demangled_name);
5847 info->demangled_name =
5848 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5849 if (info->demangled_name != nullptr) {
5850 *ReferenceName = info->demangled_name;
5851 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5856 *ReferenceName = nullptr;
5857 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5863 /// \brief Emits the comments that are stored in the CommentStream.
5864 /// Each comment in the CommentStream must end with a newline.
5865 static void emitComments(raw_svector_ostream &CommentStream,
5866 SmallString<128> &CommentsToEmit,
5867 formatted_raw_ostream &FormattedOS,
5868 const MCAsmInfo &MAI) {
5869 // Flush the stream before taking its content.
5870 CommentStream.flush();
5871 StringRef Comments = CommentsToEmit.str();
5872 // Get the default information for printing a comment.
5873 const char *CommentBegin = MAI.getCommentString();
5874 unsigned CommentColumn = MAI.getCommentColumn();
5875 bool IsFirst = true;
5876 while (!Comments.empty()) {
5878 FormattedOS << '\n';
5879 // Emit a line of comments.
5880 FormattedOS.PadToColumn(CommentColumn);
5881 size_t Position = Comments.find('\n');
5882 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5883 // Move after the newline character.
5884 Comments = Comments.substr(Position + 1);
5887 FormattedOS.flush();
5889 // Tell the comment stream that the vector changed underneath it.
5890 CommentsToEmit.clear();
5893 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5894 StringRef DisSegName, StringRef DisSectName) {
5895 const char *McpuDefault = nullptr;
5896 const Target *ThumbTarget = nullptr;
5897 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
5899 // GetTarget prints out stuff.
5902 if (MCPU.empty() && McpuDefault)
5905 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
5906 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
5908 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
5910 // Package up features to be passed to target/subtarget
5911 std::string FeaturesStr;
5912 if (MAttrs.size()) {
5913 SubtargetFeatures Features;
5914 for (unsigned i = 0; i != MAttrs.size(); ++i)
5915 Features.AddFeature(MAttrs[i]);
5916 FeaturesStr = Features.getString();
5919 // Set up disassembler.
5920 std::unique_ptr<const MCRegisterInfo> MRI(
5921 TheTarget->createMCRegInfo(TripleName));
5922 std::unique_ptr<const MCAsmInfo> AsmInfo(
5923 TheTarget->createMCAsmInfo(*MRI, TripleName));
5924 std::unique_ptr<const MCSubtargetInfo> STI(
5925 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
5926 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
5927 std::unique_ptr<MCDisassembler> DisAsm(
5928 TheTarget->createMCDisassembler(*STI, Ctx));
5929 std::unique_ptr<MCSymbolizer> Symbolizer;
5930 struct DisassembleInfo SymbolizerInfo;
5931 std::unique_ptr<MCRelocationInfo> RelInfo(
5932 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5934 Symbolizer.reset(TheTarget->createMCSymbolizer(
5935 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5936 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
5937 DisAsm->setSymbolizer(std::move(Symbolizer));
5939 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
5940 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
5941 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
5942 // Set the display preference for hex vs. decimal immediates.
5943 IP->setPrintImmHex(PrintImmHex);
5944 // Comment stream and backing vector.
5945 SmallString<128> CommentsToEmit;
5946 raw_svector_ostream CommentStream(CommentsToEmit);
5947 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5948 // if it is done then arm64 comments for string literals don't get printed
5949 // and some constant get printed instead and not setting it causes intel
5950 // (32-bit and 64-bit) comments printed with different spacing before the
5951 // comment causing different diffs with the 'C' disassembler library API.
5952 // IP->setCommentStream(CommentStream);
5954 if (!AsmInfo || !STI || !DisAsm || !IP) {
5955 errs() << "error: couldn't initialize disassembler for target "
5956 << TripleName << '\n';
5960 // Set up thumb disassembler.
5961 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5962 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5963 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
5964 std::unique_ptr<MCDisassembler> ThumbDisAsm;
5965 std::unique_ptr<MCInstPrinter> ThumbIP;
5966 std::unique_ptr<MCContext> ThumbCtx;
5967 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5968 struct DisassembleInfo ThumbSymbolizerInfo;
5969 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
5971 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
5973 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
5975 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
5976 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
5977 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
5978 MCContext *PtrThumbCtx = ThumbCtx.get();
5980 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
5982 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
5983 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5984 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
5985 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
5987 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
5988 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
5989 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
5990 *ThumbInstrInfo, *ThumbMRI));
5991 // Set the display preference for hex vs. decimal immediates.
5992 ThumbIP->setPrintImmHex(PrintImmHex);
5995 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
5996 errs() << "error: couldn't initialize disassembler for target "
5997 << ThumbTripleName << '\n';
6001 MachO::mach_header Header = MachOOF->getHeader();
6003 // FIXME: Using the -cfg command line option, this code used to be able to
6004 // annotate relocations with the referenced symbol's name, and if this was
6005 // inside a __[cf]string section, the data it points to. This is now replaced
6006 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
6007 std::vector<SectionRef> Sections;
6008 std::vector<SymbolRef> Symbols;
6009 SmallVector<uint64_t, 8> FoundFns;
6010 uint64_t BaseSegmentAddress;
6012 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
6013 BaseSegmentAddress);
6015 // Sort the symbols by address, just in case they didn't come in that way.
6016 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
6018 // Build a data in code table that is sorted on by the address of each entry.
6019 uint64_t BaseAddress = 0;
6020 if (Header.filetype == MachO::MH_OBJECT)
6021 BaseAddress = Sections[0].getAddress();
6023 BaseAddress = BaseSegmentAddress;
6025 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
6028 DI->getOffset(Offset);
6029 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6031 array_pod_sort(Dices.begin(), Dices.end());
6034 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6036 raw_ostream &DebugOut = nulls();
6039 std::unique_ptr<DIContext> diContext;
6040 ObjectFile *DbgObj = MachOOF;
6041 // Try to find debug info and set up the DIContext for it.
6043 // A separate DSym file path was specified, parse it as a macho file,
6044 // get the sections and supply it to the section name parsing machinery.
6045 if (!DSYMFile.empty()) {
6046 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
6047 MemoryBuffer::getFileOrSTDIN(DSYMFile);
6048 if (std::error_code EC = BufOrErr.getError()) {
6049 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
6053 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6058 // Setup the DIContext
6059 diContext.reset(new DWARFContextInMemory(*DbgObj));
6062 if (FilterSections.size() == 0)
6063 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
6065 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
6067 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6070 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
6072 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
6073 if (SegmentName != DisSegName)
6077 Sections[SectIdx].getContents(BytesStr);
6078 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6080 uint64_t SectAddress = Sections[SectIdx].getAddress();
6082 bool symbolTableWorked = false;
6084 // Parse relocations.
6085 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
6086 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
6087 uint64_t RelocOffset = Reloc.getOffset();
6088 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6089 RelocOffset -= SectionAddress;
6091 symbol_iterator RelocSym = Reloc.getSymbol();
6093 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
6095 array_pod_sort(Relocs.begin(), Relocs.end());
6097 // Create a map of symbol addresses to symbol names for use by
6098 // the SymbolizerSymbolLookUp() routine.
6099 SymbolAddressMap AddrMap;
6100 bool DisSymNameFound = false;
6101 for (const SymbolRef &Symbol : MachOOF->symbols()) {
6102 SymbolRef::Type ST = Symbol.getType();
6103 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6104 ST == SymbolRef::ST_Other) {
6105 uint64_t Address = Symbol.getValue();
6106 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6107 if (std::error_code EC = SymNameOrErr.getError())
6108 report_fatal_error(EC.message());
6109 StringRef SymName = *SymNameOrErr;
6110 AddrMap[Address] = SymName;
6111 if (!DisSymName.empty() && DisSymName == SymName)
6112 DisSymNameFound = true;
6115 if (!DisSymName.empty() && !DisSymNameFound) {
6116 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6119 // Set up the block of info used by the Symbolizer call backs.
6120 SymbolizerInfo.verbose = !NoSymbolicOperands;
6121 SymbolizerInfo.O = MachOOF;
6122 SymbolizerInfo.S = Sections[SectIdx];
6123 SymbolizerInfo.AddrMap = &AddrMap;
6124 SymbolizerInfo.Sections = &Sections;
6125 SymbolizerInfo.class_name = nullptr;
6126 SymbolizerInfo.selector_name = nullptr;
6127 SymbolizerInfo.method = nullptr;
6128 SymbolizerInfo.demangled_name = nullptr;
6129 SymbolizerInfo.bindtable = nullptr;
6130 SymbolizerInfo.adrp_addr = 0;
6131 SymbolizerInfo.adrp_inst = 0;
6132 // Same for the ThumbSymbolizer
6133 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
6134 ThumbSymbolizerInfo.O = MachOOF;
6135 ThumbSymbolizerInfo.S = Sections[SectIdx];
6136 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6137 ThumbSymbolizerInfo.Sections = &Sections;
6138 ThumbSymbolizerInfo.class_name = nullptr;
6139 ThumbSymbolizerInfo.selector_name = nullptr;
6140 ThumbSymbolizerInfo.method = nullptr;
6141 ThumbSymbolizerInfo.demangled_name = nullptr;
6142 ThumbSymbolizerInfo.bindtable = nullptr;
6143 ThumbSymbolizerInfo.adrp_addr = 0;
6144 ThumbSymbolizerInfo.adrp_inst = 0;
6146 // Disassemble symbol by symbol.
6147 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
6148 ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6149 if (std::error_code EC = SymNameOrErr.getError())
6150 report_fatal_error(EC.message());
6151 StringRef SymName = *SymNameOrErr;
6153 SymbolRef::Type ST = Symbols[SymIdx].getType();
6154 if (ST != SymbolRef::ST_Function)
6157 // Make sure the symbol is defined in this section.
6158 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
6162 // If we are only disassembling one symbol see if this is that symbol.
6163 if (!DisSymName.empty() && DisSymName != SymName)
6166 // Start at the address of the symbol relative to the section's address.
6167 uint64_t Start = Symbols[SymIdx].getValue();
6168 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6169 Start -= SectionAddress;
6171 // Stop disassembling either at the beginning of the next symbol or at
6172 // the end of the section.
6173 bool containsNextSym = false;
6174 uint64_t NextSym = 0;
6175 uint64_t NextSymIdx = SymIdx + 1;
6176 while (Symbols.size() > NextSymIdx) {
6177 SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
6178 if (NextSymType == SymbolRef::ST_Function) {
6180 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
6181 NextSym = Symbols[NextSymIdx].getValue();
6182 NextSym -= SectionAddress;
6188 uint64_t SectSize = Sections[SectIdx].getSize();
6189 uint64_t End = containsNextSym ? NextSym : SectSize;
6192 symbolTableWorked = true;
6194 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6196 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6198 outs() << SymName << ":\n";
6199 DILineInfo lastLine;
6200 for (uint64_t Index = Start; Index < End; Index += Size) {
6203 uint64_t PC = SectAddress + Index;
6204 if (!NoLeadingAddr) {
6205 if (FullLeadingAddr) {
6206 if (MachOOF->is64Bit())
6207 outs() << format("%016" PRIx64, PC);
6209 outs() << format("%08" PRIx64, PC);
6211 outs() << format("%8" PRIx64 ":", PC);
6217 // Check the data in code table here to see if this is data not an
6218 // instruction to be disassembled.
6220 Dice.push_back(std::make_pair(PC, DiceRef()));
6221 dice_table_iterator DTI =
6222 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6223 compareDiceTableEntries);
6224 if (DTI != Dices.end()) {
6226 DTI->second.getLength(Length);
6228 DTI->second.getKind(Kind);
6229 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
6230 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6231 (PC == (DTI->first + Length - 1)) && (Length & 1))
6236 SmallVector<char, 64> AnnotationsBytes;
6237 raw_svector_ostream Annotations(AnnotationsBytes);
6241 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
6242 PC, DebugOut, Annotations);
6244 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
6245 DebugOut, Annotations);
6247 if (!NoShowRawInsn) {
6248 dumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, Size), outs());
6250 formatted_raw_ostream FormattedOS(outs());
6251 Annotations.flush();
6252 StringRef AnnotationsStr = Annotations.str();
6254 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
6256 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
6257 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
6259 // Print debug info.
6261 DILineInfo dli = diContext->getLineInfoForAddress(PC);
6262 // Print valid line info if it changed.
6263 if (dli != lastLine && dli.Line != 0)
6264 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6270 unsigned int Arch = MachOOF->getArch();
6271 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6272 outs() << format("\t.byte 0x%02x #bad opcode\n",
6273 *(Bytes.data() + Index) & 0xff);
6274 Size = 1; // skip exactly one illegible byte and move on.
6275 } else if (Arch == Triple::aarch64) {
6276 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6277 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6278 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6279 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6280 outs() << format("\t.long\t0x%08x\n", opcode);
6283 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6285 Size = 1; // skip illegible bytes
6290 if (!symbolTableWorked) {
6291 // Reading the symbol table didn't work, disassemble the whole section.
6292 uint64_t SectAddress = Sections[SectIdx].getAddress();
6293 uint64_t SectSize = Sections[SectIdx].getSize();
6295 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
6298 uint64_t PC = SectAddress + Index;
6299 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6300 DebugOut, nulls())) {
6301 if (!NoLeadingAddr) {
6302 if (FullLeadingAddr) {
6303 if (MachOOF->is64Bit())
6304 outs() << format("%016" PRIx64, PC);
6306 outs() << format("%08" PRIx64, PC);
6308 outs() << format("%8" PRIx64 ":", PC);
6311 if (!NoShowRawInsn) {
6313 dumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, InstSize), outs());
6315 IP->printInst(&Inst, outs(), "", *STI);
6318 unsigned int Arch = MachOOF->getArch();
6319 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6320 outs() << format("\t.byte 0x%02x #bad opcode\n",
6321 *(Bytes.data() + Index) & 0xff);
6322 InstSize = 1; // skip exactly one illegible byte and move on.
6324 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6326 InstSize = 1; // skip illegible bytes
6331 // The TripleName's need to be reset if we are called again for a different
6334 ThumbTripleName = "";
6336 if (SymbolizerInfo.method != nullptr)
6337 free(SymbolizerInfo.method);
6338 if (SymbolizerInfo.demangled_name != nullptr)
6339 free(SymbolizerInfo.demangled_name);
6340 if (SymbolizerInfo.bindtable != nullptr)
6341 delete SymbolizerInfo.bindtable;
6342 if (ThumbSymbolizerInfo.method != nullptr)
6343 free(ThumbSymbolizerInfo.method);
6344 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6345 free(ThumbSymbolizerInfo.demangled_name);
6346 if (ThumbSymbolizerInfo.bindtable != nullptr)
6347 delete ThumbSymbolizerInfo.bindtable;
6351 //===----------------------------------------------------------------------===//
6352 // __compact_unwind section dumping
6353 //===----------------------------------------------------------------------===//
6357 template <typename T> static uint64_t readNext(const char *&Buf) {
6358 using llvm::support::little;
6359 using llvm::support::unaligned;
6361 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6366 struct CompactUnwindEntry {
6367 uint32_t OffsetInSection;
6369 uint64_t FunctionAddr;
6371 uint32_t CompactEncoding;
6372 uint64_t PersonalityAddr;
6375 RelocationRef FunctionReloc;
6376 RelocationRef PersonalityReloc;
6377 RelocationRef LSDAReloc;
6379 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
6380 : OffsetInSection(Offset) {
6382 read<uint64_t>(Contents.data() + Offset);
6384 read<uint32_t>(Contents.data() + Offset);
6388 template <typename UIntPtr> void read(const char *Buf) {
6389 FunctionAddr = readNext<UIntPtr>(Buf);
6390 Length = readNext<uint32_t>(Buf);
6391 CompactEncoding = readNext<uint32_t>(Buf);
6392 PersonalityAddr = readNext<UIntPtr>(Buf);
6393 LSDAAddr = readNext<UIntPtr>(Buf);
6398 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
6399 /// and data being relocated, determine the best base Name and Addend to use for
6400 /// display purposes.
6402 /// 1. An Extern relocation will directly reference a symbol (and the data is
6403 /// then already an addend), so use that.
6404 /// 2. Otherwise the data is an offset in the object file's layout; try to find
6405 // a symbol before it in the same section, and use the offset from there.
6406 /// 3. Finally, if all that fails, fall back to an offset from the start of the
6407 /// referenced section.
6408 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6409 std::map<uint64_t, SymbolRef> &Symbols,
6410 const RelocationRef &Reloc, uint64_t Addr,
6411 StringRef &Name, uint64_t &Addend) {
6412 if (Reloc.getSymbol() != Obj->symbol_end()) {
6413 ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6414 if (std::error_code EC = NameOrErr.getError())
6415 report_fatal_error(EC.message());
6421 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
6422 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
6424 uint64_t SectionAddr = RelocSection.getAddress();
6426 auto Sym = Symbols.upper_bound(Addr);
6427 if (Sym == Symbols.begin()) {
6428 // The first symbol in the object is after this reference, the best we can
6429 // do is section-relative notation.
6430 RelocSection.getName(Name);
6431 Addend = Addr - SectionAddr;
6435 // Go back one so that SymbolAddress <= Addr.
6438 section_iterator SymSection = *Sym->second.getSection();
6439 if (RelocSection == *SymSection) {
6440 // There's a valid symbol in the same section before this reference.
6441 ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6442 if (std::error_code EC = NameOrErr.getError())
6443 report_fatal_error(EC.message());
6445 Addend = Addr - Sym->first;
6449 // There is a symbol before this reference, but it's in a different
6450 // section. Probably not helpful to mention it, so use the section name.
6451 RelocSection.getName(Name);
6452 Addend = Addr - SectionAddr;
6455 static void printUnwindRelocDest(const MachOObjectFile *Obj,
6456 std::map<uint64_t, SymbolRef> &Symbols,
6457 const RelocationRef &Reloc, uint64_t Addr) {
6461 if (!Reloc.getObject())
6464 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6468 outs() << " + " << format("0x%" PRIx64, Addend);
6472 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6473 std::map<uint64_t, SymbolRef> &Symbols,
6474 const SectionRef &CompactUnwind) {
6476 assert(Obj->isLittleEndian() &&
6477 "There should not be a big-endian .o with __compact_unwind");
6479 bool Is64 = Obj->is64Bit();
6480 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6481 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6484 CompactUnwind.getContents(Contents);
6486 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6488 // First populate the initial raw offsets, encodings and so on from the entry.
6489 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6490 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6491 CompactUnwinds.push_back(Entry);
6494 // Next we need to look at the relocations to find out what objects are
6495 // actually being referred to.
6496 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
6497 uint64_t RelocAddress = Reloc.getOffset();
6499 uint32_t EntryIdx = RelocAddress / EntrySize;
6500 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6501 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6503 if (OffsetInEntry == 0)
6504 Entry.FunctionReloc = Reloc;
6505 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6506 Entry.PersonalityReloc = Reloc;
6507 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6508 Entry.LSDAReloc = Reloc;
6510 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6513 // Finally, we're ready to print the data we've gathered.
6514 outs() << "Contents of __compact_unwind section:\n";
6515 for (auto &Entry : CompactUnwinds) {
6516 outs() << " Entry at offset "
6517 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
6519 // 1. Start of the region this entry applies to.
6520 outs() << " start: " << format("0x%" PRIx64,
6521 Entry.FunctionAddr) << ' ';
6522 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
6525 // 2. Length of the region this entry applies to.
6526 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6528 // 3. The 32-bit compact encoding.
6529 outs() << " compact encoding: "
6530 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
6532 // 4. The personality function, if present.
6533 if (Entry.PersonalityReloc.getObject()) {
6534 outs() << " personality function: "
6535 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
6536 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6537 Entry.PersonalityAddr);
6541 // 5. This entry's language-specific data area.
6542 if (Entry.LSDAReloc.getObject()) {
6543 outs() << " LSDA: " << format("0x%" PRIx64,
6544 Entry.LSDAAddr) << ' ';
6545 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6551 //===----------------------------------------------------------------------===//
6552 // __unwind_info section dumping
6553 //===----------------------------------------------------------------------===//
6555 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6556 const char *Pos = PageStart;
6557 uint32_t Kind = readNext<uint32_t>(Pos);
6559 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6561 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6562 uint16_t NumEntries = readNext<uint16_t>(Pos);
6564 Pos = PageStart + EntriesStart;
6565 for (unsigned i = 0; i < NumEntries; ++i) {
6566 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6567 uint32_t Encoding = readNext<uint32_t>(Pos);
6569 outs() << " [" << i << "]: "
6570 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6572 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
6576 static void printCompressedSecondLevelUnwindPage(
6577 const char *PageStart, uint32_t FunctionBase,
6578 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6579 const char *Pos = PageStart;
6580 uint32_t Kind = readNext<uint32_t>(Pos);
6582 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6584 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6585 uint16_t NumEntries = readNext<uint16_t>(Pos);
6587 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6588 readNext<uint16_t>(Pos);
6589 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6590 PageStart + EncodingsStart);
6592 Pos = PageStart + EntriesStart;
6593 for (unsigned i = 0; i < NumEntries; ++i) {
6594 uint32_t Entry = readNext<uint32_t>(Pos);
6595 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6596 uint32_t EncodingIdx = Entry >> 24;
6599 if (EncodingIdx < CommonEncodings.size())
6600 Encoding = CommonEncodings[EncodingIdx];
6602 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6604 outs() << " [" << i << "]: "
6605 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6607 << "encoding[" << EncodingIdx
6608 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
6612 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6613 std::map<uint64_t, SymbolRef> &Symbols,
6614 const SectionRef &UnwindInfo) {
6616 assert(Obj->isLittleEndian() &&
6617 "There should not be a big-endian .o with __unwind_info");
6619 outs() << "Contents of __unwind_info section:\n";
6622 UnwindInfo.getContents(Contents);
6623 const char *Pos = Contents.data();
6625 //===----------------------------------
6627 //===----------------------------------
6629 uint32_t Version = readNext<uint32_t>(Pos);
6630 outs() << " Version: "
6631 << format("0x%" PRIx32, Version) << '\n';
6632 assert(Version == 1 && "only understand version 1");
6634 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6635 outs() << " Common encodings array section offset: "
6636 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6637 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6638 outs() << " Number of common encodings in array: "
6639 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6641 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6642 outs() << " Personality function array section offset: "
6643 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6644 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6645 outs() << " Number of personality functions in array: "
6646 << format("0x%" PRIx32, NumPersonalities) << '\n';
6648 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6649 outs() << " Index array section offset: "
6650 << format("0x%" PRIx32, IndicesStart) << '\n';
6651 uint32_t NumIndices = readNext<uint32_t>(Pos);
6652 outs() << " Number of indices in array: "
6653 << format("0x%" PRIx32, NumIndices) << '\n';
6655 //===----------------------------------
6656 // A shared list of common encodings
6657 //===----------------------------------
6659 // These occupy indices in the range [0, N] whenever an encoding is referenced
6660 // from a compressed 2nd level index table. In practice the linker only
6661 // creates ~128 of these, so that indices are available to embed encodings in
6662 // the 2nd level index.
6664 SmallVector<uint32_t, 64> CommonEncodings;
6665 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6666 Pos = Contents.data() + CommonEncodingsStart;
6667 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6668 uint32_t Encoding = readNext<uint32_t>(Pos);
6669 CommonEncodings.push_back(Encoding);
6671 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6675 //===----------------------------------
6676 // Personality functions used in this executable
6677 //===----------------------------------
6679 // There should be only a handful of these (one per source language,
6680 // roughly). Particularly since they only get 2 bits in the compact encoding.
6682 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6683 Pos = Contents.data() + PersonalitiesStart;
6684 for (unsigned i = 0; i < NumPersonalities; ++i) {
6685 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6686 outs() << " personality[" << i + 1
6687 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6690 //===----------------------------------
6691 // The level 1 index entries
6692 //===----------------------------------
6694 // These specify an approximate place to start searching for the more detailed
6695 // information, sorted by PC.
6698 uint32_t FunctionOffset;
6699 uint32_t SecondLevelPageStart;
6703 SmallVector<IndexEntry, 4> IndexEntries;
6705 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6706 Pos = Contents.data() + IndicesStart;
6707 for (unsigned i = 0; i < NumIndices; ++i) {
6710 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6711 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6712 Entry.LSDAStart = readNext<uint32_t>(Pos);
6713 IndexEntries.push_back(Entry);
6715 outs() << " [" << i << "]: "
6716 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6718 << "2nd level page offset="
6719 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
6720 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
6723 //===----------------------------------
6724 // Next come the LSDA tables
6725 //===----------------------------------
6727 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6728 // the first top-level index's LSDAOffset to the last (sentinel).
6730 outs() << " LSDA descriptors:\n";
6731 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6732 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6733 (2 * sizeof(uint32_t));
6734 for (int i = 0; i < NumLSDAs; ++i) {
6735 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6736 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6737 outs() << " [" << i << "]: "
6738 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6740 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
6743 //===----------------------------------
6744 // Finally, the 2nd level indices
6745 //===----------------------------------
6747 // Generally these are 4K in size, and have 2 possible forms:
6748 // + Regular stores up to 511 entries with disparate encodings
6749 // + Compressed stores up to 1021 entries if few enough compact encoding
6751 outs() << " Second level indices:\n";
6752 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6753 // The final sentinel top-level index has no associated 2nd level page
6754 if (IndexEntries[i].SecondLevelPageStart == 0)
6757 outs() << " Second level index[" << i << "]: "
6758 << "offset in section="
6759 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6761 << "base function offset="
6762 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6764 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
6765 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
6767 printRegularSecondLevelUnwindPage(Pos);
6769 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6772 llvm_unreachable("Do not know how to print this kind of 2nd level page");
6776 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6777 std::map<uint64_t, SymbolRef> Symbols;
6778 for (const SymbolRef &SymRef : Obj->symbols()) {
6779 // Discard any undefined or absolute symbols. They're not going to take part
6780 // in the convenience lookup for unwind info and just take up resources.
6781 section_iterator Section = *SymRef.getSection();
6782 if (Section == Obj->section_end())
6785 uint64_t Addr = SymRef.getValue();
6786 Symbols.insert(std::make_pair(Addr, SymRef));
6789 for (const SectionRef &Section : Obj->sections()) {
6791 Section.getName(SectName);
6792 if (SectName == "__compact_unwind")
6793 printMachOCompactUnwindSection(Obj, Symbols, Section);
6794 else if (SectName == "__unwind_info")
6795 printMachOUnwindInfoSection(Obj, Symbols, Section);
6796 else if (SectName == "__eh_frame")
6797 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
6801 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6802 uint32_t cpusubtype, uint32_t filetype,
6803 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6805 outs() << "Mach header\n";
6806 outs() << " magic cputype cpusubtype caps filetype ncmds "
6807 "sizeofcmds flags\n";
6809 if (magic == MachO::MH_MAGIC)
6810 outs() << " MH_MAGIC";
6811 else if (magic == MachO::MH_MAGIC_64)
6812 outs() << "MH_MAGIC_64";
6814 outs() << format(" 0x%08" PRIx32, magic);
6816 case MachO::CPU_TYPE_I386:
6818 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6819 case MachO::CPU_SUBTYPE_I386_ALL:
6823 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6827 case MachO::CPU_TYPE_X86_64:
6828 outs() << " X86_64";
6829 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6830 case MachO::CPU_SUBTYPE_X86_64_ALL:
6833 case MachO::CPU_SUBTYPE_X86_64_H:
6834 outs() << " Haswell";
6837 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6841 case MachO::CPU_TYPE_ARM:
6843 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6844 case MachO::CPU_SUBTYPE_ARM_ALL:
6847 case MachO::CPU_SUBTYPE_ARM_V4T:
6850 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6853 case MachO::CPU_SUBTYPE_ARM_XSCALE:
6854 outs() << " XSCALE";
6856 case MachO::CPU_SUBTYPE_ARM_V6:
6859 case MachO::CPU_SUBTYPE_ARM_V6M:
6862 case MachO::CPU_SUBTYPE_ARM_V7:
6865 case MachO::CPU_SUBTYPE_ARM_V7EM:
6868 case MachO::CPU_SUBTYPE_ARM_V7K:
6871 case MachO::CPU_SUBTYPE_ARM_V7M:
6874 case MachO::CPU_SUBTYPE_ARM_V7S:
6878 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6882 case MachO::CPU_TYPE_ARM64:
6884 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6885 case MachO::CPU_SUBTYPE_ARM64_ALL:
6889 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6893 case MachO::CPU_TYPE_POWERPC:
6895 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6896 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6900 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6904 case MachO::CPU_TYPE_POWERPC64:
6906 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6907 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6911 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6916 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
6919 outs() << format(" 0x%02" PRIx32,
6920 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
6923 case MachO::MH_OBJECT:
6924 outs() << " OBJECT";
6926 case MachO::MH_EXECUTE:
6927 outs() << " EXECUTE";
6929 case MachO::MH_FVMLIB:
6930 outs() << " FVMLIB";
6932 case MachO::MH_CORE:
6935 case MachO::MH_PRELOAD:
6936 outs() << " PRELOAD";
6938 case MachO::MH_DYLIB:
6941 case MachO::MH_DYLIB_STUB:
6942 outs() << " DYLIB_STUB";
6944 case MachO::MH_DYLINKER:
6945 outs() << " DYLINKER";
6947 case MachO::MH_BUNDLE:
6948 outs() << " BUNDLE";
6950 case MachO::MH_DSYM:
6953 case MachO::MH_KEXT_BUNDLE:
6954 outs() << " KEXTBUNDLE";
6957 outs() << format(" %10u", filetype);
6960 outs() << format(" %5u", ncmds);
6961 outs() << format(" %10u", sizeofcmds);
6963 if (f & MachO::MH_NOUNDEFS) {
6964 outs() << " NOUNDEFS";
6965 f &= ~MachO::MH_NOUNDEFS;
6967 if (f & MachO::MH_INCRLINK) {
6968 outs() << " INCRLINK";
6969 f &= ~MachO::MH_INCRLINK;
6971 if (f & MachO::MH_DYLDLINK) {
6972 outs() << " DYLDLINK";
6973 f &= ~MachO::MH_DYLDLINK;
6975 if (f & MachO::MH_BINDATLOAD) {
6976 outs() << " BINDATLOAD";
6977 f &= ~MachO::MH_BINDATLOAD;
6979 if (f & MachO::MH_PREBOUND) {
6980 outs() << " PREBOUND";
6981 f &= ~MachO::MH_PREBOUND;
6983 if (f & MachO::MH_SPLIT_SEGS) {
6984 outs() << " SPLIT_SEGS";
6985 f &= ~MachO::MH_SPLIT_SEGS;
6987 if (f & MachO::MH_LAZY_INIT) {
6988 outs() << " LAZY_INIT";
6989 f &= ~MachO::MH_LAZY_INIT;
6991 if (f & MachO::MH_TWOLEVEL) {
6992 outs() << " TWOLEVEL";
6993 f &= ~MachO::MH_TWOLEVEL;
6995 if (f & MachO::MH_FORCE_FLAT) {
6996 outs() << " FORCE_FLAT";
6997 f &= ~MachO::MH_FORCE_FLAT;
6999 if (f & MachO::MH_NOMULTIDEFS) {
7000 outs() << " NOMULTIDEFS";
7001 f &= ~MachO::MH_NOMULTIDEFS;
7003 if (f & MachO::MH_NOFIXPREBINDING) {
7004 outs() << " NOFIXPREBINDING";
7005 f &= ~MachO::MH_NOFIXPREBINDING;
7007 if (f & MachO::MH_PREBINDABLE) {
7008 outs() << " PREBINDABLE";
7009 f &= ~MachO::MH_PREBINDABLE;
7011 if (f & MachO::MH_ALLMODSBOUND) {
7012 outs() << " ALLMODSBOUND";
7013 f &= ~MachO::MH_ALLMODSBOUND;
7015 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7016 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7017 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7019 if (f & MachO::MH_CANONICAL) {
7020 outs() << " CANONICAL";
7021 f &= ~MachO::MH_CANONICAL;
7023 if (f & MachO::MH_WEAK_DEFINES) {
7024 outs() << " WEAK_DEFINES";
7025 f &= ~MachO::MH_WEAK_DEFINES;
7027 if (f & MachO::MH_BINDS_TO_WEAK) {
7028 outs() << " BINDS_TO_WEAK";
7029 f &= ~MachO::MH_BINDS_TO_WEAK;
7031 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7032 outs() << " ALLOW_STACK_EXECUTION";
7033 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7035 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7036 outs() << " DEAD_STRIPPABLE_DYLIB";
7037 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7039 if (f & MachO::MH_PIE) {
7041 f &= ~MachO::MH_PIE;
7043 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7044 outs() << " NO_REEXPORTED_DYLIBS";
7045 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7047 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7048 outs() << " MH_HAS_TLV_DESCRIPTORS";
7049 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7051 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7052 outs() << " MH_NO_HEAP_EXECUTION";
7053 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7055 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7056 outs() << " APP_EXTENSION_SAFE";
7057 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7059 if (f != 0 || flags == 0)
7060 outs() << format(" 0x%08" PRIx32, f);
7062 outs() << format(" 0x%08" PRIx32, magic);
7063 outs() << format(" %7d", cputype);
7064 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7065 outs() << format(" 0x%02" PRIx32,
7066 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7067 outs() << format(" %10u", filetype);
7068 outs() << format(" %5u", ncmds);
7069 outs() << format(" %10u", sizeofcmds);
7070 outs() << format(" 0x%08" PRIx32, flags);
7075 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7076 StringRef SegName, uint64_t vmaddr,
7077 uint64_t vmsize, uint64_t fileoff,
7078 uint64_t filesize, uint32_t maxprot,
7079 uint32_t initprot, uint32_t nsects,
7080 uint32_t flags, uint32_t object_size,
7082 uint64_t expected_cmdsize;
7083 if (cmd == MachO::LC_SEGMENT) {
7084 outs() << " cmd LC_SEGMENT\n";
7085 expected_cmdsize = nsects;
7086 expected_cmdsize *= sizeof(struct MachO::section);
7087 expected_cmdsize += sizeof(struct MachO::segment_command);
7089 outs() << " cmd LC_SEGMENT_64\n";
7090 expected_cmdsize = nsects;
7091 expected_cmdsize *= sizeof(struct MachO::section_64);
7092 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7094 outs() << " cmdsize " << cmdsize;
7095 if (cmdsize != expected_cmdsize)
7096 outs() << " Inconsistent size\n";
7099 outs() << " segname " << SegName << "\n";
7100 if (cmd == MachO::LC_SEGMENT_64) {
7101 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7102 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7104 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7105 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
7107 outs() << " fileoff " << fileoff;
7108 if (fileoff > object_size)
7109 outs() << " (past end of file)\n";
7112 outs() << " filesize " << filesize;
7113 if (fileoff + filesize > object_size)
7114 outs() << " (past end of file)\n";
7119 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7120 MachO::VM_PROT_EXECUTE)) != 0)
7121 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7123 if (maxprot & MachO::VM_PROT_READ)
7124 outs() << " maxprot r";
7126 outs() << " maxprot -";
7127 if (maxprot & MachO::VM_PROT_WRITE)
7131 if (maxprot & MachO::VM_PROT_EXECUTE)
7137 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7138 MachO::VM_PROT_EXECUTE)) != 0)
7139 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7141 if (initprot & MachO::VM_PROT_READ)
7142 outs() << " initprot r";
7144 outs() << " initprot -";
7145 if (initprot & MachO::VM_PROT_WRITE)
7149 if (initprot & MachO::VM_PROT_EXECUTE)
7155 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7156 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7158 outs() << " nsects " << nsects << "\n";
7162 outs() << " (none)\n";
7164 if (flags & MachO::SG_HIGHVM) {
7165 outs() << " HIGHVM";
7166 flags &= ~MachO::SG_HIGHVM;
7168 if (flags & MachO::SG_FVMLIB) {
7169 outs() << " FVMLIB";
7170 flags &= ~MachO::SG_FVMLIB;
7172 if (flags & MachO::SG_NORELOC) {
7173 outs() << " NORELOC";
7174 flags &= ~MachO::SG_NORELOC;
7176 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7177 outs() << " PROTECTED_VERSION_1";
7178 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7181 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7186 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7190 static void PrintSection(const char *sectname, const char *segname,
7191 uint64_t addr, uint64_t size, uint32_t offset,
7192 uint32_t align, uint32_t reloff, uint32_t nreloc,
7193 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7194 uint32_t cmd, const char *sg_segname,
7195 uint32_t filetype, uint32_t object_size,
7197 outs() << "Section\n";
7198 outs() << " sectname " << format("%.16s\n", sectname);
7199 outs() << " segname " << format("%.16s", segname);
7200 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7201 outs() << " (does not match segment)\n";
7204 if (cmd == MachO::LC_SEGMENT_64) {
7205 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7206 outs() << " size " << format("0x%016" PRIx64, size);
7208 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7209 outs() << " size " << format("0x%08" PRIx64, size);
7211 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7212 outs() << " (past end of file)\n";
7215 outs() << " offset " << offset;
7216 if (offset > object_size)
7217 outs() << " (past end of file)\n";
7220 uint32_t align_shifted = 1 << align;
7221 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7222 outs() << " reloff " << reloff;
7223 if (reloff > object_size)
7224 outs() << " (past end of file)\n";
7227 outs() << " nreloc " << nreloc;
7228 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7229 outs() << " (past end of file)\n";
7232 uint32_t section_type = flags & MachO::SECTION_TYPE;
7235 if (section_type == MachO::S_REGULAR)
7236 outs() << " S_REGULAR\n";
7237 else if (section_type == MachO::S_ZEROFILL)
7238 outs() << " S_ZEROFILL\n";
7239 else if (section_type == MachO::S_CSTRING_LITERALS)
7240 outs() << " S_CSTRING_LITERALS\n";
7241 else if (section_type == MachO::S_4BYTE_LITERALS)
7242 outs() << " S_4BYTE_LITERALS\n";
7243 else if (section_type == MachO::S_8BYTE_LITERALS)
7244 outs() << " S_8BYTE_LITERALS\n";
7245 else if (section_type == MachO::S_16BYTE_LITERALS)
7246 outs() << " S_16BYTE_LITERALS\n";
7247 else if (section_type == MachO::S_LITERAL_POINTERS)
7248 outs() << " S_LITERAL_POINTERS\n";
7249 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7250 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7251 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7252 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7253 else if (section_type == MachO::S_SYMBOL_STUBS)
7254 outs() << " S_SYMBOL_STUBS\n";
7255 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7256 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7257 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7258 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7259 else if (section_type == MachO::S_COALESCED)
7260 outs() << " S_COALESCED\n";
7261 else if (section_type == MachO::S_INTERPOSING)
7262 outs() << " S_INTERPOSING\n";
7263 else if (section_type == MachO::S_DTRACE_DOF)
7264 outs() << " S_DTRACE_DOF\n";
7265 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7266 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7267 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7268 outs() << " S_THREAD_LOCAL_REGULAR\n";
7269 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7270 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7271 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7272 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7273 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7274 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7275 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7276 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7278 outs() << format("0x%08" PRIx32, section_type) << "\n";
7279 outs() << "attributes";
7280 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7281 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7282 outs() << " PURE_INSTRUCTIONS";
7283 if (section_attributes & MachO::S_ATTR_NO_TOC)
7284 outs() << " NO_TOC";
7285 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7286 outs() << " STRIP_STATIC_SYMS";
7287 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7288 outs() << " NO_DEAD_STRIP";
7289 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7290 outs() << " LIVE_SUPPORT";
7291 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7292 outs() << " SELF_MODIFYING_CODE";
7293 if (section_attributes & MachO::S_ATTR_DEBUG)
7295 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7296 outs() << " SOME_INSTRUCTIONS";
7297 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7298 outs() << " EXT_RELOC";
7299 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7300 outs() << " LOC_RELOC";
7301 if (section_attributes == 0)
7302 outs() << " (none)";
7305 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7306 outs() << " reserved1 " << reserved1;
7307 if (section_type == MachO::S_SYMBOL_STUBS ||
7308 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7309 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7310 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7311 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7312 outs() << " (index into indirect symbol table)\n";
7315 outs() << " reserved2 " << reserved2;
7316 if (section_type == MachO::S_SYMBOL_STUBS)
7317 outs() << " (size of stubs)\n";
7322 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
7323 uint32_t object_size) {
7324 outs() << " cmd LC_SYMTAB\n";
7325 outs() << " cmdsize " << st.cmdsize;
7326 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7327 outs() << " Incorrect size\n";
7330 outs() << " symoff " << st.symoff;
7331 if (st.symoff > object_size)
7332 outs() << " (past end of file)\n";
7335 outs() << " nsyms " << st.nsyms;
7338 big_size = st.nsyms;
7339 big_size *= sizeof(struct MachO::nlist_64);
7340 big_size += st.symoff;
7341 if (big_size > object_size)
7342 outs() << " (past end of file)\n";
7346 big_size = st.nsyms;
7347 big_size *= sizeof(struct MachO::nlist);
7348 big_size += st.symoff;
7349 if (big_size > object_size)
7350 outs() << " (past end of file)\n";
7354 outs() << " stroff " << st.stroff;
7355 if (st.stroff > object_size)
7356 outs() << " (past end of file)\n";
7359 outs() << " strsize " << st.strsize;
7360 big_size = st.stroff;
7361 big_size += st.strsize;
7362 if (big_size > object_size)
7363 outs() << " (past end of file)\n";
7368 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7369 uint32_t nsyms, uint32_t object_size,
7371 outs() << " cmd LC_DYSYMTAB\n";
7372 outs() << " cmdsize " << dyst.cmdsize;
7373 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7374 outs() << " Incorrect size\n";
7377 outs() << " ilocalsym " << dyst.ilocalsym;
7378 if (dyst.ilocalsym > nsyms)
7379 outs() << " (greater than the number of symbols)\n";
7382 outs() << " nlocalsym " << dyst.nlocalsym;
7384 big_size = dyst.ilocalsym;
7385 big_size += dyst.nlocalsym;
7386 if (big_size > nsyms)
7387 outs() << " (past the end of the symbol table)\n";
7390 outs() << " iextdefsym " << dyst.iextdefsym;
7391 if (dyst.iextdefsym > nsyms)
7392 outs() << " (greater than the number of symbols)\n";
7395 outs() << " nextdefsym " << dyst.nextdefsym;
7396 big_size = dyst.iextdefsym;
7397 big_size += dyst.nextdefsym;
7398 if (big_size > nsyms)
7399 outs() << " (past the end of the symbol table)\n";
7402 outs() << " iundefsym " << dyst.iundefsym;
7403 if (dyst.iundefsym > nsyms)
7404 outs() << " (greater than the number of symbols)\n";
7407 outs() << " nundefsym " << dyst.nundefsym;
7408 big_size = dyst.iundefsym;
7409 big_size += dyst.nundefsym;
7410 if (big_size > nsyms)
7411 outs() << " (past the end of the symbol table)\n";
7414 outs() << " tocoff " << dyst.tocoff;
7415 if (dyst.tocoff > object_size)
7416 outs() << " (past end of file)\n";
7419 outs() << " ntoc " << dyst.ntoc;
7420 big_size = dyst.ntoc;
7421 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7422 big_size += dyst.tocoff;
7423 if (big_size > object_size)
7424 outs() << " (past end of file)\n";
7427 outs() << " modtaboff " << dyst.modtaboff;
7428 if (dyst.modtaboff > object_size)
7429 outs() << " (past end of file)\n";
7432 outs() << " nmodtab " << dyst.nmodtab;
7435 modtabend = dyst.nmodtab;
7436 modtabend *= sizeof(struct MachO::dylib_module_64);
7437 modtabend += dyst.modtaboff;
7439 modtabend = dyst.nmodtab;
7440 modtabend *= sizeof(struct MachO::dylib_module);
7441 modtabend += dyst.modtaboff;
7443 if (modtabend > object_size)
7444 outs() << " (past end of file)\n";
7447 outs() << " extrefsymoff " << dyst.extrefsymoff;
7448 if (dyst.extrefsymoff > object_size)
7449 outs() << " (past end of file)\n";
7452 outs() << " nextrefsyms " << dyst.nextrefsyms;
7453 big_size = dyst.nextrefsyms;
7454 big_size *= sizeof(struct MachO::dylib_reference);
7455 big_size += dyst.extrefsymoff;
7456 if (big_size > object_size)
7457 outs() << " (past end of file)\n";
7460 outs() << " indirectsymoff " << dyst.indirectsymoff;
7461 if (dyst.indirectsymoff > object_size)
7462 outs() << " (past end of file)\n";
7465 outs() << " nindirectsyms " << dyst.nindirectsyms;
7466 big_size = dyst.nindirectsyms;
7467 big_size *= sizeof(uint32_t);
7468 big_size += dyst.indirectsymoff;
7469 if (big_size > object_size)
7470 outs() << " (past end of file)\n";
7473 outs() << " extreloff " << dyst.extreloff;
7474 if (dyst.extreloff > object_size)
7475 outs() << " (past end of file)\n";
7478 outs() << " nextrel " << dyst.nextrel;
7479 big_size = dyst.nextrel;
7480 big_size *= sizeof(struct MachO::relocation_info);
7481 big_size += dyst.extreloff;
7482 if (big_size > object_size)
7483 outs() << " (past end of file)\n";
7486 outs() << " locreloff " << dyst.locreloff;
7487 if (dyst.locreloff > object_size)
7488 outs() << " (past end of file)\n";
7491 outs() << " nlocrel " << dyst.nlocrel;
7492 big_size = dyst.nlocrel;
7493 big_size *= sizeof(struct MachO::relocation_info);
7494 big_size += dyst.locreloff;
7495 if (big_size > object_size)
7496 outs() << " (past end of file)\n";
7501 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7502 uint32_t object_size) {
7503 if (dc.cmd == MachO::LC_DYLD_INFO)
7504 outs() << " cmd LC_DYLD_INFO\n";
7506 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7507 outs() << " cmdsize " << dc.cmdsize;
7508 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7509 outs() << " Incorrect size\n";
7512 outs() << " rebase_off " << dc.rebase_off;
7513 if (dc.rebase_off > object_size)
7514 outs() << " (past end of file)\n";
7517 outs() << " rebase_size " << dc.rebase_size;
7519 big_size = dc.rebase_off;
7520 big_size += dc.rebase_size;
7521 if (big_size > object_size)
7522 outs() << " (past end of file)\n";
7525 outs() << " bind_off " << dc.bind_off;
7526 if (dc.bind_off > object_size)
7527 outs() << " (past end of file)\n";
7530 outs() << " bind_size " << dc.bind_size;
7531 big_size = dc.bind_off;
7532 big_size += dc.bind_size;
7533 if (big_size > object_size)
7534 outs() << " (past end of file)\n";
7537 outs() << " weak_bind_off " << dc.weak_bind_off;
7538 if (dc.weak_bind_off > object_size)
7539 outs() << " (past end of file)\n";
7542 outs() << " weak_bind_size " << dc.weak_bind_size;
7543 big_size = dc.weak_bind_off;
7544 big_size += dc.weak_bind_size;
7545 if (big_size > object_size)
7546 outs() << " (past end of file)\n";
7549 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7550 if (dc.lazy_bind_off > object_size)
7551 outs() << " (past end of file)\n";
7554 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7555 big_size = dc.lazy_bind_off;
7556 big_size += dc.lazy_bind_size;
7557 if (big_size > object_size)
7558 outs() << " (past end of file)\n";
7561 outs() << " export_off " << dc.export_off;
7562 if (dc.export_off > object_size)
7563 outs() << " (past end of file)\n";
7566 outs() << " export_size " << dc.export_size;
7567 big_size = dc.export_off;
7568 big_size += dc.export_size;
7569 if (big_size > object_size)
7570 outs() << " (past end of file)\n";
7575 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7577 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7578 outs() << " cmd LC_ID_DYLINKER\n";
7579 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7580 outs() << " cmd LC_LOAD_DYLINKER\n";
7581 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7582 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7584 outs() << " cmd ?(" << dyld.cmd << ")\n";
7585 outs() << " cmdsize " << dyld.cmdsize;
7586 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7587 outs() << " Incorrect size\n";
7590 if (dyld.name >= dyld.cmdsize)
7591 outs() << " name ?(bad offset " << dyld.name << ")\n";
7593 const char *P = (const char *)(Ptr) + dyld.name;
7594 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7598 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7599 outs() << " cmd LC_UUID\n";
7600 outs() << " cmdsize " << uuid.cmdsize;
7601 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7602 outs() << " Incorrect size\n";
7606 outs() << format("%02" PRIX32, uuid.uuid[0]);
7607 outs() << format("%02" PRIX32, uuid.uuid[1]);
7608 outs() << format("%02" PRIX32, uuid.uuid[2]);
7609 outs() << format("%02" PRIX32, uuid.uuid[3]);
7611 outs() << format("%02" PRIX32, uuid.uuid[4]);
7612 outs() << format("%02" PRIX32, uuid.uuid[5]);
7614 outs() << format("%02" PRIX32, uuid.uuid[6]);
7615 outs() << format("%02" PRIX32, uuid.uuid[7]);
7617 outs() << format("%02" PRIX32, uuid.uuid[8]);
7618 outs() << format("%02" PRIX32, uuid.uuid[9]);
7620 outs() << format("%02" PRIX32, uuid.uuid[10]);
7621 outs() << format("%02" PRIX32, uuid.uuid[11]);
7622 outs() << format("%02" PRIX32, uuid.uuid[12]);
7623 outs() << format("%02" PRIX32, uuid.uuid[13]);
7624 outs() << format("%02" PRIX32, uuid.uuid[14]);
7625 outs() << format("%02" PRIX32, uuid.uuid[15]);
7629 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
7630 outs() << " cmd LC_RPATH\n";
7631 outs() << " cmdsize " << rpath.cmdsize;
7632 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7633 outs() << " Incorrect size\n";
7636 if (rpath.path >= rpath.cmdsize)
7637 outs() << " path ?(bad offset " << rpath.path << ")\n";
7639 const char *P = (const char *)(Ptr) + rpath.path;
7640 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7644 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
7645 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
7646 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
7647 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
7648 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
7650 outs() << " cmd " << vd.cmd << " (?)\n";
7651 outs() << " cmdsize " << vd.cmdsize;
7652 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7653 outs() << " Incorrect size\n";
7656 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
7657 << ((vd.version >> 8) & 0xff);
7658 if ((vd.version & 0xff) != 0)
7659 outs() << "." << (vd.version & 0xff);
7662 outs() << " sdk n/a";
7664 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
7665 << ((vd.sdk >> 8) & 0xff);
7667 if ((vd.sdk & 0xff) != 0)
7668 outs() << "." << (vd.sdk & 0xff);
7672 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7673 outs() << " cmd LC_SOURCE_VERSION\n";
7674 outs() << " cmdsize " << sd.cmdsize;
7675 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7676 outs() << " Incorrect size\n";
7679 uint64_t a = (sd.version >> 40) & 0xffffff;
7680 uint64_t b = (sd.version >> 30) & 0x3ff;
7681 uint64_t c = (sd.version >> 20) & 0x3ff;
7682 uint64_t d = (sd.version >> 10) & 0x3ff;
7683 uint64_t e = sd.version & 0x3ff;
7684 outs() << " version " << a << "." << b;
7686 outs() << "." << c << "." << d << "." << e;
7688 outs() << "." << c << "." << d;
7694 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7695 outs() << " cmd LC_MAIN\n";
7696 outs() << " cmdsize " << ep.cmdsize;
7697 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7698 outs() << " Incorrect size\n";
7701 outs() << " entryoff " << ep.entryoff << "\n";
7702 outs() << " stacksize " << ep.stacksize << "\n";
7705 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7706 uint32_t object_size) {
7707 outs() << " cmd LC_ENCRYPTION_INFO\n";
7708 outs() << " cmdsize " << ec.cmdsize;
7709 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7710 outs() << " Incorrect size\n";
7713 outs() << " cryptoff " << ec.cryptoff;
7714 if (ec.cryptoff > object_size)
7715 outs() << " (past end of file)\n";
7718 outs() << " cryptsize " << ec.cryptsize;
7719 if (ec.cryptsize > object_size)
7720 outs() << " (past end of file)\n";
7723 outs() << " cryptid " << ec.cryptid << "\n";
7726 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
7727 uint32_t object_size) {
7728 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7729 outs() << " cmdsize " << ec.cmdsize;
7730 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7731 outs() << " Incorrect size\n";
7734 outs() << " cryptoff " << ec.cryptoff;
7735 if (ec.cryptoff > object_size)
7736 outs() << " (past end of file)\n";
7739 outs() << " cryptsize " << ec.cryptsize;
7740 if (ec.cryptsize > object_size)
7741 outs() << " (past end of file)\n";
7744 outs() << " cryptid " << ec.cryptid << "\n";
7745 outs() << " pad " << ec.pad << "\n";
7748 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7750 outs() << " cmd LC_LINKER_OPTION\n";
7751 outs() << " cmdsize " << lo.cmdsize;
7752 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7753 outs() << " Incorrect size\n";
7756 outs() << " count " << lo.count << "\n";
7757 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7758 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7761 while (*string == '\0' && left > 0) {
7767 outs() << " string #" << i << " " << format("%.*s\n", left, string);
7768 uint32_t NullPos = StringRef(string, left).find('\0');
7769 uint32_t len = std::min(NullPos, left) + 1;
7775 outs() << " count " << lo.count << " does not match number of strings "
7779 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7781 outs() << " cmd LC_SUB_FRAMEWORK\n";
7782 outs() << " cmdsize " << sub.cmdsize;
7783 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7784 outs() << " Incorrect size\n";
7787 if (sub.umbrella < sub.cmdsize) {
7788 const char *P = Ptr + sub.umbrella;
7789 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7791 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7795 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7797 outs() << " cmd LC_SUB_UMBRELLA\n";
7798 outs() << " cmdsize " << sub.cmdsize;
7799 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7800 outs() << " Incorrect size\n";
7803 if (sub.sub_umbrella < sub.cmdsize) {
7804 const char *P = Ptr + sub.sub_umbrella;
7805 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7807 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7811 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
7813 outs() << " cmd LC_SUB_LIBRARY\n";
7814 outs() << " cmdsize " << sub.cmdsize;
7815 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7816 outs() << " Incorrect size\n";
7819 if (sub.sub_library < sub.cmdsize) {
7820 const char *P = Ptr + sub.sub_library;
7821 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7823 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7827 static void PrintSubClientCommand(MachO::sub_client_command sub,
7829 outs() << " cmd LC_SUB_CLIENT\n";
7830 outs() << " cmdsize " << sub.cmdsize;
7831 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7832 outs() << " Incorrect size\n";
7835 if (sub.client < sub.cmdsize) {
7836 const char *P = Ptr + sub.client;
7837 outs() << " client " << P << " (offset " << sub.client << ")\n";
7839 outs() << " client ?(bad offset " << sub.client << ")\n";
7843 static void PrintRoutinesCommand(MachO::routines_command r) {
7844 outs() << " cmd LC_ROUTINES\n";
7845 outs() << " cmdsize " << r.cmdsize;
7846 if (r.cmdsize != sizeof(struct MachO::routines_command))
7847 outs() << " Incorrect size\n";
7850 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7851 outs() << " init_module " << r.init_module << "\n";
7852 outs() << " reserved1 " << r.reserved1 << "\n";
7853 outs() << " reserved2 " << r.reserved2 << "\n";
7854 outs() << " reserved3 " << r.reserved3 << "\n";
7855 outs() << " reserved4 " << r.reserved4 << "\n";
7856 outs() << " reserved5 " << r.reserved5 << "\n";
7857 outs() << " reserved6 " << r.reserved6 << "\n";
7860 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7861 outs() << " cmd LC_ROUTINES_64\n";
7862 outs() << " cmdsize " << r.cmdsize;
7863 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
7864 outs() << " Incorrect size\n";
7867 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
7868 outs() << " init_module " << r.init_module << "\n";
7869 outs() << " reserved1 " << r.reserved1 << "\n";
7870 outs() << " reserved2 " << r.reserved2 << "\n";
7871 outs() << " reserved3 " << r.reserved3 << "\n";
7872 outs() << " reserved4 " << r.reserved4 << "\n";
7873 outs() << " reserved5 " << r.reserved5 << "\n";
7874 outs() << " reserved6 " << r.reserved6 << "\n";
7877 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
7878 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
7879 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
7880 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
7881 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
7882 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
7883 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
7884 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
7885 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
7886 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
7887 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
7888 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
7889 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
7890 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
7891 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
7892 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
7893 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
7894 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
7895 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
7896 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
7897 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
7898 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
7901 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
7903 outs() << "\t mmst_reg ";
7904 for (f = 0; f < 10; f++)
7905 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
7907 outs() << "\t mmst_rsrv ";
7908 for (f = 0; f < 6; f++)
7909 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
7913 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
7915 outs() << "\t xmm_reg ";
7916 for (f = 0; f < 16; f++)
7917 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
7921 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
7922 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
7923 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
7924 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
7925 outs() << " denorm " << fpu.fpu_fcw.denorm;
7926 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
7927 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
7928 outs() << " undfl " << fpu.fpu_fcw.undfl;
7929 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
7930 outs() << "\t\t pc ";
7931 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
7932 outs() << "FP_PREC_24B ";
7933 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
7934 outs() << "FP_PREC_53B ";
7935 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
7936 outs() << "FP_PREC_64B ";
7938 outs() << fpu.fpu_fcw.pc << " ";
7940 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
7941 outs() << "FP_RND_NEAR ";
7942 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
7943 outs() << "FP_RND_DOWN ";
7944 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
7945 outs() << "FP_RND_UP ";
7946 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
7947 outs() << "FP_CHOP ";
7949 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
7950 outs() << " denorm " << fpu.fpu_fsw.denorm;
7951 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
7952 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
7953 outs() << " undfl " << fpu.fpu_fsw.undfl;
7954 outs() << " precis " << fpu.fpu_fsw.precis;
7955 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
7956 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
7957 outs() << " c0 " << fpu.fpu_fsw.c0;
7958 outs() << " c1 " << fpu.fpu_fsw.c1;
7959 outs() << " c2 " << fpu.fpu_fsw.c2;
7960 outs() << " tos " << fpu.fpu_fsw.tos;
7961 outs() << " c3 " << fpu.fpu_fsw.c3;
7962 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
7963 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
7964 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
7965 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
7966 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
7967 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
7968 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
7969 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
7970 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
7971 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
7972 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
7973 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
7975 outs() << "\t fpu_stmm0:\n";
7976 Print_mmst_reg(fpu.fpu_stmm0);
7977 outs() << "\t fpu_stmm1:\n";
7978 Print_mmst_reg(fpu.fpu_stmm1);
7979 outs() << "\t fpu_stmm2:\n";
7980 Print_mmst_reg(fpu.fpu_stmm2);
7981 outs() << "\t fpu_stmm3:\n";
7982 Print_mmst_reg(fpu.fpu_stmm3);
7983 outs() << "\t fpu_stmm4:\n";
7984 Print_mmst_reg(fpu.fpu_stmm4);
7985 outs() << "\t fpu_stmm5:\n";
7986 Print_mmst_reg(fpu.fpu_stmm5);
7987 outs() << "\t fpu_stmm6:\n";
7988 Print_mmst_reg(fpu.fpu_stmm6);
7989 outs() << "\t fpu_stmm7:\n";
7990 Print_mmst_reg(fpu.fpu_stmm7);
7991 outs() << "\t fpu_xmm0:\n";
7992 Print_xmm_reg(fpu.fpu_xmm0);
7993 outs() << "\t fpu_xmm1:\n";
7994 Print_xmm_reg(fpu.fpu_xmm1);
7995 outs() << "\t fpu_xmm2:\n";
7996 Print_xmm_reg(fpu.fpu_xmm2);
7997 outs() << "\t fpu_xmm3:\n";
7998 Print_xmm_reg(fpu.fpu_xmm3);
7999 outs() << "\t fpu_xmm4:\n";
8000 Print_xmm_reg(fpu.fpu_xmm4);
8001 outs() << "\t fpu_xmm5:\n";
8002 Print_xmm_reg(fpu.fpu_xmm5);
8003 outs() << "\t fpu_xmm6:\n";
8004 Print_xmm_reg(fpu.fpu_xmm6);
8005 outs() << "\t fpu_xmm7:\n";
8006 Print_xmm_reg(fpu.fpu_xmm7);
8007 outs() << "\t fpu_xmm8:\n";
8008 Print_xmm_reg(fpu.fpu_xmm8);
8009 outs() << "\t fpu_xmm9:\n";
8010 Print_xmm_reg(fpu.fpu_xmm9);
8011 outs() << "\t fpu_xmm10:\n";
8012 Print_xmm_reg(fpu.fpu_xmm10);
8013 outs() << "\t fpu_xmm11:\n";
8014 Print_xmm_reg(fpu.fpu_xmm11);
8015 outs() << "\t fpu_xmm12:\n";
8016 Print_xmm_reg(fpu.fpu_xmm12);
8017 outs() << "\t fpu_xmm13:\n";
8018 Print_xmm_reg(fpu.fpu_xmm13);
8019 outs() << "\t fpu_xmm14:\n";
8020 Print_xmm_reg(fpu.fpu_xmm14);
8021 outs() << "\t fpu_xmm15:\n";
8022 Print_xmm_reg(fpu.fpu_xmm15);
8023 outs() << "\t fpu_rsrv4:\n";
8024 for (uint32_t f = 0; f < 6; f++) {
8026 for (uint32_t g = 0; g < 16; g++)
8027 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
8030 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8034 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8035 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8036 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8037 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8040 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8041 bool isLittleEndian, uint32_t cputype) {
8042 if (t.cmd == MachO::LC_THREAD)
8043 outs() << " cmd LC_THREAD\n";
8044 else if (t.cmd == MachO::LC_UNIXTHREAD)
8045 outs() << " cmd LC_UNIXTHREAD\n";
8047 outs() << " cmd " << t.cmd << " (unknown)\n";
8048 outs() << " cmdsize " << t.cmdsize;
8049 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8050 outs() << " Incorrect size\n";
8054 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8055 const char *end = Ptr + t.cmdsize;
8056 uint32_t flavor, count, left;
8057 if (cputype == MachO::CPU_TYPE_X86_64) {
8058 while (begin < end) {
8059 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8060 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8061 begin += sizeof(uint32_t);
8066 if (isLittleEndian != sys::IsLittleEndianHost)
8067 sys::swapByteOrder(flavor);
8068 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8069 memcpy((char *)&count, begin, sizeof(uint32_t));
8070 begin += sizeof(uint32_t);
8075 if (isLittleEndian != sys::IsLittleEndianHost)
8076 sys::swapByteOrder(count);
8077 if (flavor == MachO::x86_THREAD_STATE64) {
8078 outs() << " flavor x86_THREAD_STATE64\n";
8079 if (count == MachO::x86_THREAD_STATE64_COUNT)
8080 outs() << " count x86_THREAD_STATE64_COUNT\n";
8082 outs() << " count " << count
8083 << " (not x86_THREAD_STATE64_COUNT)\n";
8084 MachO::x86_thread_state64_t cpu64;
8086 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8087 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8088 begin += sizeof(MachO::x86_thread_state64_t);
8090 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8091 memcpy(&cpu64, begin, left);
8094 if (isLittleEndian != sys::IsLittleEndianHost)
8096 Print_x86_thread_state64_t(cpu64);
8097 } else if (flavor == MachO::x86_THREAD_STATE) {
8098 outs() << " flavor x86_THREAD_STATE\n";
8099 if (count == MachO::x86_THREAD_STATE_COUNT)
8100 outs() << " count x86_THREAD_STATE_COUNT\n";
8102 outs() << " count " << count
8103 << " (not x86_THREAD_STATE_COUNT)\n";
8104 struct MachO::x86_thread_state_t ts;
8106 if (left >= sizeof(MachO::x86_thread_state_t)) {
8107 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8108 begin += sizeof(MachO::x86_thread_state_t);
8110 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8111 memcpy(&ts, begin, left);
8114 if (isLittleEndian != sys::IsLittleEndianHost)
8116 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8117 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8118 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8119 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8121 outs() << "tsh.count " << ts.tsh.count
8122 << " (not x86_THREAD_STATE64_COUNT\n";
8123 Print_x86_thread_state64_t(ts.uts.ts64);
8125 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8126 << ts.tsh.count << "\n";
8128 } else if (flavor == MachO::x86_FLOAT_STATE) {
8129 outs() << " flavor x86_FLOAT_STATE\n";
8130 if (count == MachO::x86_FLOAT_STATE_COUNT)
8131 outs() << " count x86_FLOAT_STATE_COUNT\n";
8133 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
8134 struct MachO::x86_float_state_t fs;
8136 if (left >= sizeof(MachO::x86_float_state_t)) {
8137 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8138 begin += sizeof(MachO::x86_float_state_t);
8140 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8141 memcpy(&fs, begin, left);
8144 if (isLittleEndian != sys::IsLittleEndianHost)
8146 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8147 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
8148 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
8149 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8151 outs() << "fsh.count " << fs.fsh.count
8152 << " (not x86_FLOAT_STATE64_COUNT\n";
8153 Print_x86_float_state_t(fs.ufs.fs64);
8155 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8156 << fs.fsh.count << "\n";
8158 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8159 outs() << " flavor x86_EXCEPTION_STATE\n";
8160 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8161 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8163 outs() << " count " << count
8164 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8165 struct MachO::x86_exception_state_t es;
8167 if (left >= sizeof(MachO::x86_exception_state_t)) {
8168 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8169 begin += sizeof(MachO::x86_exception_state_t);
8171 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8172 memcpy(&es, begin, left);
8175 if (isLittleEndian != sys::IsLittleEndianHost)
8177 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8178 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
8179 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
8180 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8182 outs() << "\t esh.count " << es.esh.count
8183 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8184 Print_x86_exception_state_t(es.ues.es64);
8186 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8187 << es.esh.count << "\n";
8190 outs() << " flavor " << flavor << " (unknown)\n";
8191 outs() << " count " << count << "\n";
8192 outs() << " state (unknown)\n";
8193 begin += count * sizeof(uint32_t);
8197 while (begin < end) {
8198 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8199 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8200 begin += sizeof(uint32_t);
8205 if (isLittleEndian != sys::IsLittleEndianHost)
8206 sys::swapByteOrder(flavor);
8207 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8208 memcpy((char *)&count, begin, sizeof(uint32_t));
8209 begin += sizeof(uint32_t);
8214 if (isLittleEndian != sys::IsLittleEndianHost)
8215 sys::swapByteOrder(count);
8216 outs() << " flavor " << flavor << "\n";
8217 outs() << " count " << count << "\n";
8218 outs() << " state (Unknown cputype/cpusubtype)\n";
8219 begin += count * sizeof(uint32_t);
8224 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8225 if (dl.cmd == MachO::LC_ID_DYLIB)
8226 outs() << " cmd LC_ID_DYLIB\n";
8227 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8228 outs() << " cmd LC_LOAD_DYLIB\n";
8229 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8230 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8231 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8232 outs() << " cmd LC_REEXPORT_DYLIB\n";
8233 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8234 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8235 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8236 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8238 outs() << " cmd " << dl.cmd << " (unknown)\n";
8239 outs() << " cmdsize " << dl.cmdsize;
8240 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8241 outs() << " Incorrect size\n";
8244 if (dl.dylib.name < dl.cmdsize) {
8245 const char *P = (const char *)(Ptr) + dl.dylib.name;
8246 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8248 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8250 outs() << " time stamp " << dl.dylib.timestamp << " ";
8251 time_t t = dl.dylib.timestamp;
8252 outs() << ctime(&t);
8253 outs() << " current version ";
8254 if (dl.dylib.current_version == 0xffffffff)
8257 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8258 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8259 << (dl.dylib.current_version & 0xff) << "\n";
8260 outs() << "compatibility version ";
8261 if (dl.dylib.compatibility_version == 0xffffffff)
8264 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8265 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8266 << (dl.dylib.compatibility_version & 0xff) << "\n";
8269 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8270 uint32_t object_size) {
8271 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8272 outs() << " cmd LC_FUNCTION_STARTS\n";
8273 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8274 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8275 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8276 outs() << " cmd LC_FUNCTION_STARTS\n";
8277 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8278 outs() << " cmd LC_DATA_IN_CODE\n";
8279 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8280 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8281 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8282 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8284 outs() << " cmd " << ld.cmd << " (?)\n";
8285 outs() << " cmdsize " << ld.cmdsize;
8286 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8287 outs() << " Incorrect size\n";
8290 outs() << " dataoff " << ld.dataoff;
8291 if (ld.dataoff > object_size)
8292 outs() << " (past end of file)\n";
8295 outs() << " datasize " << ld.datasize;
8296 uint64_t big_size = ld.dataoff;
8297 big_size += ld.datasize;
8298 if (big_size > object_size)
8299 outs() << " (past end of file)\n";
8304 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8305 uint32_t cputype, bool verbose) {
8306 StringRef Buf = Obj->getData();
8308 for (const auto &Command : Obj->load_commands()) {
8309 outs() << "Load command " << Index++ << "\n";
8310 if (Command.C.cmd == MachO::LC_SEGMENT) {
8311 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8312 const char *sg_segname = SLC.segname;
8313 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8314 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8315 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8317 for (unsigned j = 0; j < SLC.nsects; j++) {
8318 MachO::section S = Obj->getSection(Command, j);
8319 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8320 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8321 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8323 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8324 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8325 const char *sg_segname = SLC_64.segname;
8326 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8327 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8328 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8329 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8330 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8331 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8332 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8333 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8334 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8335 sg_segname, filetype, Buf.size(), verbose);
8337 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8338 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8339 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
8340 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8341 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8342 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8343 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8345 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8346 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8347 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8348 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8349 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8350 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8351 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8352 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8353 PrintDyldLoadCommand(Dyld, Command.Ptr);
8354 } else if (Command.C.cmd == MachO::LC_UUID) {
8355 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8356 PrintUuidLoadCommand(Uuid);
8357 } else if (Command.C.cmd == MachO::LC_RPATH) {
8358 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8359 PrintRpathLoadCommand(Rpath, Command.Ptr);
8360 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
8361 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
8362 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8363 PrintVersionMinLoadCommand(Vd);
8364 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8365 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8366 PrintSourceVersionCommand(Sd);
8367 } else if (Command.C.cmd == MachO::LC_MAIN) {
8368 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8369 PrintEntryPointCommand(Ep);
8370 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
8371 MachO::encryption_info_command Ei =
8372 Obj->getEncryptionInfoCommand(Command);
8373 PrintEncryptionInfoCommand(Ei, Buf.size());
8374 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
8375 MachO::encryption_info_command_64 Ei =
8376 Obj->getEncryptionInfoCommand64(Command);
8377 PrintEncryptionInfoCommand64(Ei, Buf.size());
8378 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
8379 MachO::linker_option_command Lo =
8380 Obj->getLinkerOptionLoadCommand(Command);
8381 PrintLinkerOptionCommand(Lo, Command.Ptr);
8382 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8383 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8384 PrintSubFrameworkCommand(Sf, Command.Ptr);
8385 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8386 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8387 PrintSubUmbrellaCommand(Sf, Command.Ptr);
8388 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8389 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8390 PrintSubLibraryCommand(Sl, Command.Ptr);
8391 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8392 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8393 PrintSubClientCommand(Sc, Command.Ptr);
8394 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8395 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8396 PrintRoutinesCommand(Rc);
8397 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8398 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8399 PrintRoutinesCommand64(Rc);
8400 } else if (Command.C.cmd == MachO::LC_THREAD ||
8401 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8402 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8403 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
8404 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8405 Command.C.cmd == MachO::LC_ID_DYLIB ||
8406 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8407 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8408 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8409 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
8410 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8411 PrintDylibCommand(Dl, Command.Ptr);
8412 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8413 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8414 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8415 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8416 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8417 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8418 MachO::linkedit_data_command Ld =
8419 Obj->getLinkeditDataLoadCommand(Command);
8420 PrintLinkEditDataCommand(Ld, Buf.size());
8422 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8424 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8425 // TODO: get and print the raw bytes of the load command.
8427 // TODO: print all the other kinds of load commands.
8431 static void getAndPrintMachHeader(const MachOObjectFile *Obj,
8432 uint32_t &filetype, uint32_t &cputype,
8434 if (Obj->is64Bit()) {
8435 MachO::mach_header_64 H_64;
8436 H_64 = Obj->getHeader64();
8437 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8438 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8439 filetype = H_64.filetype;
8440 cputype = H_64.cputype;
8442 MachO::mach_header H;
8443 H = Obj->getHeader();
8444 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8445 H.sizeofcmds, H.flags, verbose);
8446 filetype = H.filetype;
8447 cputype = H.cputype;
8451 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8452 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
8453 uint32_t filetype = 0;
8454 uint32_t cputype = 0;
8455 getAndPrintMachHeader(file, filetype, cputype, !NonVerbose);
8456 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
8459 //===----------------------------------------------------------------------===//
8460 // export trie dumping
8461 //===----------------------------------------------------------------------===//
8463 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
8464 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8465 uint64_t Flags = Entry.flags();
8466 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8467 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8468 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8469 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8470 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8471 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8472 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8474 outs() << "[re-export] ";
8476 outs() << format("0x%08llX ",
8477 Entry.address()); // FIXME:add in base address
8478 outs() << Entry.name();
8479 if (WeakDef || ThreadLocal || Resolver || Abs) {
8480 bool NeedsComma = false;
8483 outs() << "weak_def";
8489 outs() << "per-thread";
8495 outs() << "absolute";
8501 outs() << format("resolver=0x%08llX", Entry.other());
8507 StringRef DylibName = "unknown";
8508 int Ordinal = Entry.other() - 1;
8509 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8510 if (Entry.otherName().empty())
8511 outs() << " (from " << DylibName << ")";
8513 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
8519 //===----------------------------------------------------------------------===//
8520 // rebase table dumping
8521 //===----------------------------------------------------------------------===//
8526 SegInfo(const object::MachOObjectFile *Obj);
8528 StringRef segmentName(uint32_t SegIndex);
8529 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8530 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
8533 struct SectionInfo {
8536 StringRef SectionName;
8537 StringRef SegmentName;
8538 uint64_t OffsetInSegment;
8539 uint64_t SegmentStartAddress;
8540 uint32_t SegmentIndex;
8542 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8543 SmallVector<SectionInfo, 32> Sections;
8547 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8548 // Build table of sections so segIndex/offset pairs can be translated.
8549 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
8550 StringRef CurSegName;
8551 uint64_t CurSegAddress;
8552 for (const SectionRef &Section : Obj->sections()) {
8554 error(Section.getName(Info.SectionName));
8555 Info.Address = Section.getAddress();
8556 Info.Size = Section.getSize();
8558 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8559 if (!Info.SegmentName.equals(CurSegName)) {
8561 CurSegName = Info.SegmentName;
8562 CurSegAddress = Info.Address;
8564 Info.SegmentIndex = CurSegIndex - 1;
8565 Info.OffsetInSegment = Info.Address - CurSegAddress;
8566 Info.SegmentStartAddress = CurSegAddress;
8567 Sections.push_back(Info);
8571 StringRef SegInfo::segmentName(uint32_t SegIndex) {
8572 for (const SectionInfo &SI : Sections) {
8573 if (SI.SegmentIndex == SegIndex)
8574 return SI.SegmentName;
8576 llvm_unreachable("invalid segIndex");
8579 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8580 uint64_t OffsetInSeg) {
8581 for (const SectionInfo &SI : Sections) {
8582 if (SI.SegmentIndex != SegIndex)
8584 if (SI.OffsetInSegment > OffsetInSeg)
8586 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8590 llvm_unreachable("segIndex and offset not in any section");
8593 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8594 return findSection(SegIndex, OffsetInSeg).SectionName;
8597 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8598 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8599 return SI.SegmentStartAddress + OffsetInSeg;
8602 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8603 // Build table of sections so names can used in final output.
8604 SegInfo sectionTable(Obj);
8606 outs() << "segment section address type\n";
8607 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8608 uint32_t SegIndex = Entry.segmentIndex();
8609 uint64_t OffsetInSeg = Entry.segmentOffset();
8610 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8611 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8612 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8614 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
8615 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8616 SegmentName.str().c_str(), SectionName.str().c_str(),
8617 Address, Entry.typeName().str().c_str());
8621 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8622 StringRef DylibName;
8624 case MachO::BIND_SPECIAL_DYLIB_SELF:
8625 return "this-image";
8626 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8627 return "main-executable";
8628 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8629 return "flat-namespace";
8632 std::error_code EC =
8633 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
8635 return "<<bad library ordinal>>";
8639 return "<<unknown special ordinal>>";
8642 //===----------------------------------------------------------------------===//
8643 // bind table dumping
8644 //===----------------------------------------------------------------------===//
8646 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8647 // Build table of sections so names can used in final output.
8648 SegInfo sectionTable(Obj);
8650 outs() << "segment section address type "
8651 "addend dylib symbol\n";
8652 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8653 uint32_t SegIndex = Entry.segmentIndex();
8654 uint64_t OffsetInSeg = Entry.segmentOffset();
8655 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8656 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8657 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8659 // Table lines look like:
8660 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
8662 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
8663 Attr = " (weak_import)";
8664 outs() << left_justify(SegmentName, 8) << " "
8665 << left_justify(SectionName, 18) << " "
8666 << format_hex(Address, 10, true) << " "
8667 << left_justify(Entry.typeName(), 8) << " "
8668 << format_decimal(Entry.addend(), 8) << " "
8669 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8670 << Entry.symbolName() << Attr << "\n";
8674 //===----------------------------------------------------------------------===//
8675 // lazy bind table dumping
8676 //===----------------------------------------------------------------------===//
8678 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8679 // Build table of sections so names can used in final output.
8680 SegInfo sectionTable(Obj);
8682 outs() << "segment section address "
8684 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8685 uint32_t SegIndex = Entry.segmentIndex();
8686 uint64_t OffsetInSeg = Entry.segmentOffset();
8687 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8688 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8689 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8691 // Table lines look like:
8692 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
8693 outs() << left_justify(SegmentName, 8) << " "
8694 << left_justify(SectionName, 18) << " "
8695 << format_hex(Address, 10, true) << " "
8696 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8697 << Entry.symbolName() << "\n";
8701 //===----------------------------------------------------------------------===//
8702 // weak bind table dumping
8703 //===----------------------------------------------------------------------===//
8705 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8706 // Build table of sections so names can used in final output.
8707 SegInfo sectionTable(Obj);
8709 outs() << "segment section address "
8710 "type addend symbol\n";
8711 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8712 // Strong symbols don't have a location to update.
8713 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
8714 outs() << " strong "
8715 << Entry.symbolName() << "\n";
8718 uint32_t SegIndex = Entry.segmentIndex();
8719 uint64_t OffsetInSeg = Entry.segmentOffset();
8720 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8721 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8722 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8724 // Table lines look like:
8725 // __DATA __data 0x00001000 pointer 0 _foo
8726 outs() << left_justify(SegmentName, 8) << " "
8727 << left_justify(SectionName, 18) << " "
8728 << format_hex(Address, 10, true) << " "
8729 << left_justify(Entry.typeName(), 8) << " "
8730 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8735 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
8736 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8737 // information for that address. If the address is found its binding symbol
8738 // name is returned. If not nullptr is returned.
8739 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8740 struct DisassembleInfo *info) {
8741 if (info->bindtable == nullptr) {
8742 info->bindtable = new (BindTable);
8743 SegInfo sectionTable(info->O);
8744 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8745 uint32_t SegIndex = Entry.segmentIndex();
8746 uint64_t OffsetInSeg = Entry.segmentOffset();
8747 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8748 const char *SymbolName = nullptr;
8749 StringRef name = Entry.symbolName();
8751 SymbolName = name.data();
8752 info->bindtable->push_back(std::make_pair(Address, SymbolName));
8755 for (bind_table_iterator BI = info->bindtable->begin(),
8756 BE = info->bindtable->end();
8758 uint64_t Address = BI->first;
8759 if (ReferenceValue == Address) {
8760 const char *SymbolName = BI->second;