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();
5891 CommentStream.resync();
5894 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5895 StringRef DisSegName, StringRef DisSectName) {
5896 const char *McpuDefault = nullptr;
5897 const Target *ThumbTarget = nullptr;
5898 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
5900 // GetTarget prints out stuff.
5903 if (MCPU.empty() && McpuDefault)
5906 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
5907 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
5909 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
5911 // Package up features to be passed to target/subtarget
5912 std::string FeaturesStr;
5913 if (MAttrs.size()) {
5914 SubtargetFeatures Features;
5915 for (unsigned i = 0; i != MAttrs.size(); ++i)
5916 Features.AddFeature(MAttrs[i]);
5917 FeaturesStr = Features.getString();
5920 // Set up disassembler.
5921 std::unique_ptr<const MCRegisterInfo> MRI(
5922 TheTarget->createMCRegInfo(TripleName));
5923 std::unique_ptr<const MCAsmInfo> AsmInfo(
5924 TheTarget->createMCAsmInfo(*MRI, TripleName));
5925 std::unique_ptr<const MCSubtargetInfo> STI(
5926 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
5927 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
5928 std::unique_ptr<MCDisassembler> DisAsm(
5929 TheTarget->createMCDisassembler(*STI, Ctx));
5930 std::unique_ptr<MCSymbolizer> Symbolizer;
5931 struct DisassembleInfo SymbolizerInfo;
5932 std::unique_ptr<MCRelocationInfo> RelInfo(
5933 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5935 Symbolizer.reset(TheTarget->createMCSymbolizer(
5936 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5937 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
5938 DisAsm->setSymbolizer(std::move(Symbolizer));
5940 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
5941 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
5942 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
5943 // Set the display preference for hex vs. decimal immediates.
5944 IP->setPrintImmHex(PrintImmHex);
5945 // Comment stream and backing vector.
5946 SmallString<128> CommentsToEmit;
5947 raw_svector_ostream CommentStream(CommentsToEmit);
5948 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5949 // if it is done then arm64 comments for string literals don't get printed
5950 // and some constant get printed instead and not setting it causes intel
5951 // (32-bit and 64-bit) comments printed with different spacing before the
5952 // comment causing different diffs with the 'C' disassembler library API.
5953 // IP->setCommentStream(CommentStream);
5955 if (!AsmInfo || !STI || !DisAsm || !IP) {
5956 errs() << "error: couldn't initialize disassembler for target "
5957 << TripleName << '\n';
5961 // Set up thumb disassembler.
5962 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5963 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5964 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
5965 std::unique_ptr<MCDisassembler> ThumbDisAsm;
5966 std::unique_ptr<MCInstPrinter> ThumbIP;
5967 std::unique_ptr<MCContext> ThumbCtx;
5968 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5969 struct DisassembleInfo ThumbSymbolizerInfo;
5970 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
5972 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
5974 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
5976 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
5977 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
5978 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
5979 MCContext *PtrThumbCtx = ThumbCtx.get();
5981 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
5983 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
5984 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5985 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
5986 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
5988 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
5989 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
5990 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
5991 *ThumbInstrInfo, *ThumbMRI));
5992 // Set the display preference for hex vs. decimal immediates.
5993 ThumbIP->setPrintImmHex(PrintImmHex);
5996 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
5997 errs() << "error: couldn't initialize disassembler for target "
5998 << ThumbTripleName << '\n';
6002 MachO::mach_header Header = MachOOF->getHeader();
6004 // FIXME: Using the -cfg command line option, this code used to be able to
6005 // annotate relocations with the referenced symbol's name, and if this was
6006 // inside a __[cf]string section, the data it points to. This is now replaced
6007 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
6008 std::vector<SectionRef> Sections;
6009 std::vector<SymbolRef> Symbols;
6010 SmallVector<uint64_t, 8> FoundFns;
6011 uint64_t BaseSegmentAddress;
6013 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
6014 BaseSegmentAddress);
6016 // Sort the symbols by address, just in case they didn't come in that way.
6017 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
6019 // Build a data in code table that is sorted on by the address of each entry.
6020 uint64_t BaseAddress = 0;
6021 if (Header.filetype == MachO::MH_OBJECT)
6022 BaseAddress = Sections[0].getAddress();
6024 BaseAddress = BaseSegmentAddress;
6026 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
6029 DI->getOffset(Offset);
6030 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6032 array_pod_sort(Dices.begin(), Dices.end());
6035 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6037 raw_ostream &DebugOut = nulls();
6040 std::unique_ptr<DIContext> diContext;
6041 ObjectFile *DbgObj = MachOOF;
6042 // Try to find debug info and set up the DIContext for it.
6044 // A separate DSym file path was specified, parse it as a macho file,
6045 // get the sections and supply it to the section name parsing machinery.
6046 if (!DSYMFile.empty()) {
6047 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
6048 MemoryBuffer::getFileOrSTDIN(DSYMFile);
6049 if (std::error_code EC = BufOrErr.getError()) {
6050 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
6054 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6059 // Setup the DIContext
6060 diContext.reset(new DWARFContextInMemory(*DbgObj));
6063 if (FilterSections.size() == 0)
6064 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
6066 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
6068 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6071 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
6073 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
6074 if (SegmentName != DisSegName)
6078 Sections[SectIdx].getContents(BytesStr);
6079 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6081 uint64_t SectAddress = Sections[SectIdx].getAddress();
6083 bool symbolTableWorked = false;
6085 // Parse relocations.
6086 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
6087 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
6088 uint64_t RelocOffset = Reloc.getOffset();
6089 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6090 RelocOffset -= SectionAddress;
6092 symbol_iterator RelocSym = Reloc.getSymbol();
6094 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
6096 array_pod_sort(Relocs.begin(), Relocs.end());
6098 // Create a map of symbol addresses to symbol names for use by
6099 // the SymbolizerSymbolLookUp() routine.
6100 SymbolAddressMap AddrMap;
6101 bool DisSymNameFound = false;
6102 for (const SymbolRef &Symbol : MachOOF->symbols()) {
6103 SymbolRef::Type ST = Symbol.getType();
6104 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6105 ST == SymbolRef::ST_Other) {
6106 uint64_t Address = Symbol.getValue();
6107 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6108 if (std::error_code EC = SymNameOrErr.getError())
6109 report_fatal_error(EC.message());
6110 StringRef SymName = *SymNameOrErr;
6111 AddrMap[Address] = SymName;
6112 if (!DisSymName.empty() && DisSymName == SymName)
6113 DisSymNameFound = true;
6116 if (!DisSymName.empty() && !DisSymNameFound) {
6117 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6120 // Set up the block of info used by the Symbolizer call backs.
6121 SymbolizerInfo.verbose = !NoSymbolicOperands;
6122 SymbolizerInfo.O = MachOOF;
6123 SymbolizerInfo.S = Sections[SectIdx];
6124 SymbolizerInfo.AddrMap = &AddrMap;
6125 SymbolizerInfo.Sections = &Sections;
6126 SymbolizerInfo.class_name = nullptr;
6127 SymbolizerInfo.selector_name = nullptr;
6128 SymbolizerInfo.method = nullptr;
6129 SymbolizerInfo.demangled_name = nullptr;
6130 SymbolizerInfo.bindtable = nullptr;
6131 SymbolizerInfo.adrp_addr = 0;
6132 SymbolizerInfo.adrp_inst = 0;
6133 // Same for the ThumbSymbolizer
6134 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
6135 ThumbSymbolizerInfo.O = MachOOF;
6136 ThumbSymbolizerInfo.S = Sections[SectIdx];
6137 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6138 ThumbSymbolizerInfo.Sections = &Sections;
6139 ThumbSymbolizerInfo.class_name = nullptr;
6140 ThumbSymbolizerInfo.selector_name = nullptr;
6141 ThumbSymbolizerInfo.method = nullptr;
6142 ThumbSymbolizerInfo.demangled_name = nullptr;
6143 ThumbSymbolizerInfo.bindtable = nullptr;
6144 ThumbSymbolizerInfo.adrp_addr = 0;
6145 ThumbSymbolizerInfo.adrp_inst = 0;
6147 // Disassemble symbol by symbol.
6148 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
6149 ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6150 if (std::error_code EC = SymNameOrErr.getError())
6151 report_fatal_error(EC.message());
6152 StringRef SymName = *SymNameOrErr;
6154 SymbolRef::Type ST = Symbols[SymIdx].getType();
6155 if (ST != SymbolRef::ST_Function)
6158 // Make sure the symbol is defined in this section.
6159 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
6163 // If we are only disassembling one symbol see if this is that symbol.
6164 if (!DisSymName.empty() && DisSymName != SymName)
6167 // Start at the address of the symbol relative to the section's address.
6168 uint64_t Start = Symbols[SymIdx].getValue();
6169 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6170 Start -= SectionAddress;
6172 // Stop disassembling either at the beginning of the next symbol or at
6173 // the end of the section.
6174 bool containsNextSym = false;
6175 uint64_t NextSym = 0;
6176 uint64_t NextSymIdx = SymIdx + 1;
6177 while (Symbols.size() > NextSymIdx) {
6178 SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
6179 if (NextSymType == SymbolRef::ST_Function) {
6181 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
6182 NextSym = Symbols[NextSymIdx].getValue();
6183 NextSym -= SectionAddress;
6189 uint64_t SectSize = Sections[SectIdx].getSize();
6190 uint64_t End = containsNextSym ? NextSym : SectSize;
6193 symbolTableWorked = true;
6195 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6197 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6199 outs() << SymName << ":\n";
6200 DILineInfo lastLine;
6201 for (uint64_t Index = Start; Index < End; Index += Size) {
6204 uint64_t PC = SectAddress + Index;
6205 if (!NoLeadingAddr) {
6206 if (FullLeadingAddr) {
6207 if (MachOOF->is64Bit())
6208 outs() << format("%016" PRIx64, PC);
6210 outs() << format("%08" PRIx64, PC);
6212 outs() << format("%8" PRIx64 ":", PC);
6218 // Check the data in code table here to see if this is data not an
6219 // instruction to be disassembled.
6221 Dice.push_back(std::make_pair(PC, DiceRef()));
6222 dice_table_iterator DTI =
6223 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6224 compareDiceTableEntries);
6225 if (DTI != Dices.end()) {
6227 DTI->second.getLength(Length);
6229 DTI->second.getKind(Kind);
6230 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
6231 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6232 (PC == (DTI->first + Length - 1)) && (Length & 1))
6237 SmallVector<char, 64> AnnotationsBytes;
6238 raw_svector_ostream Annotations(AnnotationsBytes);
6242 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
6243 PC, DebugOut, Annotations);
6245 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
6246 DebugOut, Annotations);
6248 if (!NoShowRawInsn) {
6249 dumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, Size), outs());
6251 formatted_raw_ostream FormattedOS(outs());
6252 Annotations.flush();
6253 StringRef AnnotationsStr = Annotations.str();
6255 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
6257 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
6258 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
6260 // Print debug info.
6262 DILineInfo dli = diContext->getLineInfoForAddress(PC);
6263 // Print valid line info if it changed.
6264 if (dli != lastLine && dli.Line != 0)
6265 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6271 unsigned int Arch = MachOOF->getArch();
6272 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6273 outs() << format("\t.byte 0x%02x #bad opcode\n",
6274 *(Bytes.data() + Index) & 0xff);
6275 Size = 1; // skip exactly one illegible byte and move on.
6276 } else if (Arch == Triple::aarch64) {
6277 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6278 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6279 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6280 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6281 outs() << format("\t.long\t0x%08x\n", opcode);
6284 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6286 Size = 1; // skip illegible bytes
6291 if (!symbolTableWorked) {
6292 // Reading the symbol table didn't work, disassemble the whole section.
6293 uint64_t SectAddress = Sections[SectIdx].getAddress();
6294 uint64_t SectSize = Sections[SectIdx].getSize();
6296 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
6299 uint64_t PC = SectAddress + Index;
6300 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6301 DebugOut, nulls())) {
6302 if (!NoLeadingAddr) {
6303 if (FullLeadingAddr) {
6304 if (MachOOF->is64Bit())
6305 outs() << format("%016" PRIx64, PC);
6307 outs() << format("%08" PRIx64, PC);
6309 outs() << format("%8" PRIx64 ":", PC);
6312 if (!NoShowRawInsn) {
6314 dumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, InstSize), outs());
6316 IP->printInst(&Inst, outs(), "", *STI);
6319 unsigned int Arch = MachOOF->getArch();
6320 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6321 outs() << format("\t.byte 0x%02x #bad opcode\n",
6322 *(Bytes.data() + Index) & 0xff);
6323 InstSize = 1; // skip exactly one illegible byte and move on.
6325 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6327 InstSize = 1; // skip illegible bytes
6332 // The TripleName's need to be reset if we are called again for a different
6335 ThumbTripleName = "";
6337 if (SymbolizerInfo.method != nullptr)
6338 free(SymbolizerInfo.method);
6339 if (SymbolizerInfo.demangled_name != nullptr)
6340 free(SymbolizerInfo.demangled_name);
6341 if (SymbolizerInfo.bindtable != nullptr)
6342 delete SymbolizerInfo.bindtable;
6343 if (ThumbSymbolizerInfo.method != nullptr)
6344 free(ThumbSymbolizerInfo.method);
6345 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6346 free(ThumbSymbolizerInfo.demangled_name);
6347 if (ThumbSymbolizerInfo.bindtable != nullptr)
6348 delete ThumbSymbolizerInfo.bindtable;
6352 //===----------------------------------------------------------------------===//
6353 // __compact_unwind section dumping
6354 //===----------------------------------------------------------------------===//
6358 template <typename T> static uint64_t readNext(const char *&Buf) {
6359 using llvm::support::little;
6360 using llvm::support::unaligned;
6362 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6367 struct CompactUnwindEntry {
6368 uint32_t OffsetInSection;
6370 uint64_t FunctionAddr;
6372 uint32_t CompactEncoding;
6373 uint64_t PersonalityAddr;
6376 RelocationRef FunctionReloc;
6377 RelocationRef PersonalityReloc;
6378 RelocationRef LSDAReloc;
6380 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
6381 : OffsetInSection(Offset) {
6383 read<uint64_t>(Contents.data() + Offset);
6385 read<uint32_t>(Contents.data() + Offset);
6389 template <typename UIntPtr> void read(const char *Buf) {
6390 FunctionAddr = readNext<UIntPtr>(Buf);
6391 Length = readNext<uint32_t>(Buf);
6392 CompactEncoding = readNext<uint32_t>(Buf);
6393 PersonalityAddr = readNext<UIntPtr>(Buf);
6394 LSDAAddr = readNext<UIntPtr>(Buf);
6399 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
6400 /// and data being relocated, determine the best base Name and Addend to use for
6401 /// display purposes.
6403 /// 1. An Extern relocation will directly reference a symbol (and the data is
6404 /// then already an addend), so use that.
6405 /// 2. Otherwise the data is an offset in the object file's layout; try to find
6406 // a symbol before it in the same section, and use the offset from there.
6407 /// 3. Finally, if all that fails, fall back to an offset from the start of the
6408 /// referenced section.
6409 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6410 std::map<uint64_t, SymbolRef> &Symbols,
6411 const RelocationRef &Reloc, uint64_t Addr,
6412 StringRef &Name, uint64_t &Addend) {
6413 if (Reloc.getSymbol() != Obj->symbol_end()) {
6414 ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6415 if (std::error_code EC = NameOrErr.getError())
6416 report_fatal_error(EC.message());
6422 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
6423 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
6425 uint64_t SectionAddr = RelocSection.getAddress();
6427 auto Sym = Symbols.upper_bound(Addr);
6428 if (Sym == Symbols.begin()) {
6429 // The first symbol in the object is after this reference, the best we can
6430 // do is section-relative notation.
6431 RelocSection.getName(Name);
6432 Addend = Addr - SectionAddr;
6436 // Go back one so that SymbolAddress <= Addr.
6439 section_iterator SymSection = Obj->section_end();
6440 Sym->second.getSection(SymSection);
6441 if (RelocSection == *SymSection) {
6442 // There's a valid symbol in the same section before this reference.
6443 ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6444 if (std::error_code EC = NameOrErr.getError())
6445 report_fatal_error(EC.message());
6447 Addend = Addr - Sym->first;
6451 // There is a symbol before this reference, but it's in a different
6452 // section. Probably not helpful to mention it, so use the section name.
6453 RelocSection.getName(Name);
6454 Addend = Addr - SectionAddr;
6457 static void printUnwindRelocDest(const MachOObjectFile *Obj,
6458 std::map<uint64_t, SymbolRef> &Symbols,
6459 const RelocationRef &Reloc, uint64_t Addr) {
6463 if (!Reloc.getObject())
6466 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6470 outs() << " + " << format("0x%" PRIx64, Addend);
6474 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6475 std::map<uint64_t, SymbolRef> &Symbols,
6476 const SectionRef &CompactUnwind) {
6478 assert(Obj->isLittleEndian() &&
6479 "There should not be a big-endian .o with __compact_unwind");
6481 bool Is64 = Obj->is64Bit();
6482 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6483 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6486 CompactUnwind.getContents(Contents);
6488 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6490 // First populate the initial raw offsets, encodings and so on from the entry.
6491 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6492 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6493 CompactUnwinds.push_back(Entry);
6496 // Next we need to look at the relocations to find out what objects are
6497 // actually being referred to.
6498 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
6499 uint64_t RelocAddress = Reloc.getOffset();
6501 uint32_t EntryIdx = RelocAddress / EntrySize;
6502 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6503 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6505 if (OffsetInEntry == 0)
6506 Entry.FunctionReloc = Reloc;
6507 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6508 Entry.PersonalityReloc = Reloc;
6509 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6510 Entry.LSDAReloc = Reloc;
6512 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6515 // Finally, we're ready to print the data we've gathered.
6516 outs() << "Contents of __compact_unwind section:\n";
6517 for (auto &Entry : CompactUnwinds) {
6518 outs() << " Entry at offset "
6519 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
6521 // 1. Start of the region this entry applies to.
6522 outs() << " start: " << format("0x%" PRIx64,
6523 Entry.FunctionAddr) << ' ';
6524 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
6527 // 2. Length of the region this entry applies to.
6528 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6530 // 3. The 32-bit compact encoding.
6531 outs() << " compact encoding: "
6532 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
6534 // 4. The personality function, if present.
6535 if (Entry.PersonalityReloc.getObject()) {
6536 outs() << " personality function: "
6537 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
6538 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6539 Entry.PersonalityAddr);
6543 // 5. This entry's language-specific data area.
6544 if (Entry.LSDAReloc.getObject()) {
6545 outs() << " LSDA: " << format("0x%" PRIx64,
6546 Entry.LSDAAddr) << ' ';
6547 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6553 //===----------------------------------------------------------------------===//
6554 // __unwind_info section dumping
6555 //===----------------------------------------------------------------------===//
6557 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6558 const char *Pos = PageStart;
6559 uint32_t Kind = readNext<uint32_t>(Pos);
6561 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6563 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6564 uint16_t NumEntries = readNext<uint16_t>(Pos);
6566 Pos = PageStart + EntriesStart;
6567 for (unsigned i = 0; i < NumEntries; ++i) {
6568 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6569 uint32_t Encoding = readNext<uint32_t>(Pos);
6571 outs() << " [" << i << "]: "
6572 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6574 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
6578 static void printCompressedSecondLevelUnwindPage(
6579 const char *PageStart, uint32_t FunctionBase,
6580 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6581 const char *Pos = PageStart;
6582 uint32_t Kind = readNext<uint32_t>(Pos);
6584 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6586 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6587 uint16_t NumEntries = readNext<uint16_t>(Pos);
6589 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6590 readNext<uint16_t>(Pos);
6591 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6592 PageStart + EncodingsStart);
6594 Pos = PageStart + EntriesStart;
6595 for (unsigned i = 0; i < NumEntries; ++i) {
6596 uint32_t Entry = readNext<uint32_t>(Pos);
6597 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6598 uint32_t EncodingIdx = Entry >> 24;
6601 if (EncodingIdx < CommonEncodings.size())
6602 Encoding = CommonEncodings[EncodingIdx];
6604 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6606 outs() << " [" << i << "]: "
6607 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6609 << "encoding[" << EncodingIdx
6610 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
6614 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6615 std::map<uint64_t, SymbolRef> &Symbols,
6616 const SectionRef &UnwindInfo) {
6618 assert(Obj->isLittleEndian() &&
6619 "There should not be a big-endian .o with __unwind_info");
6621 outs() << "Contents of __unwind_info section:\n";
6624 UnwindInfo.getContents(Contents);
6625 const char *Pos = Contents.data();
6627 //===----------------------------------
6629 //===----------------------------------
6631 uint32_t Version = readNext<uint32_t>(Pos);
6632 outs() << " Version: "
6633 << format("0x%" PRIx32, Version) << '\n';
6634 assert(Version == 1 && "only understand version 1");
6636 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6637 outs() << " Common encodings array section offset: "
6638 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6639 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6640 outs() << " Number of common encodings in array: "
6641 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6643 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6644 outs() << " Personality function array section offset: "
6645 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6646 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6647 outs() << " Number of personality functions in array: "
6648 << format("0x%" PRIx32, NumPersonalities) << '\n';
6650 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6651 outs() << " Index array section offset: "
6652 << format("0x%" PRIx32, IndicesStart) << '\n';
6653 uint32_t NumIndices = readNext<uint32_t>(Pos);
6654 outs() << " Number of indices in array: "
6655 << format("0x%" PRIx32, NumIndices) << '\n';
6657 //===----------------------------------
6658 // A shared list of common encodings
6659 //===----------------------------------
6661 // These occupy indices in the range [0, N] whenever an encoding is referenced
6662 // from a compressed 2nd level index table. In practice the linker only
6663 // creates ~128 of these, so that indices are available to embed encodings in
6664 // the 2nd level index.
6666 SmallVector<uint32_t, 64> CommonEncodings;
6667 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6668 Pos = Contents.data() + CommonEncodingsStart;
6669 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6670 uint32_t Encoding = readNext<uint32_t>(Pos);
6671 CommonEncodings.push_back(Encoding);
6673 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6677 //===----------------------------------
6678 // Personality functions used in this executable
6679 //===----------------------------------
6681 // There should be only a handful of these (one per source language,
6682 // roughly). Particularly since they only get 2 bits in the compact encoding.
6684 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6685 Pos = Contents.data() + PersonalitiesStart;
6686 for (unsigned i = 0; i < NumPersonalities; ++i) {
6687 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6688 outs() << " personality[" << i + 1
6689 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6692 //===----------------------------------
6693 // The level 1 index entries
6694 //===----------------------------------
6696 // These specify an approximate place to start searching for the more detailed
6697 // information, sorted by PC.
6700 uint32_t FunctionOffset;
6701 uint32_t SecondLevelPageStart;
6705 SmallVector<IndexEntry, 4> IndexEntries;
6707 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6708 Pos = Contents.data() + IndicesStart;
6709 for (unsigned i = 0; i < NumIndices; ++i) {
6712 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6713 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6714 Entry.LSDAStart = readNext<uint32_t>(Pos);
6715 IndexEntries.push_back(Entry);
6717 outs() << " [" << i << "]: "
6718 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6720 << "2nd level page offset="
6721 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
6722 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
6725 //===----------------------------------
6726 // Next come the LSDA tables
6727 //===----------------------------------
6729 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6730 // the first top-level index's LSDAOffset to the last (sentinel).
6732 outs() << " LSDA descriptors:\n";
6733 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6734 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6735 (2 * sizeof(uint32_t));
6736 for (int i = 0; i < NumLSDAs; ++i) {
6737 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6738 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6739 outs() << " [" << i << "]: "
6740 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6742 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
6745 //===----------------------------------
6746 // Finally, the 2nd level indices
6747 //===----------------------------------
6749 // Generally these are 4K in size, and have 2 possible forms:
6750 // + Regular stores up to 511 entries with disparate encodings
6751 // + Compressed stores up to 1021 entries if few enough compact encoding
6753 outs() << " Second level indices:\n";
6754 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6755 // The final sentinel top-level index has no associated 2nd level page
6756 if (IndexEntries[i].SecondLevelPageStart == 0)
6759 outs() << " Second level index[" << i << "]: "
6760 << "offset in section="
6761 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6763 << "base function offset="
6764 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6766 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
6767 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
6769 printRegularSecondLevelUnwindPage(Pos);
6771 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6774 llvm_unreachable("Do not know how to print this kind of 2nd level page");
6778 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6779 std::map<uint64_t, SymbolRef> Symbols;
6780 for (const SymbolRef &SymRef : Obj->symbols()) {
6781 // Discard any undefined or absolute symbols. They're not going to take part
6782 // in the convenience lookup for unwind info and just take up resources.
6783 section_iterator Section = Obj->section_end();
6784 SymRef.getSection(Section);
6785 if (Section == Obj->section_end())
6788 uint64_t Addr = SymRef.getValue();
6789 Symbols.insert(std::make_pair(Addr, SymRef));
6792 for (const SectionRef &Section : Obj->sections()) {
6794 Section.getName(SectName);
6795 if (SectName == "__compact_unwind")
6796 printMachOCompactUnwindSection(Obj, Symbols, Section);
6797 else if (SectName == "__unwind_info")
6798 printMachOUnwindInfoSection(Obj, Symbols, Section);
6799 else if (SectName == "__eh_frame")
6800 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
6804 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6805 uint32_t cpusubtype, uint32_t filetype,
6806 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6808 outs() << "Mach header\n";
6809 outs() << " magic cputype cpusubtype caps filetype ncmds "
6810 "sizeofcmds flags\n";
6812 if (magic == MachO::MH_MAGIC)
6813 outs() << " MH_MAGIC";
6814 else if (magic == MachO::MH_MAGIC_64)
6815 outs() << "MH_MAGIC_64";
6817 outs() << format(" 0x%08" PRIx32, magic);
6819 case MachO::CPU_TYPE_I386:
6821 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6822 case MachO::CPU_SUBTYPE_I386_ALL:
6826 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6830 case MachO::CPU_TYPE_X86_64:
6831 outs() << " X86_64";
6832 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6833 case MachO::CPU_SUBTYPE_X86_64_ALL:
6836 case MachO::CPU_SUBTYPE_X86_64_H:
6837 outs() << " Haswell";
6840 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6844 case MachO::CPU_TYPE_ARM:
6846 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6847 case MachO::CPU_SUBTYPE_ARM_ALL:
6850 case MachO::CPU_SUBTYPE_ARM_V4T:
6853 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6856 case MachO::CPU_SUBTYPE_ARM_XSCALE:
6857 outs() << " XSCALE";
6859 case MachO::CPU_SUBTYPE_ARM_V6:
6862 case MachO::CPU_SUBTYPE_ARM_V6M:
6865 case MachO::CPU_SUBTYPE_ARM_V7:
6868 case MachO::CPU_SUBTYPE_ARM_V7EM:
6871 case MachO::CPU_SUBTYPE_ARM_V7K:
6874 case MachO::CPU_SUBTYPE_ARM_V7M:
6877 case MachO::CPU_SUBTYPE_ARM_V7S:
6881 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6885 case MachO::CPU_TYPE_ARM64:
6887 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6888 case MachO::CPU_SUBTYPE_ARM64_ALL:
6892 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6896 case MachO::CPU_TYPE_POWERPC:
6898 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6899 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6903 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6907 case MachO::CPU_TYPE_POWERPC64:
6909 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6910 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6914 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6919 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
6922 outs() << format(" 0x%02" PRIx32,
6923 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
6926 case MachO::MH_OBJECT:
6927 outs() << " OBJECT";
6929 case MachO::MH_EXECUTE:
6930 outs() << " EXECUTE";
6932 case MachO::MH_FVMLIB:
6933 outs() << " FVMLIB";
6935 case MachO::MH_CORE:
6938 case MachO::MH_PRELOAD:
6939 outs() << " PRELOAD";
6941 case MachO::MH_DYLIB:
6944 case MachO::MH_DYLIB_STUB:
6945 outs() << " DYLIB_STUB";
6947 case MachO::MH_DYLINKER:
6948 outs() << " DYLINKER";
6950 case MachO::MH_BUNDLE:
6951 outs() << " BUNDLE";
6953 case MachO::MH_DSYM:
6956 case MachO::MH_KEXT_BUNDLE:
6957 outs() << " KEXTBUNDLE";
6960 outs() << format(" %10u", filetype);
6963 outs() << format(" %5u", ncmds);
6964 outs() << format(" %10u", sizeofcmds);
6966 if (f & MachO::MH_NOUNDEFS) {
6967 outs() << " NOUNDEFS";
6968 f &= ~MachO::MH_NOUNDEFS;
6970 if (f & MachO::MH_INCRLINK) {
6971 outs() << " INCRLINK";
6972 f &= ~MachO::MH_INCRLINK;
6974 if (f & MachO::MH_DYLDLINK) {
6975 outs() << " DYLDLINK";
6976 f &= ~MachO::MH_DYLDLINK;
6978 if (f & MachO::MH_BINDATLOAD) {
6979 outs() << " BINDATLOAD";
6980 f &= ~MachO::MH_BINDATLOAD;
6982 if (f & MachO::MH_PREBOUND) {
6983 outs() << " PREBOUND";
6984 f &= ~MachO::MH_PREBOUND;
6986 if (f & MachO::MH_SPLIT_SEGS) {
6987 outs() << " SPLIT_SEGS";
6988 f &= ~MachO::MH_SPLIT_SEGS;
6990 if (f & MachO::MH_LAZY_INIT) {
6991 outs() << " LAZY_INIT";
6992 f &= ~MachO::MH_LAZY_INIT;
6994 if (f & MachO::MH_TWOLEVEL) {
6995 outs() << " TWOLEVEL";
6996 f &= ~MachO::MH_TWOLEVEL;
6998 if (f & MachO::MH_FORCE_FLAT) {
6999 outs() << " FORCE_FLAT";
7000 f &= ~MachO::MH_FORCE_FLAT;
7002 if (f & MachO::MH_NOMULTIDEFS) {
7003 outs() << " NOMULTIDEFS";
7004 f &= ~MachO::MH_NOMULTIDEFS;
7006 if (f & MachO::MH_NOFIXPREBINDING) {
7007 outs() << " NOFIXPREBINDING";
7008 f &= ~MachO::MH_NOFIXPREBINDING;
7010 if (f & MachO::MH_PREBINDABLE) {
7011 outs() << " PREBINDABLE";
7012 f &= ~MachO::MH_PREBINDABLE;
7014 if (f & MachO::MH_ALLMODSBOUND) {
7015 outs() << " ALLMODSBOUND";
7016 f &= ~MachO::MH_ALLMODSBOUND;
7018 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7019 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7020 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7022 if (f & MachO::MH_CANONICAL) {
7023 outs() << " CANONICAL";
7024 f &= ~MachO::MH_CANONICAL;
7026 if (f & MachO::MH_WEAK_DEFINES) {
7027 outs() << " WEAK_DEFINES";
7028 f &= ~MachO::MH_WEAK_DEFINES;
7030 if (f & MachO::MH_BINDS_TO_WEAK) {
7031 outs() << " BINDS_TO_WEAK";
7032 f &= ~MachO::MH_BINDS_TO_WEAK;
7034 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7035 outs() << " ALLOW_STACK_EXECUTION";
7036 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7038 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7039 outs() << " DEAD_STRIPPABLE_DYLIB";
7040 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7042 if (f & MachO::MH_PIE) {
7044 f &= ~MachO::MH_PIE;
7046 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7047 outs() << " NO_REEXPORTED_DYLIBS";
7048 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7050 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7051 outs() << " MH_HAS_TLV_DESCRIPTORS";
7052 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7054 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7055 outs() << " MH_NO_HEAP_EXECUTION";
7056 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7058 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7059 outs() << " APP_EXTENSION_SAFE";
7060 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7062 if (f != 0 || flags == 0)
7063 outs() << format(" 0x%08" PRIx32, f);
7065 outs() << format(" 0x%08" PRIx32, magic);
7066 outs() << format(" %7d", cputype);
7067 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7068 outs() << format(" 0x%02" PRIx32,
7069 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7070 outs() << format(" %10u", filetype);
7071 outs() << format(" %5u", ncmds);
7072 outs() << format(" %10u", sizeofcmds);
7073 outs() << format(" 0x%08" PRIx32, flags);
7078 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7079 StringRef SegName, uint64_t vmaddr,
7080 uint64_t vmsize, uint64_t fileoff,
7081 uint64_t filesize, uint32_t maxprot,
7082 uint32_t initprot, uint32_t nsects,
7083 uint32_t flags, uint32_t object_size,
7085 uint64_t expected_cmdsize;
7086 if (cmd == MachO::LC_SEGMENT) {
7087 outs() << " cmd LC_SEGMENT\n";
7088 expected_cmdsize = nsects;
7089 expected_cmdsize *= sizeof(struct MachO::section);
7090 expected_cmdsize += sizeof(struct MachO::segment_command);
7092 outs() << " cmd LC_SEGMENT_64\n";
7093 expected_cmdsize = nsects;
7094 expected_cmdsize *= sizeof(struct MachO::section_64);
7095 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7097 outs() << " cmdsize " << cmdsize;
7098 if (cmdsize != expected_cmdsize)
7099 outs() << " Inconsistent size\n";
7102 outs() << " segname " << SegName << "\n";
7103 if (cmd == MachO::LC_SEGMENT_64) {
7104 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7105 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7107 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7108 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
7110 outs() << " fileoff " << fileoff;
7111 if (fileoff > object_size)
7112 outs() << " (past end of file)\n";
7115 outs() << " filesize " << filesize;
7116 if (fileoff + filesize > object_size)
7117 outs() << " (past end of file)\n";
7122 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7123 MachO::VM_PROT_EXECUTE)) != 0)
7124 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7126 if (maxprot & MachO::VM_PROT_READ)
7127 outs() << " maxprot r";
7129 outs() << " maxprot -";
7130 if (maxprot & MachO::VM_PROT_WRITE)
7134 if (maxprot & MachO::VM_PROT_EXECUTE)
7140 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7141 MachO::VM_PROT_EXECUTE)) != 0)
7142 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7144 if (initprot & MachO::VM_PROT_READ)
7145 outs() << " initprot r";
7147 outs() << " initprot -";
7148 if (initprot & MachO::VM_PROT_WRITE)
7152 if (initprot & MachO::VM_PROT_EXECUTE)
7158 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7159 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7161 outs() << " nsects " << nsects << "\n";
7165 outs() << " (none)\n";
7167 if (flags & MachO::SG_HIGHVM) {
7168 outs() << " HIGHVM";
7169 flags &= ~MachO::SG_HIGHVM;
7171 if (flags & MachO::SG_FVMLIB) {
7172 outs() << " FVMLIB";
7173 flags &= ~MachO::SG_FVMLIB;
7175 if (flags & MachO::SG_NORELOC) {
7176 outs() << " NORELOC";
7177 flags &= ~MachO::SG_NORELOC;
7179 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7180 outs() << " PROTECTED_VERSION_1";
7181 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7184 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7189 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7193 static void PrintSection(const char *sectname, const char *segname,
7194 uint64_t addr, uint64_t size, uint32_t offset,
7195 uint32_t align, uint32_t reloff, uint32_t nreloc,
7196 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7197 uint32_t cmd, const char *sg_segname,
7198 uint32_t filetype, uint32_t object_size,
7200 outs() << "Section\n";
7201 outs() << " sectname " << format("%.16s\n", sectname);
7202 outs() << " segname " << format("%.16s", segname);
7203 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7204 outs() << " (does not match segment)\n";
7207 if (cmd == MachO::LC_SEGMENT_64) {
7208 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7209 outs() << " size " << format("0x%016" PRIx64, size);
7211 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7212 outs() << " size " << format("0x%08" PRIx64, size);
7214 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7215 outs() << " (past end of file)\n";
7218 outs() << " offset " << offset;
7219 if (offset > object_size)
7220 outs() << " (past end of file)\n";
7223 uint32_t align_shifted = 1 << align;
7224 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7225 outs() << " reloff " << reloff;
7226 if (reloff > object_size)
7227 outs() << " (past end of file)\n";
7230 outs() << " nreloc " << nreloc;
7231 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7232 outs() << " (past end of file)\n";
7235 uint32_t section_type = flags & MachO::SECTION_TYPE;
7238 if (section_type == MachO::S_REGULAR)
7239 outs() << " S_REGULAR\n";
7240 else if (section_type == MachO::S_ZEROFILL)
7241 outs() << " S_ZEROFILL\n";
7242 else if (section_type == MachO::S_CSTRING_LITERALS)
7243 outs() << " S_CSTRING_LITERALS\n";
7244 else if (section_type == MachO::S_4BYTE_LITERALS)
7245 outs() << " S_4BYTE_LITERALS\n";
7246 else if (section_type == MachO::S_8BYTE_LITERALS)
7247 outs() << " S_8BYTE_LITERALS\n";
7248 else if (section_type == MachO::S_16BYTE_LITERALS)
7249 outs() << " S_16BYTE_LITERALS\n";
7250 else if (section_type == MachO::S_LITERAL_POINTERS)
7251 outs() << " S_LITERAL_POINTERS\n";
7252 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7253 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7254 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7255 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7256 else if (section_type == MachO::S_SYMBOL_STUBS)
7257 outs() << " S_SYMBOL_STUBS\n";
7258 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7259 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7260 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7261 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7262 else if (section_type == MachO::S_COALESCED)
7263 outs() << " S_COALESCED\n";
7264 else if (section_type == MachO::S_INTERPOSING)
7265 outs() << " S_INTERPOSING\n";
7266 else if (section_type == MachO::S_DTRACE_DOF)
7267 outs() << " S_DTRACE_DOF\n";
7268 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7269 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7270 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7271 outs() << " S_THREAD_LOCAL_REGULAR\n";
7272 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7273 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7274 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7275 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7276 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7277 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7278 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7279 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7281 outs() << format("0x%08" PRIx32, section_type) << "\n";
7282 outs() << "attributes";
7283 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7284 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7285 outs() << " PURE_INSTRUCTIONS";
7286 if (section_attributes & MachO::S_ATTR_NO_TOC)
7287 outs() << " NO_TOC";
7288 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7289 outs() << " STRIP_STATIC_SYMS";
7290 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7291 outs() << " NO_DEAD_STRIP";
7292 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7293 outs() << " LIVE_SUPPORT";
7294 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7295 outs() << " SELF_MODIFYING_CODE";
7296 if (section_attributes & MachO::S_ATTR_DEBUG)
7298 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7299 outs() << " SOME_INSTRUCTIONS";
7300 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7301 outs() << " EXT_RELOC";
7302 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7303 outs() << " LOC_RELOC";
7304 if (section_attributes == 0)
7305 outs() << " (none)";
7308 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7309 outs() << " reserved1 " << reserved1;
7310 if (section_type == MachO::S_SYMBOL_STUBS ||
7311 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7312 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7313 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7314 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7315 outs() << " (index into indirect symbol table)\n";
7318 outs() << " reserved2 " << reserved2;
7319 if (section_type == MachO::S_SYMBOL_STUBS)
7320 outs() << " (size of stubs)\n";
7325 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
7326 uint32_t object_size) {
7327 outs() << " cmd LC_SYMTAB\n";
7328 outs() << " cmdsize " << st.cmdsize;
7329 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7330 outs() << " Incorrect size\n";
7333 outs() << " symoff " << st.symoff;
7334 if (st.symoff > object_size)
7335 outs() << " (past end of file)\n";
7338 outs() << " nsyms " << st.nsyms;
7341 big_size = st.nsyms;
7342 big_size *= sizeof(struct MachO::nlist_64);
7343 big_size += st.symoff;
7344 if (big_size > object_size)
7345 outs() << " (past end of file)\n";
7349 big_size = st.nsyms;
7350 big_size *= sizeof(struct MachO::nlist);
7351 big_size += st.symoff;
7352 if (big_size > object_size)
7353 outs() << " (past end of file)\n";
7357 outs() << " stroff " << st.stroff;
7358 if (st.stroff > object_size)
7359 outs() << " (past end of file)\n";
7362 outs() << " strsize " << st.strsize;
7363 big_size = st.stroff;
7364 big_size += st.strsize;
7365 if (big_size > object_size)
7366 outs() << " (past end of file)\n";
7371 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7372 uint32_t nsyms, uint32_t object_size,
7374 outs() << " cmd LC_DYSYMTAB\n";
7375 outs() << " cmdsize " << dyst.cmdsize;
7376 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7377 outs() << " Incorrect size\n";
7380 outs() << " ilocalsym " << dyst.ilocalsym;
7381 if (dyst.ilocalsym > nsyms)
7382 outs() << " (greater than the number of symbols)\n";
7385 outs() << " nlocalsym " << dyst.nlocalsym;
7387 big_size = dyst.ilocalsym;
7388 big_size += dyst.nlocalsym;
7389 if (big_size > nsyms)
7390 outs() << " (past the end of the symbol table)\n";
7393 outs() << " iextdefsym " << dyst.iextdefsym;
7394 if (dyst.iextdefsym > nsyms)
7395 outs() << " (greater than the number of symbols)\n";
7398 outs() << " nextdefsym " << dyst.nextdefsym;
7399 big_size = dyst.iextdefsym;
7400 big_size += dyst.nextdefsym;
7401 if (big_size > nsyms)
7402 outs() << " (past the end of the symbol table)\n";
7405 outs() << " iundefsym " << dyst.iundefsym;
7406 if (dyst.iundefsym > nsyms)
7407 outs() << " (greater than the number of symbols)\n";
7410 outs() << " nundefsym " << dyst.nundefsym;
7411 big_size = dyst.iundefsym;
7412 big_size += dyst.nundefsym;
7413 if (big_size > nsyms)
7414 outs() << " (past the end of the symbol table)\n";
7417 outs() << " tocoff " << dyst.tocoff;
7418 if (dyst.tocoff > object_size)
7419 outs() << " (past end of file)\n";
7422 outs() << " ntoc " << dyst.ntoc;
7423 big_size = dyst.ntoc;
7424 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7425 big_size += dyst.tocoff;
7426 if (big_size > object_size)
7427 outs() << " (past end of file)\n";
7430 outs() << " modtaboff " << dyst.modtaboff;
7431 if (dyst.modtaboff > object_size)
7432 outs() << " (past end of file)\n";
7435 outs() << " nmodtab " << dyst.nmodtab;
7438 modtabend = dyst.nmodtab;
7439 modtabend *= sizeof(struct MachO::dylib_module_64);
7440 modtabend += dyst.modtaboff;
7442 modtabend = dyst.nmodtab;
7443 modtabend *= sizeof(struct MachO::dylib_module);
7444 modtabend += dyst.modtaboff;
7446 if (modtabend > object_size)
7447 outs() << " (past end of file)\n";
7450 outs() << " extrefsymoff " << dyst.extrefsymoff;
7451 if (dyst.extrefsymoff > object_size)
7452 outs() << " (past end of file)\n";
7455 outs() << " nextrefsyms " << dyst.nextrefsyms;
7456 big_size = dyst.nextrefsyms;
7457 big_size *= sizeof(struct MachO::dylib_reference);
7458 big_size += dyst.extrefsymoff;
7459 if (big_size > object_size)
7460 outs() << " (past end of file)\n";
7463 outs() << " indirectsymoff " << dyst.indirectsymoff;
7464 if (dyst.indirectsymoff > object_size)
7465 outs() << " (past end of file)\n";
7468 outs() << " nindirectsyms " << dyst.nindirectsyms;
7469 big_size = dyst.nindirectsyms;
7470 big_size *= sizeof(uint32_t);
7471 big_size += dyst.indirectsymoff;
7472 if (big_size > object_size)
7473 outs() << " (past end of file)\n";
7476 outs() << " extreloff " << dyst.extreloff;
7477 if (dyst.extreloff > object_size)
7478 outs() << " (past end of file)\n";
7481 outs() << " nextrel " << dyst.nextrel;
7482 big_size = dyst.nextrel;
7483 big_size *= sizeof(struct MachO::relocation_info);
7484 big_size += dyst.extreloff;
7485 if (big_size > object_size)
7486 outs() << " (past end of file)\n";
7489 outs() << " locreloff " << dyst.locreloff;
7490 if (dyst.locreloff > object_size)
7491 outs() << " (past end of file)\n";
7494 outs() << " nlocrel " << dyst.nlocrel;
7495 big_size = dyst.nlocrel;
7496 big_size *= sizeof(struct MachO::relocation_info);
7497 big_size += dyst.locreloff;
7498 if (big_size > object_size)
7499 outs() << " (past end of file)\n";
7504 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7505 uint32_t object_size) {
7506 if (dc.cmd == MachO::LC_DYLD_INFO)
7507 outs() << " cmd LC_DYLD_INFO\n";
7509 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7510 outs() << " cmdsize " << dc.cmdsize;
7511 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7512 outs() << " Incorrect size\n";
7515 outs() << " rebase_off " << dc.rebase_off;
7516 if (dc.rebase_off > object_size)
7517 outs() << " (past end of file)\n";
7520 outs() << " rebase_size " << dc.rebase_size;
7522 big_size = dc.rebase_off;
7523 big_size += dc.rebase_size;
7524 if (big_size > object_size)
7525 outs() << " (past end of file)\n";
7528 outs() << " bind_off " << dc.bind_off;
7529 if (dc.bind_off > object_size)
7530 outs() << " (past end of file)\n";
7533 outs() << " bind_size " << dc.bind_size;
7534 big_size = dc.bind_off;
7535 big_size += dc.bind_size;
7536 if (big_size > object_size)
7537 outs() << " (past end of file)\n";
7540 outs() << " weak_bind_off " << dc.weak_bind_off;
7541 if (dc.weak_bind_off > object_size)
7542 outs() << " (past end of file)\n";
7545 outs() << " weak_bind_size " << dc.weak_bind_size;
7546 big_size = dc.weak_bind_off;
7547 big_size += dc.weak_bind_size;
7548 if (big_size > object_size)
7549 outs() << " (past end of file)\n";
7552 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7553 if (dc.lazy_bind_off > object_size)
7554 outs() << " (past end of file)\n";
7557 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7558 big_size = dc.lazy_bind_off;
7559 big_size += dc.lazy_bind_size;
7560 if (big_size > object_size)
7561 outs() << " (past end of file)\n";
7564 outs() << " export_off " << dc.export_off;
7565 if (dc.export_off > object_size)
7566 outs() << " (past end of file)\n";
7569 outs() << " export_size " << dc.export_size;
7570 big_size = dc.export_off;
7571 big_size += dc.export_size;
7572 if (big_size > object_size)
7573 outs() << " (past end of file)\n";
7578 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7580 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7581 outs() << " cmd LC_ID_DYLINKER\n";
7582 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7583 outs() << " cmd LC_LOAD_DYLINKER\n";
7584 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7585 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7587 outs() << " cmd ?(" << dyld.cmd << ")\n";
7588 outs() << " cmdsize " << dyld.cmdsize;
7589 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7590 outs() << " Incorrect size\n";
7593 if (dyld.name >= dyld.cmdsize)
7594 outs() << " name ?(bad offset " << dyld.name << ")\n";
7596 const char *P = (const char *)(Ptr) + dyld.name;
7597 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7601 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7602 outs() << " cmd LC_UUID\n";
7603 outs() << " cmdsize " << uuid.cmdsize;
7604 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7605 outs() << " Incorrect size\n";
7609 outs() << format("%02" PRIX32, uuid.uuid[0]);
7610 outs() << format("%02" PRIX32, uuid.uuid[1]);
7611 outs() << format("%02" PRIX32, uuid.uuid[2]);
7612 outs() << format("%02" PRIX32, uuid.uuid[3]);
7614 outs() << format("%02" PRIX32, uuid.uuid[4]);
7615 outs() << format("%02" PRIX32, uuid.uuid[5]);
7617 outs() << format("%02" PRIX32, uuid.uuid[6]);
7618 outs() << format("%02" PRIX32, uuid.uuid[7]);
7620 outs() << format("%02" PRIX32, uuid.uuid[8]);
7621 outs() << format("%02" PRIX32, uuid.uuid[9]);
7623 outs() << format("%02" PRIX32, uuid.uuid[10]);
7624 outs() << format("%02" PRIX32, uuid.uuid[11]);
7625 outs() << format("%02" PRIX32, uuid.uuid[12]);
7626 outs() << format("%02" PRIX32, uuid.uuid[13]);
7627 outs() << format("%02" PRIX32, uuid.uuid[14]);
7628 outs() << format("%02" PRIX32, uuid.uuid[15]);
7632 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
7633 outs() << " cmd LC_RPATH\n";
7634 outs() << " cmdsize " << rpath.cmdsize;
7635 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7636 outs() << " Incorrect size\n";
7639 if (rpath.path >= rpath.cmdsize)
7640 outs() << " path ?(bad offset " << rpath.path << ")\n";
7642 const char *P = (const char *)(Ptr) + rpath.path;
7643 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7647 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
7648 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
7649 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
7650 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
7651 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
7653 outs() << " cmd " << vd.cmd << " (?)\n";
7654 outs() << " cmdsize " << vd.cmdsize;
7655 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7656 outs() << " Incorrect size\n";
7659 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
7660 << ((vd.version >> 8) & 0xff);
7661 if ((vd.version & 0xff) != 0)
7662 outs() << "." << (vd.version & 0xff);
7665 outs() << " sdk n/a";
7667 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
7668 << ((vd.sdk >> 8) & 0xff);
7670 if ((vd.sdk & 0xff) != 0)
7671 outs() << "." << (vd.sdk & 0xff);
7675 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7676 outs() << " cmd LC_SOURCE_VERSION\n";
7677 outs() << " cmdsize " << sd.cmdsize;
7678 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7679 outs() << " Incorrect size\n";
7682 uint64_t a = (sd.version >> 40) & 0xffffff;
7683 uint64_t b = (sd.version >> 30) & 0x3ff;
7684 uint64_t c = (sd.version >> 20) & 0x3ff;
7685 uint64_t d = (sd.version >> 10) & 0x3ff;
7686 uint64_t e = sd.version & 0x3ff;
7687 outs() << " version " << a << "." << b;
7689 outs() << "." << c << "." << d << "." << e;
7691 outs() << "." << c << "." << d;
7697 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7698 outs() << " cmd LC_MAIN\n";
7699 outs() << " cmdsize " << ep.cmdsize;
7700 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7701 outs() << " Incorrect size\n";
7704 outs() << " entryoff " << ep.entryoff << "\n";
7705 outs() << " stacksize " << ep.stacksize << "\n";
7708 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7709 uint32_t object_size) {
7710 outs() << " cmd LC_ENCRYPTION_INFO\n";
7711 outs() << " cmdsize " << ec.cmdsize;
7712 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7713 outs() << " Incorrect size\n";
7716 outs() << " cryptoff " << ec.cryptoff;
7717 if (ec.cryptoff > object_size)
7718 outs() << " (past end of file)\n";
7721 outs() << " cryptsize " << ec.cryptsize;
7722 if (ec.cryptsize > object_size)
7723 outs() << " (past end of file)\n";
7726 outs() << " cryptid " << ec.cryptid << "\n";
7729 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
7730 uint32_t object_size) {
7731 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7732 outs() << " cmdsize " << ec.cmdsize;
7733 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7734 outs() << " Incorrect size\n";
7737 outs() << " cryptoff " << ec.cryptoff;
7738 if (ec.cryptoff > object_size)
7739 outs() << " (past end of file)\n";
7742 outs() << " cryptsize " << ec.cryptsize;
7743 if (ec.cryptsize > object_size)
7744 outs() << " (past end of file)\n";
7747 outs() << " cryptid " << ec.cryptid << "\n";
7748 outs() << " pad " << ec.pad << "\n";
7751 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7753 outs() << " cmd LC_LINKER_OPTION\n";
7754 outs() << " cmdsize " << lo.cmdsize;
7755 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7756 outs() << " Incorrect size\n";
7759 outs() << " count " << lo.count << "\n";
7760 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7761 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7764 while (*string == '\0' && left > 0) {
7770 outs() << " string #" << i << " " << format("%.*s\n", left, string);
7771 uint32_t NullPos = StringRef(string, left).find('\0');
7772 uint32_t len = std::min(NullPos, left) + 1;
7778 outs() << " count " << lo.count << " does not match number of strings "
7782 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7784 outs() << " cmd LC_SUB_FRAMEWORK\n";
7785 outs() << " cmdsize " << sub.cmdsize;
7786 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7787 outs() << " Incorrect size\n";
7790 if (sub.umbrella < sub.cmdsize) {
7791 const char *P = Ptr + sub.umbrella;
7792 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7794 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7798 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7800 outs() << " cmd LC_SUB_UMBRELLA\n";
7801 outs() << " cmdsize " << sub.cmdsize;
7802 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7803 outs() << " Incorrect size\n";
7806 if (sub.sub_umbrella < sub.cmdsize) {
7807 const char *P = Ptr + sub.sub_umbrella;
7808 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7810 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7814 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
7816 outs() << " cmd LC_SUB_LIBRARY\n";
7817 outs() << " cmdsize " << sub.cmdsize;
7818 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7819 outs() << " Incorrect size\n";
7822 if (sub.sub_library < sub.cmdsize) {
7823 const char *P = Ptr + sub.sub_library;
7824 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7826 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7830 static void PrintSubClientCommand(MachO::sub_client_command sub,
7832 outs() << " cmd LC_SUB_CLIENT\n";
7833 outs() << " cmdsize " << sub.cmdsize;
7834 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7835 outs() << " Incorrect size\n";
7838 if (sub.client < sub.cmdsize) {
7839 const char *P = Ptr + sub.client;
7840 outs() << " client " << P << " (offset " << sub.client << ")\n";
7842 outs() << " client ?(bad offset " << sub.client << ")\n";
7846 static void PrintRoutinesCommand(MachO::routines_command r) {
7847 outs() << " cmd LC_ROUTINES\n";
7848 outs() << " cmdsize " << r.cmdsize;
7849 if (r.cmdsize != sizeof(struct MachO::routines_command))
7850 outs() << " Incorrect size\n";
7853 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7854 outs() << " init_module " << r.init_module << "\n";
7855 outs() << " reserved1 " << r.reserved1 << "\n";
7856 outs() << " reserved2 " << r.reserved2 << "\n";
7857 outs() << " reserved3 " << r.reserved3 << "\n";
7858 outs() << " reserved4 " << r.reserved4 << "\n";
7859 outs() << " reserved5 " << r.reserved5 << "\n";
7860 outs() << " reserved6 " << r.reserved6 << "\n";
7863 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7864 outs() << " cmd LC_ROUTINES_64\n";
7865 outs() << " cmdsize " << r.cmdsize;
7866 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
7867 outs() << " Incorrect size\n";
7870 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
7871 outs() << " init_module " << r.init_module << "\n";
7872 outs() << " reserved1 " << r.reserved1 << "\n";
7873 outs() << " reserved2 " << r.reserved2 << "\n";
7874 outs() << " reserved3 " << r.reserved3 << "\n";
7875 outs() << " reserved4 " << r.reserved4 << "\n";
7876 outs() << " reserved5 " << r.reserved5 << "\n";
7877 outs() << " reserved6 " << r.reserved6 << "\n";
7880 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
7881 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
7882 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
7883 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
7884 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
7885 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
7886 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
7887 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
7888 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
7889 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
7890 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
7891 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
7892 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
7893 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
7894 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
7895 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
7896 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
7897 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
7898 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
7899 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
7900 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
7901 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
7904 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
7906 outs() << "\t mmst_reg ";
7907 for (f = 0; f < 10; f++)
7908 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
7910 outs() << "\t mmst_rsrv ";
7911 for (f = 0; f < 6; f++)
7912 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
7916 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
7918 outs() << "\t xmm_reg ";
7919 for (f = 0; f < 16; f++)
7920 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
7924 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
7925 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
7926 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
7927 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
7928 outs() << " denorm " << fpu.fpu_fcw.denorm;
7929 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
7930 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
7931 outs() << " undfl " << fpu.fpu_fcw.undfl;
7932 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
7933 outs() << "\t\t pc ";
7934 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
7935 outs() << "FP_PREC_24B ";
7936 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
7937 outs() << "FP_PREC_53B ";
7938 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
7939 outs() << "FP_PREC_64B ";
7941 outs() << fpu.fpu_fcw.pc << " ";
7943 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
7944 outs() << "FP_RND_NEAR ";
7945 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
7946 outs() << "FP_RND_DOWN ";
7947 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
7948 outs() << "FP_RND_UP ";
7949 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
7950 outs() << "FP_CHOP ";
7952 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
7953 outs() << " denorm " << fpu.fpu_fsw.denorm;
7954 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
7955 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
7956 outs() << " undfl " << fpu.fpu_fsw.undfl;
7957 outs() << " precis " << fpu.fpu_fsw.precis;
7958 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
7959 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
7960 outs() << " c0 " << fpu.fpu_fsw.c0;
7961 outs() << " c1 " << fpu.fpu_fsw.c1;
7962 outs() << " c2 " << fpu.fpu_fsw.c2;
7963 outs() << " tos " << fpu.fpu_fsw.tos;
7964 outs() << " c3 " << fpu.fpu_fsw.c3;
7965 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
7966 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
7967 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
7968 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
7969 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
7970 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
7971 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
7972 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
7973 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
7974 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
7975 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
7976 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
7978 outs() << "\t fpu_stmm0:\n";
7979 Print_mmst_reg(fpu.fpu_stmm0);
7980 outs() << "\t fpu_stmm1:\n";
7981 Print_mmst_reg(fpu.fpu_stmm1);
7982 outs() << "\t fpu_stmm2:\n";
7983 Print_mmst_reg(fpu.fpu_stmm2);
7984 outs() << "\t fpu_stmm3:\n";
7985 Print_mmst_reg(fpu.fpu_stmm3);
7986 outs() << "\t fpu_stmm4:\n";
7987 Print_mmst_reg(fpu.fpu_stmm4);
7988 outs() << "\t fpu_stmm5:\n";
7989 Print_mmst_reg(fpu.fpu_stmm5);
7990 outs() << "\t fpu_stmm6:\n";
7991 Print_mmst_reg(fpu.fpu_stmm6);
7992 outs() << "\t fpu_stmm7:\n";
7993 Print_mmst_reg(fpu.fpu_stmm7);
7994 outs() << "\t fpu_xmm0:\n";
7995 Print_xmm_reg(fpu.fpu_xmm0);
7996 outs() << "\t fpu_xmm1:\n";
7997 Print_xmm_reg(fpu.fpu_xmm1);
7998 outs() << "\t fpu_xmm2:\n";
7999 Print_xmm_reg(fpu.fpu_xmm2);
8000 outs() << "\t fpu_xmm3:\n";
8001 Print_xmm_reg(fpu.fpu_xmm3);
8002 outs() << "\t fpu_xmm4:\n";
8003 Print_xmm_reg(fpu.fpu_xmm4);
8004 outs() << "\t fpu_xmm5:\n";
8005 Print_xmm_reg(fpu.fpu_xmm5);
8006 outs() << "\t fpu_xmm6:\n";
8007 Print_xmm_reg(fpu.fpu_xmm6);
8008 outs() << "\t fpu_xmm7:\n";
8009 Print_xmm_reg(fpu.fpu_xmm7);
8010 outs() << "\t fpu_xmm8:\n";
8011 Print_xmm_reg(fpu.fpu_xmm8);
8012 outs() << "\t fpu_xmm9:\n";
8013 Print_xmm_reg(fpu.fpu_xmm9);
8014 outs() << "\t fpu_xmm10:\n";
8015 Print_xmm_reg(fpu.fpu_xmm10);
8016 outs() << "\t fpu_xmm11:\n";
8017 Print_xmm_reg(fpu.fpu_xmm11);
8018 outs() << "\t fpu_xmm12:\n";
8019 Print_xmm_reg(fpu.fpu_xmm12);
8020 outs() << "\t fpu_xmm13:\n";
8021 Print_xmm_reg(fpu.fpu_xmm13);
8022 outs() << "\t fpu_xmm14:\n";
8023 Print_xmm_reg(fpu.fpu_xmm14);
8024 outs() << "\t fpu_xmm15:\n";
8025 Print_xmm_reg(fpu.fpu_xmm15);
8026 outs() << "\t fpu_rsrv4:\n";
8027 for (uint32_t f = 0; f < 6; f++) {
8029 for (uint32_t g = 0; g < 16; g++)
8030 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
8033 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8037 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8038 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8039 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8040 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8043 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8044 bool isLittleEndian, uint32_t cputype) {
8045 if (t.cmd == MachO::LC_THREAD)
8046 outs() << " cmd LC_THREAD\n";
8047 else if (t.cmd == MachO::LC_UNIXTHREAD)
8048 outs() << " cmd LC_UNIXTHREAD\n";
8050 outs() << " cmd " << t.cmd << " (unknown)\n";
8051 outs() << " cmdsize " << t.cmdsize;
8052 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8053 outs() << " Incorrect size\n";
8057 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8058 const char *end = Ptr + t.cmdsize;
8059 uint32_t flavor, count, left;
8060 if (cputype == MachO::CPU_TYPE_X86_64) {
8061 while (begin < end) {
8062 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8063 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8064 begin += sizeof(uint32_t);
8069 if (isLittleEndian != sys::IsLittleEndianHost)
8070 sys::swapByteOrder(flavor);
8071 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8072 memcpy((char *)&count, begin, sizeof(uint32_t));
8073 begin += sizeof(uint32_t);
8078 if (isLittleEndian != sys::IsLittleEndianHost)
8079 sys::swapByteOrder(count);
8080 if (flavor == MachO::x86_THREAD_STATE64) {
8081 outs() << " flavor x86_THREAD_STATE64\n";
8082 if (count == MachO::x86_THREAD_STATE64_COUNT)
8083 outs() << " count x86_THREAD_STATE64_COUNT\n";
8085 outs() << " count " << count
8086 << " (not x86_THREAD_STATE64_COUNT)\n";
8087 MachO::x86_thread_state64_t cpu64;
8089 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8090 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8091 begin += sizeof(MachO::x86_thread_state64_t);
8093 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8094 memcpy(&cpu64, begin, left);
8097 if (isLittleEndian != sys::IsLittleEndianHost)
8099 Print_x86_thread_state64_t(cpu64);
8100 } else if (flavor == MachO::x86_THREAD_STATE) {
8101 outs() << " flavor x86_THREAD_STATE\n";
8102 if (count == MachO::x86_THREAD_STATE_COUNT)
8103 outs() << " count x86_THREAD_STATE_COUNT\n";
8105 outs() << " count " << count
8106 << " (not x86_THREAD_STATE_COUNT)\n";
8107 struct MachO::x86_thread_state_t ts;
8109 if (left >= sizeof(MachO::x86_thread_state_t)) {
8110 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8111 begin += sizeof(MachO::x86_thread_state_t);
8113 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8114 memcpy(&ts, begin, left);
8117 if (isLittleEndian != sys::IsLittleEndianHost)
8119 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8120 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8121 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8122 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8124 outs() << "tsh.count " << ts.tsh.count
8125 << " (not x86_THREAD_STATE64_COUNT\n";
8126 Print_x86_thread_state64_t(ts.uts.ts64);
8128 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8129 << ts.tsh.count << "\n";
8131 } else if (flavor == MachO::x86_FLOAT_STATE) {
8132 outs() << " flavor x86_FLOAT_STATE\n";
8133 if (count == MachO::x86_FLOAT_STATE_COUNT)
8134 outs() << " count x86_FLOAT_STATE_COUNT\n";
8136 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
8137 struct MachO::x86_float_state_t fs;
8139 if (left >= sizeof(MachO::x86_float_state_t)) {
8140 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8141 begin += sizeof(MachO::x86_float_state_t);
8143 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8144 memcpy(&fs, begin, left);
8147 if (isLittleEndian != sys::IsLittleEndianHost)
8149 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8150 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
8151 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
8152 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8154 outs() << "fsh.count " << fs.fsh.count
8155 << " (not x86_FLOAT_STATE64_COUNT\n";
8156 Print_x86_float_state_t(fs.ufs.fs64);
8158 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8159 << fs.fsh.count << "\n";
8161 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8162 outs() << " flavor x86_EXCEPTION_STATE\n";
8163 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8164 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8166 outs() << " count " << count
8167 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8168 struct MachO::x86_exception_state_t es;
8170 if (left >= sizeof(MachO::x86_exception_state_t)) {
8171 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8172 begin += sizeof(MachO::x86_exception_state_t);
8174 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8175 memcpy(&es, begin, left);
8178 if (isLittleEndian != sys::IsLittleEndianHost)
8180 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8181 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
8182 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
8183 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8185 outs() << "\t esh.count " << es.esh.count
8186 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8187 Print_x86_exception_state_t(es.ues.es64);
8189 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8190 << es.esh.count << "\n";
8193 outs() << " flavor " << flavor << " (unknown)\n";
8194 outs() << " count " << count << "\n";
8195 outs() << " state (unknown)\n";
8196 begin += count * sizeof(uint32_t);
8200 while (begin < end) {
8201 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8202 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8203 begin += sizeof(uint32_t);
8208 if (isLittleEndian != sys::IsLittleEndianHost)
8209 sys::swapByteOrder(flavor);
8210 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8211 memcpy((char *)&count, begin, sizeof(uint32_t));
8212 begin += sizeof(uint32_t);
8217 if (isLittleEndian != sys::IsLittleEndianHost)
8218 sys::swapByteOrder(count);
8219 outs() << " flavor " << flavor << "\n";
8220 outs() << " count " << count << "\n";
8221 outs() << " state (Unknown cputype/cpusubtype)\n";
8222 begin += count * sizeof(uint32_t);
8227 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8228 if (dl.cmd == MachO::LC_ID_DYLIB)
8229 outs() << " cmd LC_ID_DYLIB\n";
8230 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8231 outs() << " cmd LC_LOAD_DYLIB\n";
8232 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8233 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8234 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8235 outs() << " cmd LC_REEXPORT_DYLIB\n";
8236 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8237 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8238 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8239 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8241 outs() << " cmd " << dl.cmd << " (unknown)\n";
8242 outs() << " cmdsize " << dl.cmdsize;
8243 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8244 outs() << " Incorrect size\n";
8247 if (dl.dylib.name < dl.cmdsize) {
8248 const char *P = (const char *)(Ptr) + dl.dylib.name;
8249 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8251 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8253 outs() << " time stamp " << dl.dylib.timestamp << " ";
8254 time_t t = dl.dylib.timestamp;
8255 outs() << ctime(&t);
8256 outs() << " current version ";
8257 if (dl.dylib.current_version == 0xffffffff)
8260 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8261 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8262 << (dl.dylib.current_version & 0xff) << "\n";
8263 outs() << "compatibility version ";
8264 if (dl.dylib.compatibility_version == 0xffffffff)
8267 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8268 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8269 << (dl.dylib.compatibility_version & 0xff) << "\n";
8272 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8273 uint32_t object_size) {
8274 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8275 outs() << " cmd LC_FUNCTION_STARTS\n";
8276 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8277 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8278 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8279 outs() << " cmd LC_FUNCTION_STARTS\n";
8280 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8281 outs() << " cmd LC_DATA_IN_CODE\n";
8282 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8283 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8284 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8285 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8287 outs() << " cmd " << ld.cmd << " (?)\n";
8288 outs() << " cmdsize " << ld.cmdsize;
8289 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8290 outs() << " Incorrect size\n";
8293 outs() << " dataoff " << ld.dataoff;
8294 if (ld.dataoff > object_size)
8295 outs() << " (past end of file)\n";
8298 outs() << " datasize " << ld.datasize;
8299 uint64_t big_size = ld.dataoff;
8300 big_size += ld.datasize;
8301 if (big_size > object_size)
8302 outs() << " (past end of file)\n";
8307 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8308 uint32_t cputype, bool verbose) {
8309 StringRef Buf = Obj->getData();
8311 for (const auto &Command : Obj->load_commands()) {
8312 outs() << "Load command " << Index++ << "\n";
8313 if (Command.C.cmd == MachO::LC_SEGMENT) {
8314 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8315 const char *sg_segname = SLC.segname;
8316 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8317 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8318 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8320 for (unsigned j = 0; j < SLC.nsects; j++) {
8321 MachO::section S = Obj->getSection(Command, j);
8322 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8323 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8324 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8326 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8327 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8328 const char *sg_segname = SLC_64.segname;
8329 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8330 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8331 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8332 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8333 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8334 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8335 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8336 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8337 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8338 sg_segname, filetype, Buf.size(), verbose);
8340 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8341 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8342 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
8343 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8344 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8345 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8346 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8348 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8349 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8350 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8351 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8352 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8353 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8354 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8355 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8356 PrintDyldLoadCommand(Dyld, Command.Ptr);
8357 } else if (Command.C.cmd == MachO::LC_UUID) {
8358 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8359 PrintUuidLoadCommand(Uuid);
8360 } else if (Command.C.cmd == MachO::LC_RPATH) {
8361 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8362 PrintRpathLoadCommand(Rpath, Command.Ptr);
8363 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
8364 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
8365 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8366 PrintVersionMinLoadCommand(Vd);
8367 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8368 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8369 PrintSourceVersionCommand(Sd);
8370 } else if (Command.C.cmd == MachO::LC_MAIN) {
8371 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8372 PrintEntryPointCommand(Ep);
8373 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
8374 MachO::encryption_info_command Ei =
8375 Obj->getEncryptionInfoCommand(Command);
8376 PrintEncryptionInfoCommand(Ei, Buf.size());
8377 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
8378 MachO::encryption_info_command_64 Ei =
8379 Obj->getEncryptionInfoCommand64(Command);
8380 PrintEncryptionInfoCommand64(Ei, Buf.size());
8381 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
8382 MachO::linker_option_command Lo =
8383 Obj->getLinkerOptionLoadCommand(Command);
8384 PrintLinkerOptionCommand(Lo, Command.Ptr);
8385 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8386 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8387 PrintSubFrameworkCommand(Sf, Command.Ptr);
8388 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8389 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8390 PrintSubUmbrellaCommand(Sf, Command.Ptr);
8391 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8392 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8393 PrintSubLibraryCommand(Sl, Command.Ptr);
8394 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8395 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8396 PrintSubClientCommand(Sc, Command.Ptr);
8397 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8398 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8399 PrintRoutinesCommand(Rc);
8400 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8401 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8402 PrintRoutinesCommand64(Rc);
8403 } else if (Command.C.cmd == MachO::LC_THREAD ||
8404 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8405 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8406 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
8407 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8408 Command.C.cmd == MachO::LC_ID_DYLIB ||
8409 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8410 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8411 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8412 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
8413 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8414 PrintDylibCommand(Dl, Command.Ptr);
8415 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8416 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8417 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8418 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8419 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8420 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8421 MachO::linkedit_data_command Ld =
8422 Obj->getLinkeditDataLoadCommand(Command);
8423 PrintLinkEditDataCommand(Ld, Buf.size());
8425 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8427 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8428 // TODO: get and print the raw bytes of the load command.
8430 // TODO: print all the other kinds of load commands.
8434 static void getAndPrintMachHeader(const MachOObjectFile *Obj,
8435 uint32_t &filetype, uint32_t &cputype,
8437 if (Obj->is64Bit()) {
8438 MachO::mach_header_64 H_64;
8439 H_64 = Obj->getHeader64();
8440 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8441 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8442 filetype = H_64.filetype;
8443 cputype = H_64.cputype;
8445 MachO::mach_header H;
8446 H = Obj->getHeader();
8447 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8448 H.sizeofcmds, H.flags, verbose);
8449 filetype = H.filetype;
8450 cputype = H.cputype;
8454 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8455 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
8456 uint32_t filetype = 0;
8457 uint32_t cputype = 0;
8458 getAndPrintMachHeader(file, filetype, cputype, !NonVerbose);
8459 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
8462 //===----------------------------------------------------------------------===//
8463 // export trie dumping
8464 //===----------------------------------------------------------------------===//
8466 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
8467 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8468 uint64_t Flags = Entry.flags();
8469 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8470 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8471 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8472 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8473 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8474 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8475 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8477 outs() << "[re-export] ";
8479 outs() << format("0x%08llX ",
8480 Entry.address()); // FIXME:add in base address
8481 outs() << Entry.name();
8482 if (WeakDef || ThreadLocal || Resolver || Abs) {
8483 bool NeedsComma = false;
8486 outs() << "weak_def";
8492 outs() << "per-thread";
8498 outs() << "absolute";
8504 outs() << format("resolver=0x%08llX", Entry.other());
8510 StringRef DylibName = "unknown";
8511 int Ordinal = Entry.other() - 1;
8512 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8513 if (Entry.otherName().empty())
8514 outs() << " (from " << DylibName << ")";
8516 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
8522 //===----------------------------------------------------------------------===//
8523 // rebase table dumping
8524 //===----------------------------------------------------------------------===//
8529 SegInfo(const object::MachOObjectFile *Obj);
8531 StringRef segmentName(uint32_t SegIndex);
8532 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8533 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
8536 struct SectionInfo {
8539 StringRef SectionName;
8540 StringRef SegmentName;
8541 uint64_t OffsetInSegment;
8542 uint64_t SegmentStartAddress;
8543 uint32_t SegmentIndex;
8545 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8546 SmallVector<SectionInfo, 32> Sections;
8550 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8551 // Build table of sections so segIndex/offset pairs can be translated.
8552 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
8553 StringRef CurSegName;
8554 uint64_t CurSegAddress;
8555 for (const SectionRef &Section : Obj->sections()) {
8557 error(Section.getName(Info.SectionName));
8558 Info.Address = Section.getAddress();
8559 Info.Size = Section.getSize();
8561 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8562 if (!Info.SegmentName.equals(CurSegName)) {
8564 CurSegName = Info.SegmentName;
8565 CurSegAddress = Info.Address;
8567 Info.SegmentIndex = CurSegIndex - 1;
8568 Info.OffsetInSegment = Info.Address - CurSegAddress;
8569 Info.SegmentStartAddress = CurSegAddress;
8570 Sections.push_back(Info);
8574 StringRef SegInfo::segmentName(uint32_t SegIndex) {
8575 for (const SectionInfo &SI : Sections) {
8576 if (SI.SegmentIndex == SegIndex)
8577 return SI.SegmentName;
8579 llvm_unreachable("invalid segIndex");
8582 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8583 uint64_t OffsetInSeg) {
8584 for (const SectionInfo &SI : Sections) {
8585 if (SI.SegmentIndex != SegIndex)
8587 if (SI.OffsetInSegment > OffsetInSeg)
8589 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8593 llvm_unreachable("segIndex and offset not in any section");
8596 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8597 return findSection(SegIndex, OffsetInSeg).SectionName;
8600 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8601 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8602 return SI.SegmentStartAddress + OffsetInSeg;
8605 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8606 // Build table of sections so names can used in final output.
8607 SegInfo sectionTable(Obj);
8609 outs() << "segment section address type\n";
8610 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8611 uint32_t SegIndex = Entry.segmentIndex();
8612 uint64_t OffsetInSeg = Entry.segmentOffset();
8613 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8614 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8615 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8617 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
8618 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8619 SegmentName.str().c_str(), SectionName.str().c_str(),
8620 Address, Entry.typeName().str().c_str());
8624 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8625 StringRef DylibName;
8627 case MachO::BIND_SPECIAL_DYLIB_SELF:
8628 return "this-image";
8629 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8630 return "main-executable";
8631 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8632 return "flat-namespace";
8635 std::error_code EC =
8636 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
8638 return "<<bad library ordinal>>";
8642 return "<<unknown special ordinal>>";
8645 //===----------------------------------------------------------------------===//
8646 // bind table dumping
8647 //===----------------------------------------------------------------------===//
8649 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8650 // Build table of sections so names can used in final output.
8651 SegInfo sectionTable(Obj);
8653 outs() << "segment section address type "
8654 "addend dylib symbol\n";
8655 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8656 uint32_t SegIndex = Entry.segmentIndex();
8657 uint64_t OffsetInSeg = Entry.segmentOffset();
8658 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8659 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8660 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8662 // Table lines look like:
8663 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
8665 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
8666 Attr = " (weak_import)";
8667 outs() << left_justify(SegmentName, 8) << " "
8668 << left_justify(SectionName, 18) << " "
8669 << format_hex(Address, 10, true) << " "
8670 << left_justify(Entry.typeName(), 8) << " "
8671 << format_decimal(Entry.addend(), 8) << " "
8672 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8673 << Entry.symbolName() << Attr << "\n";
8677 //===----------------------------------------------------------------------===//
8678 // lazy bind table dumping
8679 //===----------------------------------------------------------------------===//
8681 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8682 // Build table of sections so names can used in final output.
8683 SegInfo sectionTable(Obj);
8685 outs() << "segment section address "
8687 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8688 uint32_t SegIndex = Entry.segmentIndex();
8689 uint64_t OffsetInSeg = Entry.segmentOffset();
8690 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8691 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8692 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8694 // Table lines look like:
8695 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
8696 outs() << left_justify(SegmentName, 8) << " "
8697 << left_justify(SectionName, 18) << " "
8698 << format_hex(Address, 10, true) << " "
8699 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8700 << Entry.symbolName() << "\n";
8704 //===----------------------------------------------------------------------===//
8705 // weak bind table dumping
8706 //===----------------------------------------------------------------------===//
8708 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8709 // Build table of sections so names can used in final output.
8710 SegInfo sectionTable(Obj);
8712 outs() << "segment section address "
8713 "type addend symbol\n";
8714 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8715 // Strong symbols don't have a location to update.
8716 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
8717 outs() << " strong "
8718 << Entry.symbolName() << "\n";
8721 uint32_t SegIndex = Entry.segmentIndex();
8722 uint64_t OffsetInSeg = Entry.segmentOffset();
8723 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8724 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8725 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8727 // Table lines look like:
8728 // __DATA __data 0x00001000 pointer 0 _foo
8729 outs() << left_justify(SegmentName, 8) << " "
8730 << left_justify(SectionName, 18) << " "
8731 << format_hex(Address, 10, true) << " "
8732 << left_justify(Entry.typeName(), 8) << " "
8733 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8738 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
8739 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8740 // information for that address. If the address is found its binding symbol
8741 // name is returned. If not nullptr is returned.
8742 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8743 struct DisassembleInfo *info) {
8744 if (info->bindtable == nullptr) {
8745 info->bindtable = new (BindTable);
8746 SegInfo sectionTable(info->O);
8747 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8748 uint32_t SegIndex = Entry.segmentIndex();
8749 uint64_t OffsetInSeg = Entry.segmentOffset();
8750 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8751 const char *SymbolName = nullptr;
8752 StringRef name = Entry.symbolName();
8754 SymbolName = name.data();
8755 info->bindtable->push_back(std::make_pair(Address, SymbolName));
8758 for (bind_table_iterator BI = info->bindtable->begin(),
8759 BE = info->bindtable->end();
8761 uint64_t Address = BI->first;
8762 if (ReferenceValue == Address) {
8763 const char *SymbolName = BI->second;