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)"));
100 cl::list<std::string>
101 llvm::DumpSections("section",
102 cl::desc("Prints the specified segment,section for "
103 "Mach-O objects (requires -macho)"));
105 cl::opt<bool> llvm::Raw("raw",
106 cl::desc("Have -section dump the raw binary contents"));
109 llvm::InfoPlist("info-plist",
110 cl::desc("Print the info plist section as strings for "
111 "Mach-O objects (requires -macho)"));
114 llvm::DylibsUsed("dylibs-used",
115 cl::desc("Print the shared libraries used for linked "
116 "Mach-O files (requires -macho)"));
119 llvm::DylibId("dylib-id",
120 cl::desc("Print the shared library's id for the dylib Mach-O "
121 "file (requires -macho)"));
124 llvm::NonVerbose("non-verbose",
125 cl::desc("Print the info for Mach-O objects in "
126 "non-verbose or numeric form (requires -macho)"));
129 llvm::ObjcMetaData("objc-meta-data",
130 cl::desc("Print the Objective-C runtime meta data for "
131 "Mach-O files (requires -macho)"));
133 cl::opt<std::string> llvm::DisSymName(
135 cl::desc("disassemble just this symbol's instructions (requires -macho"));
137 static cl::opt<bool> NoSymbolicOperands(
138 "no-symbolic-operands",
139 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
141 static cl::list<std::string>
142 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
144 bool ArchAll = false;
146 static std::string ThumbTripleName;
148 static const Target *GetTarget(const MachOObjectFile *MachOObj,
149 const char **McpuDefault,
150 const Target **ThumbTarget) {
151 // Figure out the target triple.
152 if (TripleName.empty()) {
153 llvm::Triple TT("unknown-unknown-unknown");
154 llvm::Triple ThumbTriple = Triple();
155 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
156 TripleName = TT.str();
157 ThumbTripleName = ThumbTriple.str();
160 // Get the target specific parser.
162 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
163 if (TheTarget && ThumbTripleName.empty())
166 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
170 errs() << "llvm-objdump: error: unable to get target for '";
172 errs() << TripleName;
174 errs() << ThumbTripleName;
175 errs() << "', see --version and --triple.\n";
179 struct SymbolSorter {
180 bool operator()(const SymbolRef &A, const SymbolRef &B) {
181 SymbolRef::Type AType = A.getType();
182 SymbolRef::Type BType = B.getType();
184 uint64_t AAddr, BAddr;
185 if (AType != SymbolRef::ST_Function)
189 if (BType != SymbolRef::ST_Function)
193 return AAddr < BAddr;
197 // Types for the storted data in code table that is built before disassembly
198 // and the predicate function to sort them.
199 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
200 typedef std::vector<DiceTableEntry> DiceTable;
201 typedef DiceTable::iterator dice_table_iterator;
203 // This is used to search for a data in code table entry for the PC being
204 // disassembled. The j parameter has the PC in j.first. A single data in code
205 // table entry can cover many bytes for each of its Kind's. So if the offset,
206 // aka the i.first value, of the data in code table entry plus its Length
207 // covers the PC being searched for this will return true. If not it will
209 static bool compareDiceTableEntries(const DiceTableEntry &i,
210 const DiceTableEntry &j) {
212 i.second.getLength(Length);
214 return j.first >= i.first && j.first < i.first + Length;
217 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
218 unsigned short Kind) {
219 uint32_t Value, Size = 1;
223 case MachO::DICE_KIND_DATA:
226 dumpBytes(ArrayRef<uint8_t>(bytes, 4), outs());
227 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
228 outs() << "\t.long " << Value;
230 } else if (Length >= 2) {
232 dumpBytes(ArrayRef<uint8_t>(bytes, 2), outs());
233 Value = bytes[1] << 8 | bytes[0];
234 outs() << "\t.short " << Value;
238 dumpBytes(ArrayRef<uint8_t>(bytes, 2), outs());
240 outs() << "\t.byte " << Value;
243 if (Kind == MachO::DICE_KIND_DATA)
244 outs() << "\t@ KIND_DATA\n";
246 outs() << "\t@ data in code kind = " << Kind << "\n";
248 case MachO::DICE_KIND_JUMP_TABLE8:
250 dumpBytes(ArrayRef<uint8_t>(bytes, 1), outs());
252 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
255 case MachO::DICE_KIND_JUMP_TABLE16:
257 dumpBytes(ArrayRef<uint8_t>(bytes, 2), outs());
258 Value = bytes[1] << 8 | bytes[0];
259 outs() << "\t.short " << format("%5u", Value & 0xffff)
260 << "\t@ KIND_JUMP_TABLE16\n";
263 case MachO::DICE_KIND_JUMP_TABLE32:
264 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
266 dumpBytes(ArrayRef<uint8_t>(bytes, 4), outs());
267 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
268 outs() << "\t.long " << Value;
269 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
270 outs() << "\t@ KIND_JUMP_TABLE32\n";
272 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
279 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
280 std::vector<SectionRef> &Sections,
281 std::vector<SymbolRef> &Symbols,
282 SmallVectorImpl<uint64_t> &FoundFns,
283 uint64_t &BaseSegmentAddress) {
284 for (const SymbolRef &Symbol : MachOObj->symbols()) {
285 ErrorOr<StringRef> SymName = Symbol.getName();
286 if (std::error_code EC = SymName.getError())
287 report_fatal_error(EC.message());
288 if (!SymName->startswith("ltmp"))
289 Symbols.push_back(Symbol);
292 for (const SectionRef &Section : MachOObj->sections()) {
294 Section.getName(SectName);
295 Sections.push_back(Section);
298 bool BaseSegmentAddressSet = false;
299 for (const auto &Command : MachOObj->load_commands()) {
300 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
301 // We found a function starts segment, parse the addresses for later
303 MachO::linkedit_data_command LLC =
304 MachOObj->getLinkeditDataLoadCommand(Command);
306 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
307 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
308 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
309 StringRef SegName = SLC.segname;
310 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
311 BaseSegmentAddressSet = true;
312 BaseSegmentAddress = SLC.vmaddr;
318 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
319 uint32_t n, uint32_t count,
320 uint32_t stride, uint64_t addr) {
321 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
322 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
323 if (n > nindirectsyms)
324 outs() << " (entries start past the end of the indirect symbol "
325 "table) (reserved1 field greater than the table size)";
326 else if (n + count > nindirectsyms)
327 outs() << " (entries extends past the end of the indirect symbol "
330 uint32_t cputype = O->getHeader().cputype;
331 if (cputype & MachO::CPU_ARCH_ABI64)
332 outs() << "address index";
334 outs() << "address index";
339 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
340 if (cputype & MachO::CPU_ARCH_ABI64)
341 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
343 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
344 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
345 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
346 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
350 if (indirect_symbol ==
351 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
352 outs() << "LOCAL ABSOLUTE\n";
355 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
356 outs() << "ABSOLUTE\n";
359 outs() << format("%5u ", indirect_symbol);
361 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
362 if (indirect_symbol < Symtab.nsyms) {
363 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
364 SymbolRef Symbol = *Sym;
365 ErrorOr<StringRef> SymName = Symbol.getName();
366 if (std::error_code EC = SymName.getError())
367 report_fatal_error(EC.message());
377 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
378 for (const auto &Load : O->load_commands()) {
379 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
380 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
381 for (unsigned J = 0; J < Seg.nsects; ++J) {
382 MachO::section_64 Sec = O->getSection64(Load, J);
383 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
384 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
385 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
386 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
387 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
388 section_type == MachO::S_SYMBOL_STUBS) {
390 if (section_type == MachO::S_SYMBOL_STUBS)
391 stride = Sec.reserved2;
395 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
396 << Sec.sectname << ") "
397 << "(size of stubs in reserved2 field is zero)\n";
400 uint32_t count = Sec.size / stride;
401 outs() << "Indirect symbols for (" << Sec.segname << ","
402 << Sec.sectname << ") " << count << " entries";
403 uint32_t n = Sec.reserved1;
404 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
407 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
408 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
409 for (unsigned J = 0; J < Seg.nsects; ++J) {
410 MachO::section Sec = O->getSection(Load, J);
411 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
412 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
413 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
414 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
415 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
416 section_type == MachO::S_SYMBOL_STUBS) {
418 if (section_type == MachO::S_SYMBOL_STUBS)
419 stride = Sec.reserved2;
423 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
424 << Sec.sectname << ") "
425 << "(size of stubs in reserved2 field is zero)\n";
428 uint32_t count = Sec.size / stride;
429 outs() << "Indirect symbols for (" << Sec.segname << ","
430 << Sec.sectname << ") " << count << " entries";
431 uint32_t n = Sec.reserved1;
432 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
439 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
440 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
441 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
442 outs() << "Data in code table (" << nentries << " entries)\n";
443 outs() << "offset length kind\n";
444 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
447 DI->getOffset(Offset);
448 outs() << format("0x%08" PRIx32, Offset) << " ";
450 DI->getLength(Length);
451 outs() << format("%6u", Length) << " ";
456 case MachO::DICE_KIND_DATA:
459 case MachO::DICE_KIND_JUMP_TABLE8:
460 outs() << "JUMP_TABLE8";
462 case MachO::DICE_KIND_JUMP_TABLE16:
463 outs() << "JUMP_TABLE16";
465 case MachO::DICE_KIND_JUMP_TABLE32:
466 outs() << "JUMP_TABLE32";
468 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
469 outs() << "ABS_JUMP_TABLE32";
472 outs() << format("0x%04" PRIx32, Kind);
476 outs() << format("0x%04" PRIx32, Kind);
481 static void PrintLinkOptHints(MachOObjectFile *O) {
482 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
483 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
484 uint32_t nloh = LohLC.datasize;
485 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
486 for (uint32_t i = 0; i < nloh;) {
488 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
490 outs() << " identifier " << identifier << " ";
493 switch (identifier) {
495 outs() << "AdrpAdrp\n";
498 outs() << "AdrpLdr\n";
501 outs() << "AdrpAddLdr\n";
504 outs() << "AdrpLdrGotLdr\n";
507 outs() << "AdrpAddStr\n";
510 outs() << "AdrpLdrGotStr\n";
513 outs() << "AdrpAdd\n";
516 outs() << "AdrpLdrGot\n";
519 outs() << "Unknown identifier value\n";
522 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
524 outs() << " narguments " << narguments << "\n";
528 for (uint32_t j = 0; j < narguments; j++) {
529 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
531 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
538 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
540 for (const auto &Load : O->load_commands()) {
541 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
542 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
543 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
544 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
545 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
546 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
547 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
548 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
549 if (dl.dylib.name < dl.cmdsize) {
550 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
555 outs() << " (compatibility version "
556 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
557 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
558 << (dl.dylib.compatibility_version & 0xff) << ",";
559 outs() << " current version "
560 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
561 << ((dl.dylib.current_version >> 8) & 0xff) << "."
562 << (dl.dylib.current_version & 0xff) << ")\n";
565 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
566 if (Load.C.cmd == MachO::LC_ID_DYLIB)
567 outs() << "LC_ID_DYLIB ";
568 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
569 outs() << "LC_LOAD_DYLIB ";
570 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
571 outs() << "LC_LOAD_WEAK_DYLIB ";
572 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
573 outs() << "LC_LAZY_LOAD_DYLIB ";
574 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
575 outs() << "LC_REEXPORT_DYLIB ";
576 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
577 outs() << "LC_LOAD_UPWARD_DYLIB ";
580 outs() << "command " << Index++ << "\n";
586 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
588 static void CreateSymbolAddressMap(MachOObjectFile *O,
589 SymbolAddressMap *AddrMap) {
590 // Create a map of symbol addresses to symbol names.
591 for (const SymbolRef &Symbol : O->symbols()) {
592 SymbolRef::Type ST = Symbol.getType();
593 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
594 ST == SymbolRef::ST_Other) {
596 Symbol.getAddress(Address);
597 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
598 if (std::error_code EC = SymNameOrErr.getError())
599 report_fatal_error(EC.message());
600 StringRef SymName = *SymNameOrErr;
601 if (!SymName.startswith(".objc"))
602 (*AddrMap)[Address] = SymName;
607 // GuessSymbolName is passed the address of what might be a symbol and a
608 // pointer to the SymbolAddressMap. It returns the name of a symbol
609 // with that address or nullptr if no symbol is found with that address.
610 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
611 const char *SymbolName = nullptr;
612 // A DenseMap can't lookup up some values.
613 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
614 StringRef name = AddrMap->lookup(value);
616 SymbolName = name.data();
621 static void DumpCstringChar(const char c) {
625 outs().write_escaped(p);
628 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
629 uint32_t sect_size, uint64_t sect_addr,
630 bool print_addresses) {
631 for (uint32_t i = 0; i < sect_size; i++) {
632 if (print_addresses) {
634 outs() << format("%016" PRIx64, sect_addr + i) << " ";
636 outs() << format("%08" PRIx64, sect_addr + i) << " ";
638 for (; i < sect_size && sect[i] != '\0'; i++)
639 DumpCstringChar(sect[i]);
640 if (i < sect_size && sect[i] == '\0')
645 static void DumpLiteral4(uint32_t l, float f) {
646 outs() << format("0x%08" PRIx32, l);
647 if ((l & 0x7f800000) != 0x7f800000)
648 outs() << format(" (%.16e)\n", f);
651 outs() << " (+Infinity)\n";
652 else if (l == 0xff800000)
653 outs() << " (-Infinity)\n";
654 else if ((l & 0x00400000) == 0x00400000)
655 outs() << " (non-signaling Not-a-Number)\n";
657 outs() << " (signaling Not-a-Number)\n";
661 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
662 uint32_t sect_size, uint64_t sect_addr,
663 bool print_addresses) {
664 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
665 if (print_addresses) {
667 outs() << format("%016" PRIx64, sect_addr + i) << " ";
669 outs() << format("%08" PRIx64, sect_addr + i) << " ";
672 memcpy(&f, sect + i, sizeof(float));
673 if (O->isLittleEndian() != sys::IsLittleEndianHost)
674 sys::swapByteOrder(f);
676 memcpy(&l, sect + i, sizeof(uint32_t));
677 if (O->isLittleEndian() != sys::IsLittleEndianHost)
678 sys::swapByteOrder(l);
683 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
685 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
687 if (O->isLittleEndian()) {
694 // Hi is the high word, so this is equivalent to if(isfinite(d))
695 if ((Hi & 0x7ff00000) != 0x7ff00000)
696 outs() << format(" (%.16e)\n", d);
698 if (Hi == 0x7ff00000 && Lo == 0)
699 outs() << " (+Infinity)\n";
700 else if (Hi == 0xfff00000 && Lo == 0)
701 outs() << " (-Infinity)\n";
702 else if ((Hi & 0x00080000) == 0x00080000)
703 outs() << " (non-signaling Not-a-Number)\n";
705 outs() << " (signaling Not-a-Number)\n";
709 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
710 uint32_t sect_size, uint64_t sect_addr,
711 bool print_addresses) {
712 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
713 if (print_addresses) {
715 outs() << format("%016" PRIx64, sect_addr + i) << " ";
717 outs() << format("%08" PRIx64, sect_addr + i) << " ";
720 memcpy(&d, sect + i, sizeof(double));
721 if (O->isLittleEndian() != sys::IsLittleEndianHost)
722 sys::swapByteOrder(d);
724 memcpy(&l0, sect + i, sizeof(uint32_t));
725 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
726 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
727 sys::swapByteOrder(l0);
728 sys::swapByteOrder(l1);
730 DumpLiteral8(O, l0, l1, d);
734 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
735 outs() << format("0x%08" PRIx32, l0) << " ";
736 outs() << format("0x%08" PRIx32, l1) << " ";
737 outs() << format("0x%08" PRIx32, l2) << " ";
738 outs() << format("0x%08" PRIx32, l3) << "\n";
741 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
742 uint32_t sect_size, uint64_t sect_addr,
743 bool print_addresses) {
744 for (uint32_t i = 0; i < sect_size; i += 16) {
745 if (print_addresses) {
747 outs() << format("%016" PRIx64, sect_addr + i) << " ";
749 outs() << format("%08" PRIx64, sect_addr + i) << " ";
751 uint32_t l0, l1, l2, l3;
752 memcpy(&l0, sect + i, sizeof(uint32_t));
753 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
754 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
755 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
756 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
757 sys::swapByteOrder(l0);
758 sys::swapByteOrder(l1);
759 sys::swapByteOrder(l2);
760 sys::swapByteOrder(l3);
762 DumpLiteral16(l0, l1, l2, l3);
766 static void DumpLiteralPointerSection(MachOObjectFile *O,
767 const SectionRef &Section,
768 const char *sect, uint32_t sect_size,
770 bool print_addresses) {
771 // Collect the literal sections in this Mach-O file.
772 std::vector<SectionRef> LiteralSections;
773 for (const SectionRef &Section : O->sections()) {
774 DataRefImpl Ref = Section.getRawDataRefImpl();
775 uint32_t section_type;
777 const MachO::section_64 Sec = O->getSection64(Ref);
778 section_type = Sec.flags & MachO::SECTION_TYPE;
780 const MachO::section Sec = O->getSection(Ref);
781 section_type = Sec.flags & MachO::SECTION_TYPE;
783 if (section_type == MachO::S_CSTRING_LITERALS ||
784 section_type == MachO::S_4BYTE_LITERALS ||
785 section_type == MachO::S_8BYTE_LITERALS ||
786 section_type == MachO::S_16BYTE_LITERALS)
787 LiteralSections.push_back(Section);
790 // Set the size of the literal pointer.
791 uint32_t lp_size = O->is64Bit() ? 8 : 4;
793 // Collect the external relocation symbols for the literal pointers.
794 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
795 for (const RelocationRef &Reloc : Section.relocations()) {
797 MachO::any_relocation_info RE;
798 bool isExtern = false;
799 Rel = Reloc.getRawDataRefImpl();
800 RE = O->getRelocation(Rel);
801 isExtern = O->getPlainRelocationExternal(RE);
803 uint64_t RelocOffset = Reloc.getOffset();
804 symbol_iterator RelocSym = Reloc.getSymbol();
805 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
808 array_pod_sort(Relocs.begin(), Relocs.end());
810 // Dump each literal pointer.
811 for (uint32_t i = 0; i < sect_size; i += lp_size) {
812 if (print_addresses) {
814 outs() << format("%016" PRIx64, sect_addr + i) << " ";
816 outs() << format("%08" PRIx64, sect_addr + i) << " ";
820 memcpy(&lp, sect + i, sizeof(uint64_t));
821 if (O->isLittleEndian() != sys::IsLittleEndianHost)
822 sys::swapByteOrder(lp);
825 memcpy(&li, sect + i, sizeof(uint32_t));
826 if (O->isLittleEndian() != sys::IsLittleEndianHost)
827 sys::swapByteOrder(li);
831 // First look for an external relocation entry for this literal pointer.
832 auto Reloc = std::find_if(
833 Relocs.begin(), Relocs.end(),
834 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
835 if (Reloc != Relocs.end()) {
836 symbol_iterator RelocSym = Reloc->second;
837 ErrorOr<StringRef> SymName = RelocSym->getName();
838 if (std::error_code EC = SymName.getError())
839 report_fatal_error(EC.message());
840 outs() << "external relocation entry for symbol:" << *SymName << "\n";
844 // For local references see what the section the literal pointer points to.
845 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
846 [&](const SectionRef &R) {
847 return lp >= R.getAddress() &&
848 lp < R.getAddress() + R.getSize();
850 if (Sect == LiteralSections.end()) {
851 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
855 uint64_t SectAddress = Sect->getAddress();
856 uint64_t SectSize = Sect->getSize();
859 Sect->getName(SectName);
860 DataRefImpl Ref = Sect->getRawDataRefImpl();
861 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
862 outs() << SegmentName << ":" << SectName << ":";
864 uint32_t section_type;
866 const MachO::section_64 Sec = O->getSection64(Ref);
867 section_type = Sec.flags & MachO::SECTION_TYPE;
869 const MachO::section Sec = O->getSection(Ref);
870 section_type = Sec.flags & MachO::SECTION_TYPE;
874 Sect->getContents(BytesStr);
875 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
877 switch (section_type) {
878 case MachO::S_CSTRING_LITERALS:
879 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
881 DumpCstringChar(Contents[i]);
885 case MachO::S_4BYTE_LITERALS:
887 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
889 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
890 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
891 sys::swapByteOrder(f);
892 sys::swapByteOrder(l);
896 case MachO::S_8BYTE_LITERALS: {
898 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
900 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
901 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
903 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
904 sys::swapByteOrder(f);
905 sys::swapByteOrder(l0);
906 sys::swapByteOrder(l1);
908 DumpLiteral8(O, l0, l1, d);
911 case MachO::S_16BYTE_LITERALS: {
912 uint32_t l0, l1, l2, l3;
913 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
914 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
916 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
918 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
920 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
921 sys::swapByteOrder(l0);
922 sys::swapByteOrder(l1);
923 sys::swapByteOrder(l2);
924 sys::swapByteOrder(l3);
926 DumpLiteral16(l0, l1, l2, l3);
933 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
934 uint32_t sect_size, uint64_t sect_addr,
935 SymbolAddressMap *AddrMap,
939 stride = sizeof(uint64_t);
941 stride = sizeof(uint32_t);
942 for (uint32_t i = 0; i < sect_size; i += stride) {
943 const char *SymbolName = nullptr;
945 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
946 uint64_t pointer_value;
947 memcpy(&pointer_value, sect + i, stride);
948 if (O->isLittleEndian() != sys::IsLittleEndianHost)
949 sys::swapByteOrder(pointer_value);
950 outs() << format("0x%016" PRIx64, pointer_value);
952 SymbolName = GuessSymbolName(pointer_value, AddrMap);
954 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
955 uint32_t pointer_value;
956 memcpy(&pointer_value, sect + i, stride);
957 if (O->isLittleEndian() != sys::IsLittleEndianHost)
958 sys::swapByteOrder(pointer_value);
959 outs() << format("0x%08" PRIx32, pointer_value);
961 SymbolName = GuessSymbolName(pointer_value, AddrMap);
964 outs() << " " << SymbolName;
969 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
970 uint32_t size, uint64_t addr) {
971 uint32_t cputype = O->getHeader().cputype;
972 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
974 for (uint32_t i = 0; i < size; i += j, addr += j) {
976 outs() << format("%016" PRIx64, addr) << "\t";
978 outs() << format("%08" PRIx64, addr) << "\t";
979 for (j = 0; j < 16 && i + j < size; j++) {
980 uint8_t byte_word = *(sect + i + j);
981 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
987 for (uint32_t i = 0; i < size; i += j, addr += j) {
989 outs() << format("%016" PRIx64, addr) << "\t";
991 outs() << format("%08" PRIx64, sect) << "\t";
992 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
993 j += sizeof(int32_t)) {
994 if (i + j + sizeof(int32_t) < size) {
996 memcpy(&long_word, sect + i + j, sizeof(int32_t));
997 if (O->isLittleEndian() != sys::IsLittleEndianHost)
998 sys::swapByteOrder(long_word);
999 outs() << format("%08" PRIx32, long_word) << " ";
1001 for (uint32_t k = 0; i + j + k < size; k++) {
1002 uint8_t byte_word = *(sect + i + j);
1003 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1012 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1013 StringRef DisSegName, StringRef DisSectName);
1014 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1015 uint32_t size, uint32_t addr);
1017 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1019 SymbolAddressMap AddrMap;
1021 CreateSymbolAddressMap(O, &AddrMap);
1023 for (unsigned i = 0; i < DumpSections.size(); ++i) {
1024 StringRef DumpSection = DumpSections[i];
1025 std::pair<StringRef, StringRef> DumpSegSectName;
1026 DumpSegSectName = DumpSection.split(',');
1027 StringRef DumpSegName, DumpSectName;
1028 if (DumpSegSectName.second.size()) {
1029 DumpSegName = DumpSegSectName.first;
1030 DumpSectName = DumpSegSectName.second;
1033 DumpSectName = DumpSegSectName.first;
1035 for (const SectionRef &Section : O->sections()) {
1037 Section.getName(SectName);
1038 DataRefImpl Ref = Section.getRawDataRefImpl();
1039 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1040 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1041 (SectName == DumpSectName)) {
1043 uint32_t section_flags;
1045 const MachO::section_64 Sec = O->getSection64(Ref);
1046 section_flags = Sec.flags;
1049 const MachO::section Sec = O->getSection(Ref);
1050 section_flags = Sec.flags;
1052 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1055 Section.getContents(BytesStr);
1056 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1057 uint32_t sect_size = BytesStr.size();
1058 uint64_t sect_addr = Section.getAddress();
1061 outs().write(BytesStr.data(), BytesStr.size());
1065 outs() << "Contents of (" << SegName << "," << SectName
1069 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1070 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1071 DisassembleMachO(Filename, O, SegName, SectName);
1074 if (SegName == "__TEXT" && SectName == "__info_plist") {
1078 if (SegName == "__OBJC" && SectName == "__protocol") {
1079 DumpProtocolSection(O, sect, sect_size, sect_addr);
1082 switch (section_type) {
1083 case MachO::S_REGULAR:
1084 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1086 case MachO::S_ZEROFILL:
1087 outs() << "zerofill section and has no contents in the file\n";
1089 case MachO::S_CSTRING_LITERALS:
1090 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1092 case MachO::S_4BYTE_LITERALS:
1093 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1095 case MachO::S_8BYTE_LITERALS:
1096 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1098 case MachO::S_16BYTE_LITERALS:
1099 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1101 case MachO::S_LITERAL_POINTERS:
1102 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1105 case MachO::S_MOD_INIT_FUNC_POINTERS:
1106 case MachO::S_MOD_TERM_FUNC_POINTERS:
1107 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1111 outs() << "Unknown section type ("
1112 << format("0x%08" PRIx32, section_type) << ")\n";
1113 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1117 if (section_type == MachO::S_ZEROFILL)
1118 outs() << "zerofill section and has no contents in the file\n";
1120 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1127 static void DumpInfoPlistSectionContents(StringRef Filename,
1128 MachOObjectFile *O) {
1129 for (const SectionRef &Section : O->sections()) {
1131 Section.getName(SectName);
1132 DataRefImpl Ref = Section.getRawDataRefImpl();
1133 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1134 if (SegName == "__TEXT" && SectName == "__info_plist") {
1135 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1137 Section.getContents(BytesStr);
1138 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1145 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1146 // and if it is and there is a list of architecture flags is specified then
1147 // check to make sure this Mach-O file is one of those architectures or all
1148 // architectures were specified. If not then an error is generated and this
1149 // routine returns false. Else it returns true.
1150 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1151 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1152 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1153 bool ArchFound = false;
1154 MachO::mach_header H;
1155 MachO::mach_header_64 H_64;
1157 if (MachO->is64Bit()) {
1158 H_64 = MachO->MachOObjectFile::getHeader64();
1159 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1161 H = MachO->MachOObjectFile::getHeader();
1162 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1165 for (i = 0; i < ArchFlags.size(); ++i) {
1166 if (ArchFlags[i] == T.getArchName())
1171 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1172 << "architecture: " + ArchFlags[i] + "\n";
1179 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1181 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1182 // archive member and or in a slice of a universal file. It prints the
1183 // the file name and header info and then processes it according to the
1184 // command line options.
1185 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1186 StringRef ArchiveMemberName = StringRef(),
1187 StringRef ArchitectureName = StringRef()) {
1188 // If we are doing some processing here on the Mach-O file print the header
1189 // info. And don't print it otherwise like in the case of printing the
1190 // UniversalHeaders or ArchiveHeaders.
1191 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
1192 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1193 DylibsUsed || DylibId || ObjcMetaData ||
1194 (DumpSections.size() != 0 && !Raw)) {
1196 if (!ArchiveMemberName.empty())
1197 outs() << '(' << ArchiveMemberName << ')';
1198 if (!ArchitectureName.empty())
1199 outs() << " (architecture " << ArchitectureName << ")";
1204 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1205 if (IndirectSymbols)
1206 PrintIndirectSymbols(MachOOF, !NonVerbose);
1208 PrintDataInCodeTable(MachOOF, !NonVerbose);
1210 PrintLinkOptHints(MachOOF);
1212 PrintRelocations(MachOOF);
1214 PrintSectionHeaders(MachOOF);
1215 if (SectionContents)
1216 PrintSectionContents(MachOOF);
1217 if (DumpSections.size() != 0)
1218 DumpSectionContents(Filename, MachOOF, !NonVerbose);
1220 DumpInfoPlistSectionContents(Filename, MachOOF);
1222 PrintDylibs(MachOOF, false);
1224 PrintDylibs(MachOOF, true);
1226 PrintSymbolTable(MachOOF);
1228 printMachOUnwindInfo(MachOOF);
1230 printMachOFileHeader(MachOOF);
1232 printObjcMetaData(MachOOF, !NonVerbose);
1234 printExportsTrie(MachOOF);
1236 printRebaseTable(MachOOF);
1238 printBindTable(MachOOF);
1240 printLazyBindTable(MachOOF);
1242 printWeakBindTable(MachOOF);
1245 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1246 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1247 outs() << " cputype (" << cputype << ")\n";
1248 outs() << " cpusubtype (" << cpusubtype << ")\n";
1251 // printCPUType() helps print_fat_headers by printing the cputype and
1252 // pusubtype (symbolically for the one's it knows about).
1253 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1255 case MachO::CPU_TYPE_I386:
1256 switch (cpusubtype) {
1257 case MachO::CPU_SUBTYPE_I386_ALL:
1258 outs() << " cputype CPU_TYPE_I386\n";
1259 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1262 printUnknownCPUType(cputype, cpusubtype);
1266 case MachO::CPU_TYPE_X86_64:
1267 switch (cpusubtype) {
1268 case MachO::CPU_SUBTYPE_X86_64_ALL:
1269 outs() << " cputype CPU_TYPE_X86_64\n";
1270 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1272 case MachO::CPU_SUBTYPE_X86_64_H:
1273 outs() << " cputype CPU_TYPE_X86_64\n";
1274 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1277 printUnknownCPUType(cputype, cpusubtype);
1281 case MachO::CPU_TYPE_ARM:
1282 switch (cpusubtype) {
1283 case MachO::CPU_SUBTYPE_ARM_ALL:
1284 outs() << " cputype CPU_TYPE_ARM\n";
1285 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1287 case MachO::CPU_SUBTYPE_ARM_V4T:
1288 outs() << " cputype CPU_TYPE_ARM\n";
1289 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1291 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1292 outs() << " cputype CPU_TYPE_ARM\n";
1293 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1295 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1296 outs() << " cputype CPU_TYPE_ARM\n";
1297 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1299 case MachO::CPU_SUBTYPE_ARM_V6:
1300 outs() << " cputype CPU_TYPE_ARM\n";
1301 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1303 case MachO::CPU_SUBTYPE_ARM_V6M:
1304 outs() << " cputype CPU_TYPE_ARM\n";
1305 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1307 case MachO::CPU_SUBTYPE_ARM_V7:
1308 outs() << " cputype CPU_TYPE_ARM\n";
1309 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1311 case MachO::CPU_SUBTYPE_ARM_V7EM:
1312 outs() << " cputype CPU_TYPE_ARM\n";
1313 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1315 case MachO::CPU_SUBTYPE_ARM_V7K:
1316 outs() << " cputype CPU_TYPE_ARM\n";
1317 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1319 case MachO::CPU_SUBTYPE_ARM_V7M:
1320 outs() << " cputype CPU_TYPE_ARM\n";
1321 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1323 case MachO::CPU_SUBTYPE_ARM_V7S:
1324 outs() << " cputype CPU_TYPE_ARM\n";
1325 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1328 printUnknownCPUType(cputype, cpusubtype);
1332 case MachO::CPU_TYPE_ARM64:
1333 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1334 case MachO::CPU_SUBTYPE_ARM64_ALL:
1335 outs() << " cputype CPU_TYPE_ARM64\n";
1336 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1339 printUnknownCPUType(cputype, cpusubtype);
1344 printUnknownCPUType(cputype, cpusubtype);
1349 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1351 outs() << "Fat headers\n";
1353 outs() << "fat_magic FAT_MAGIC\n";
1355 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1357 uint32_t nfat_arch = UB->getNumberOfObjects();
1358 StringRef Buf = UB->getData();
1359 uint64_t size = Buf.size();
1360 uint64_t big_size = sizeof(struct MachO::fat_header) +
1361 nfat_arch * sizeof(struct MachO::fat_arch);
1362 outs() << "nfat_arch " << UB->getNumberOfObjects();
1364 outs() << " (malformed, contains zero architecture types)\n";
1365 else if (big_size > size)
1366 outs() << " (malformed, architectures past end of file)\n";
1370 for (uint32_t i = 0; i < nfat_arch; ++i) {
1371 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1372 uint32_t cputype = OFA.getCPUType();
1373 uint32_t cpusubtype = OFA.getCPUSubType();
1374 outs() << "architecture ";
1375 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1376 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1377 uint32_t other_cputype = other_OFA.getCPUType();
1378 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1379 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1380 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1381 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1382 outs() << "(illegal duplicate architecture) ";
1387 outs() << OFA.getArchTypeName() << "\n";
1388 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1390 outs() << i << "\n";
1391 outs() << " cputype " << cputype << "\n";
1392 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1396 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1397 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1399 outs() << " capabilities "
1400 << format("0x%" PRIx32,
1401 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1402 outs() << " offset " << OFA.getOffset();
1403 if (OFA.getOffset() > size)
1404 outs() << " (past end of file)";
1405 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1406 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1408 outs() << " size " << OFA.getSize();
1409 big_size = OFA.getOffset() + OFA.getSize();
1410 if (big_size > size)
1411 outs() << " (past end of file)";
1413 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1418 static void printArchiveChild(Archive::Child &C, bool verbose,
1419 bool print_offset) {
1421 outs() << C.getChildOffset() << "\t";
1422 sys::fs::perms Mode = C.getAccessMode();
1424 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1425 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1427 if (Mode & sys::fs::owner_read)
1431 if (Mode & sys::fs::owner_write)
1435 if (Mode & sys::fs::owner_exe)
1439 if (Mode & sys::fs::group_read)
1443 if (Mode & sys::fs::group_write)
1447 if (Mode & sys::fs::group_exe)
1451 if (Mode & sys::fs::others_read)
1455 if (Mode & sys::fs::others_write)
1459 if (Mode & sys::fs::others_exe)
1464 outs() << format("0%o ", Mode);
1467 unsigned UID = C.getUID();
1468 outs() << format("%3d/", UID);
1469 unsigned GID = C.getGID();
1470 outs() << format("%-3d ", GID);
1471 uint64_t Size = C.getRawSize();
1472 outs() << format("%5" PRId64, Size) << " ";
1474 StringRef RawLastModified = C.getRawLastModified();
1477 if (RawLastModified.getAsInteger(10, Seconds))
1478 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1480 // Since cime(3) returns a 26 character string of the form:
1481 // "Sun Sep 16 01:03:52 1973\n\0"
1482 // just print 24 characters.
1484 outs() << format("%.24s ", ctime(&t));
1487 outs() << RawLastModified << " ";
1491 ErrorOr<StringRef> NameOrErr = C.getName();
1492 if (NameOrErr.getError()) {
1493 StringRef RawName = C.getRawName();
1494 outs() << RawName << "\n";
1496 StringRef Name = NameOrErr.get();
1497 outs() << Name << "\n";
1500 StringRef RawName = C.getRawName();
1501 outs() << RawName << "\n";
1505 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1506 if (A->hasSymbolTable()) {
1507 Archive::child_iterator S = A->getSymbolTableChild();
1508 Archive::Child C = *S;
1509 printArchiveChild(C, verbose, print_offset);
1511 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1513 Archive::Child C = *I;
1514 printArchiveChild(C, verbose, print_offset);
1518 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1519 // -arch flags selecting just those slices as specified by them and also parses
1520 // archive files. Then for each individual Mach-O file ProcessMachO() is
1521 // called to process the file based on the command line options.
1522 void llvm::ParseInputMachO(StringRef Filename) {
1523 // Check for -arch all and verifiy the -arch flags are valid.
1524 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1525 if (ArchFlags[i] == "all") {
1528 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1529 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1530 "'for the -arch option\n";
1536 // Attempt to open the binary.
1537 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1538 if (std::error_code EC = BinaryOrErr.getError()) {
1539 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
1542 Binary &Bin = *BinaryOrErr.get().getBinary();
1544 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1545 outs() << "Archive : " << Filename << "\n";
1547 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
1548 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1550 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1551 if (ChildOrErr.getError())
1553 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1554 if (!checkMachOAndArchFlags(O, Filename))
1556 ProcessMachO(Filename, O, O->getFileName());
1561 if (UniversalHeaders) {
1562 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1563 printMachOUniversalHeaders(UB, !NonVerbose);
1565 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1566 // If we have a list of architecture flags specified dump only those.
1567 if (!ArchAll && ArchFlags.size() != 0) {
1568 // Look for a slice in the universal binary that matches each ArchFlag.
1570 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1572 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1573 E = UB->end_objects();
1575 if (ArchFlags[i] == I->getArchTypeName()) {
1577 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1578 I->getAsObjectFile();
1579 std::string ArchitectureName = "";
1580 if (ArchFlags.size() > 1)
1581 ArchitectureName = I->getArchTypeName();
1583 ObjectFile &O = *ObjOrErr.get();
1584 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1585 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1586 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1587 I->getAsArchive()) {
1588 std::unique_ptr<Archive> &A = *AOrErr;
1589 outs() << "Archive : " << Filename;
1590 if (!ArchitectureName.empty())
1591 outs() << " (architecture " << ArchitectureName << ")";
1594 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1595 for (Archive::child_iterator AI = A->child_begin(),
1596 AE = A->child_end();
1598 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1599 if (ChildOrErr.getError())
1601 if (MachOObjectFile *O =
1602 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1603 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1609 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1610 << "architecture: " + ArchFlags[i] + "\n";
1616 // No architecture flags were specified so if this contains a slice that
1617 // matches the host architecture dump only that.
1619 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1620 E = UB->end_objects();
1622 if (MachOObjectFile::getHostArch().getArchName() ==
1623 I->getArchTypeName()) {
1624 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1625 std::string ArchiveName;
1626 ArchiveName.clear();
1628 ObjectFile &O = *ObjOrErr.get();
1629 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1630 ProcessMachO(Filename, MachOOF);
1631 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1632 I->getAsArchive()) {
1633 std::unique_ptr<Archive> &A = *AOrErr;
1634 outs() << "Archive : " << Filename << "\n";
1636 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1637 for (Archive::child_iterator AI = A->child_begin(),
1638 AE = A->child_end();
1640 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1641 if (ChildOrErr.getError())
1643 if (MachOObjectFile *O =
1644 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1645 ProcessMachO(Filename, O, O->getFileName());
1652 // Either all architectures have been specified or none have been specified
1653 // and this does not contain the host architecture so dump all the slices.
1654 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1655 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1656 E = UB->end_objects();
1658 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1659 std::string ArchitectureName = "";
1660 if (moreThanOneArch)
1661 ArchitectureName = I->getArchTypeName();
1663 ObjectFile &Obj = *ObjOrErr.get();
1664 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1665 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1666 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1667 std::unique_ptr<Archive> &A = *AOrErr;
1668 outs() << "Archive : " << Filename;
1669 if (!ArchitectureName.empty())
1670 outs() << " (architecture " << ArchitectureName << ")";
1673 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1674 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1676 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1677 if (ChildOrErr.getError())
1679 if (MachOObjectFile *O =
1680 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1681 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1682 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1690 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1691 if (!checkMachOAndArchFlags(O, Filename))
1693 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1694 ProcessMachO(Filename, MachOOF);
1696 errs() << "llvm-objdump: '" << Filename << "': "
1697 << "Object is not a Mach-O file type.\n";
1699 errs() << "llvm-objdump: '" << Filename << "': "
1700 << "Unrecognized file type.\n";
1703 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1704 typedef std::vector<BindInfoEntry> BindTable;
1705 typedef BindTable::iterator bind_table_iterator;
1707 // The block of info used by the Symbolizer call backs.
1708 struct DisassembleInfo {
1712 SymbolAddressMap *AddrMap;
1713 std::vector<SectionRef> *Sections;
1714 const char *class_name;
1715 const char *selector_name;
1717 char *demangled_name;
1720 BindTable *bindtable;
1723 // SymbolizerGetOpInfo() is the operand information call back function.
1724 // This is called to get the symbolic information for operand(s) of an
1725 // instruction when it is being done. This routine does this from
1726 // the relocation information, symbol table, etc. That block of information
1727 // is a pointer to the struct DisassembleInfo that was passed when the
1728 // disassembler context was created and passed to back to here when
1729 // called back by the disassembler for instruction operands that could have
1730 // relocation information. The address of the instruction containing operand is
1731 // at the Pc parameter. The immediate value the operand has is passed in
1732 // op_info->Value and is at Offset past the start of the instruction and has a
1733 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1734 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1735 // names and addends of the symbolic expression to add for the operand. The
1736 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1737 // information is returned then this function returns 1 else it returns 0.
1738 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1739 uint64_t Size, int TagType, void *TagBuf) {
1740 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1741 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1742 uint64_t value = op_info->Value;
1744 // Make sure all fields returned are zero if we don't set them.
1745 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1746 op_info->Value = value;
1748 // If the TagType is not the value 1 which it code knows about or if no
1749 // verbose symbolic information is wanted then just return 0, indicating no
1750 // information is being returned.
1751 if (TagType != 1 || !info->verbose)
1754 unsigned int Arch = info->O->getArch();
1755 if (Arch == Triple::x86) {
1756 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1758 // First search the section's relocation entries (if any) for an entry
1759 // for this section offset.
1760 uint32_t sect_addr = info->S.getAddress();
1761 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1762 bool reloc_found = false;
1764 MachO::any_relocation_info RE;
1765 bool isExtern = false;
1767 bool r_scattered = false;
1768 uint32_t r_value, pair_r_value, r_type;
1769 for (const RelocationRef &Reloc : info->S.relocations()) {
1770 uint64_t RelocOffset = Reloc.getOffset();
1771 if (RelocOffset == sect_offset) {
1772 Rel = Reloc.getRawDataRefImpl();
1773 RE = info->O->getRelocation(Rel);
1774 r_type = info->O->getAnyRelocationType(RE);
1775 r_scattered = info->O->isRelocationScattered(RE);
1777 r_value = info->O->getScatteredRelocationValue(RE);
1778 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1779 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1780 DataRefImpl RelNext = Rel;
1781 info->O->moveRelocationNext(RelNext);
1782 MachO::any_relocation_info RENext;
1783 RENext = info->O->getRelocation(RelNext);
1784 if (info->O->isRelocationScattered(RENext))
1785 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1790 isExtern = info->O->getPlainRelocationExternal(RE);
1792 symbol_iterator RelocSym = Reloc.getSymbol();
1800 if (reloc_found && isExtern) {
1801 ErrorOr<StringRef> SymName = Symbol.getName();
1802 if (std::error_code EC = SymName.getError())
1803 report_fatal_error(EC.message());
1804 const char *name = SymName->data();
1805 op_info->AddSymbol.Present = 1;
1806 op_info->AddSymbol.Name = name;
1807 // For i386 extern relocation entries the value in the instruction is
1808 // the offset from the symbol, and value is already set in op_info->Value.
1811 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1812 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1813 const char *add = GuessSymbolName(r_value, info->AddrMap);
1814 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1815 uint32_t offset = value - (r_value - pair_r_value);
1816 op_info->AddSymbol.Present = 1;
1818 op_info->AddSymbol.Name = add;
1820 op_info->AddSymbol.Value = r_value;
1821 op_info->SubtractSymbol.Present = 1;
1823 op_info->SubtractSymbol.Name = sub;
1825 op_info->SubtractSymbol.Value = pair_r_value;
1826 op_info->Value = offset;
1830 // Second search the external relocation entries of a fully linked image
1831 // (if any) for an entry that matches this segment offset.
1832 // uint32_t seg_offset = (Pc + Offset);
1835 if (Arch == Triple::x86_64) {
1836 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1838 // First search the section's relocation entries (if any) for an entry
1839 // for this section offset.
1840 uint64_t sect_addr = info->S.getAddress();
1841 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1842 bool reloc_found = false;
1844 MachO::any_relocation_info RE;
1845 bool isExtern = false;
1847 for (const RelocationRef &Reloc : info->S.relocations()) {
1848 uint64_t RelocOffset = Reloc.getOffset();
1849 if (RelocOffset == sect_offset) {
1850 Rel = Reloc.getRawDataRefImpl();
1851 RE = info->O->getRelocation(Rel);
1852 // NOTE: Scattered relocations don't exist on x86_64.
1853 isExtern = info->O->getPlainRelocationExternal(RE);
1855 symbol_iterator RelocSym = Reloc.getSymbol();
1862 if (reloc_found && isExtern) {
1863 // The Value passed in will be adjusted by the Pc if the instruction
1864 // adds the Pc. But for x86_64 external relocation entries the Value
1865 // is the offset from the external symbol.
1866 if (info->O->getAnyRelocationPCRel(RE))
1867 op_info->Value -= Pc + Offset + Size;
1868 ErrorOr<StringRef> SymName = Symbol.getName();
1869 if (std::error_code EC = SymName.getError())
1870 report_fatal_error(EC.message());
1871 const char *name = SymName->data();
1872 unsigned Type = info->O->getAnyRelocationType(RE);
1873 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1874 DataRefImpl RelNext = Rel;
1875 info->O->moveRelocationNext(RelNext);
1876 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1877 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1878 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1879 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1880 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1881 op_info->SubtractSymbol.Present = 1;
1882 op_info->SubtractSymbol.Name = name;
1883 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1884 Symbol = *RelocSymNext;
1885 ErrorOr<StringRef> SymNameNext = Symbol.getName();
1886 if (std::error_code EC = SymNameNext.getError())
1887 report_fatal_error(EC.message());
1888 name = SymNameNext->data();
1891 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1892 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1893 op_info->AddSymbol.Present = 1;
1894 op_info->AddSymbol.Name = name;
1898 // Second search the external relocation entries of a fully linked image
1899 // (if any) for an entry that matches this segment offset.
1900 // uint64_t seg_offset = (Pc + Offset);
1903 if (Arch == Triple::arm) {
1904 if (Offset != 0 || (Size != 4 && Size != 2))
1906 // First search the section's relocation entries (if any) for an entry
1907 // for this section offset.
1908 uint32_t sect_addr = info->S.getAddress();
1909 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1911 MachO::any_relocation_info RE;
1912 bool isExtern = false;
1914 bool r_scattered = false;
1915 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1917 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1918 [&](const RelocationRef &Reloc) {
1919 uint64_t RelocOffset = Reloc.getOffset();
1920 return RelocOffset == sect_offset;
1923 if (Reloc == info->S.relocations().end())
1926 Rel = Reloc->getRawDataRefImpl();
1927 RE = info->O->getRelocation(Rel);
1928 r_length = info->O->getAnyRelocationLength(RE);
1929 r_scattered = info->O->isRelocationScattered(RE);
1931 r_value = info->O->getScatteredRelocationValue(RE);
1932 r_type = info->O->getScatteredRelocationType(RE);
1934 r_type = info->O->getAnyRelocationType(RE);
1935 isExtern = info->O->getPlainRelocationExternal(RE);
1937 symbol_iterator RelocSym = Reloc->getSymbol();
1941 if (r_type == MachO::ARM_RELOC_HALF ||
1942 r_type == MachO::ARM_RELOC_SECTDIFF ||
1943 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1944 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1945 DataRefImpl RelNext = Rel;
1946 info->O->moveRelocationNext(RelNext);
1947 MachO::any_relocation_info RENext;
1948 RENext = info->O->getRelocation(RelNext);
1949 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1950 if (info->O->isRelocationScattered(RENext))
1951 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1955 ErrorOr<StringRef> SymName = Symbol.getName();
1956 if (std::error_code EC = SymName.getError())
1957 report_fatal_error(EC.message());
1958 const char *name = SymName->data();
1959 op_info->AddSymbol.Present = 1;
1960 op_info->AddSymbol.Name = name;
1962 case MachO::ARM_RELOC_HALF:
1963 if ((r_length & 0x1) == 1) {
1964 op_info->Value = value << 16 | other_half;
1965 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1967 op_info->Value = other_half << 16 | value;
1968 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1976 // If we have a branch that is not an external relocation entry then
1977 // return 0 so the code in tryAddingSymbolicOperand() can use the
1978 // SymbolLookUp call back with the branch target address to look up the
1979 // symbol and possiblity add an annotation for a symbol stub.
1980 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1981 r_type == MachO::ARM_THUMB_RELOC_BR22))
1984 uint32_t offset = 0;
1985 if (r_type == MachO::ARM_RELOC_HALF ||
1986 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1987 if ((r_length & 0x1) == 1)
1988 value = value << 16 | other_half;
1990 value = other_half << 16 | value;
1992 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1993 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1994 offset = value - r_value;
1998 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1999 if ((r_length & 0x1) == 1)
2000 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2002 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2003 const char *add = GuessSymbolName(r_value, info->AddrMap);
2004 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2005 int32_t offset = value - (r_value - pair_r_value);
2006 op_info->AddSymbol.Present = 1;
2008 op_info->AddSymbol.Name = add;
2010 op_info->AddSymbol.Value = r_value;
2011 op_info->SubtractSymbol.Present = 1;
2013 op_info->SubtractSymbol.Name = sub;
2015 op_info->SubtractSymbol.Value = pair_r_value;
2016 op_info->Value = offset;
2020 op_info->AddSymbol.Present = 1;
2021 op_info->Value = offset;
2022 if (r_type == MachO::ARM_RELOC_HALF) {
2023 if ((r_length & 0x1) == 1)
2024 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2026 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2028 const char *add = GuessSymbolName(value, info->AddrMap);
2029 if (add != nullptr) {
2030 op_info->AddSymbol.Name = add;
2033 op_info->AddSymbol.Value = value;
2036 if (Arch == Triple::aarch64) {
2037 if (Offset != 0 || Size != 4)
2039 // First search the section's relocation entries (if any) for an entry
2040 // for this section offset.
2041 uint64_t sect_addr = info->S.getAddress();
2042 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2044 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2045 [&](const RelocationRef &Reloc) {
2046 uint64_t RelocOffset = Reloc.getOffset();
2047 return RelocOffset == sect_offset;
2050 if (Reloc == info->S.relocations().end())
2053 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2054 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2055 uint32_t r_type = info->O->getAnyRelocationType(RE);
2056 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2057 DataRefImpl RelNext = Rel;
2058 info->O->moveRelocationNext(RelNext);
2059 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2061 value = info->O->getPlainRelocationSymbolNum(RENext);
2062 op_info->Value = value;
2065 // NOTE: Scattered relocations don't exist on arm64.
2066 if (!info->O->getPlainRelocationExternal(RE))
2068 ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
2069 if (std::error_code EC = SymName.getError())
2070 report_fatal_error(EC.message());
2071 const char *name = SymName->data();
2072 op_info->AddSymbol.Present = 1;
2073 op_info->AddSymbol.Name = name;
2076 case MachO::ARM64_RELOC_PAGE21:
2078 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2080 case MachO::ARM64_RELOC_PAGEOFF12:
2082 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2084 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2086 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2088 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2090 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2092 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2093 /* @tvlppage is not implemented in llvm-mc */
2094 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2096 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2097 /* @tvlppageoff is not implemented in llvm-mc */
2098 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2101 case MachO::ARM64_RELOC_BRANCH26:
2102 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2110 // GuessCstringPointer is passed the address of what might be a pointer to a
2111 // literal string in a cstring section. If that address is in a cstring section
2112 // it returns a pointer to that string. Else it returns nullptr.
2113 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2114 struct DisassembleInfo *info) {
2115 for (const auto &Load : info->O->load_commands()) {
2116 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2117 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2118 for (unsigned J = 0; J < Seg.nsects; ++J) {
2119 MachO::section_64 Sec = info->O->getSection64(Load, J);
2120 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2121 if (section_type == MachO::S_CSTRING_LITERALS &&
2122 ReferenceValue >= Sec.addr &&
2123 ReferenceValue < Sec.addr + Sec.size) {
2124 uint64_t sect_offset = ReferenceValue - Sec.addr;
2125 uint64_t object_offset = Sec.offset + sect_offset;
2126 StringRef MachOContents = info->O->getData();
2127 uint64_t object_size = MachOContents.size();
2128 const char *object_addr = (const char *)MachOContents.data();
2129 if (object_offset < object_size) {
2130 const char *name = object_addr + object_offset;
2137 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2138 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2139 for (unsigned J = 0; J < Seg.nsects; ++J) {
2140 MachO::section Sec = info->O->getSection(Load, J);
2141 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2142 if (section_type == MachO::S_CSTRING_LITERALS &&
2143 ReferenceValue >= Sec.addr &&
2144 ReferenceValue < Sec.addr + Sec.size) {
2145 uint64_t sect_offset = ReferenceValue - Sec.addr;
2146 uint64_t object_offset = Sec.offset + sect_offset;
2147 StringRef MachOContents = info->O->getData();
2148 uint64_t object_size = MachOContents.size();
2149 const char *object_addr = (const char *)MachOContents.data();
2150 if (object_offset < object_size) {
2151 const char *name = object_addr + object_offset;
2163 // GuessIndirectSymbol returns the name of the indirect symbol for the
2164 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2165 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2166 // symbol name being referenced by the stub or pointer.
2167 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2168 struct DisassembleInfo *info) {
2169 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2170 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2171 for (const auto &Load : info->O->load_commands()) {
2172 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2173 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2174 for (unsigned J = 0; J < Seg.nsects; ++J) {
2175 MachO::section_64 Sec = info->O->getSection64(Load, J);
2176 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2177 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2178 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2179 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2180 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2181 section_type == MachO::S_SYMBOL_STUBS) &&
2182 ReferenceValue >= Sec.addr &&
2183 ReferenceValue < Sec.addr + Sec.size) {
2185 if (section_type == MachO::S_SYMBOL_STUBS)
2186 stride = Sec.reserved2;
2191 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2192 if (index < Dysymtab.nindirectsyms) {
2193 uint32_t indirect_symbol =
2194 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2195 if (indirect_symbol < Symtab.nsyms) {
2196 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2197 SymbolRef Symbol = *Sym;
2198 ErrorOr<StringRef> SymName = Symbol.getName();
2199 if (std::error_code EC = SymName.getError())
2200 report_fatal_error(EC.message());
2201 const char *name = SymName->data();
2207 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2208 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2209 for (unsigned J = 0; J < Seg.nsects; ++J) {
2210 MachO::section Sec = info->O->getSection(Load, J);
2211 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2212 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2213 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2214 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2215 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2216 section_type == MachO::S_SYMBOL_STUBS) &&
2217 ReferenceValue >= Sec.addr &&
2218 ReferenceValue < Sec.addr + Sec.size) {
2220 if (section_type == MachO::S_SYMBOL_STUBS)
2221 stride = Sec.reserved2;
2226 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2227 if (index < Dysymtab.nindirectsyms) {
2228 uint32_t indirect_symbol =
2229 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2230 if (indirect_symbol < Symtab.nsyms) {
2231 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2232 SymbolRef Symbol = *Sym;
2233 ErrorOr<StringRef> SymName = Symbol.getName();
2234 if (std::error_code EC = SymName.getError())
2235 report_fatal_error(EC.message());
2236 const char *name = SymName->data();
2247 // method_reference() is called passing it the ReferenceName that might be
2248 // a reference it to an Objective-C method call. If so then it allocates and
2249 // assembles a method call string with the values last seen and saved in
2250 // the DisassembleInfo's class_name and selector_name fields. This is saved
2251 // into the method field of the info and any previous string is free'ed.
2252 // Then the class_name field in the info is set to nullptr. The method call
2253 // string is set into ReferenceName and ReferenceType is set to
2254 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2255 // then both ReferenceType and ReferenceName are left unchanged.
2256 static void method_reference(struct DisassembleInfo *info,
2257 uint64_t *ReferenceType,
2258 const char **ReferenceName) {
2259 unsigned int Arch = info->O->getArch();
2260 if (*ReferenceName != nullptr) {
2261 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2262 if (info->selector_name != nullptr) {
2263 if (info->method != nullptr)
2265 if (info->class_name != nullptr) {
2266 info->method = (char *)malloc(5 + strlen(info->class_name) +
2267 strlen(info->selector_name));
2268 if (info->method != nullptr) {
2269 strcpy(info->method, "+[");
2270 strcat(info->method, info->class_name);
2271 strcat(info->method, " ");
2272 strcat(info->method, info->selector_name);
2273 strcat(info->method, "]");
2274 *ReferenceName = info->method;
2275 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2278 info->method = (char *)malloc(9 + strlen(info->selector_name));
2279 if (info->method != nullptr) {
2280 if (Arch == Triple::x86_64)
2281 strcpy(info->method, "-[%rdi ");
2282 else if (Arch == Triple::aarch64)
2283 strcpy(info->method, "-[x0 ");
2285 strcpy(info->method, "-[r? ");
2286 strcat(info->method, info->selector_name);
2287 strcat(info->method, "]");
2288 *ReferenceName = info->method;
2289 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2292 info->class_name = nullptr;
2294 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2295 if (info->selector_name != nullptr) {
2296 if (info->method != nullptr)
2298 info->method = (char *)malloc(17 + strlen(info->selector_name));
2299 if (info->method != nullptr) {
2300 if (Arch == Triple::x86_64)
2301 strcpy(info->method, "-[[%rdi super] ");
2302 else if (Arch == Triple::aarch64)
2303 strcpy(info->method, "-[[x0 super] ");
2305 strcpy(info->method, "-[[r? super] ");
2306 strcat(info->method, info->selector_name);
2307 strcat(info->method, "]");
2308 *ReferenceName = info->method;
2309 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2311 info->class_name = nullptr;
2317 // GuessPointerPointer() is passed the address of what might be a pointer to
2318 // a reference to an Objective-C class, selector, message ref or cfstring.
2319 // If so the value of the pointer is returned and one of the booleans are set
2320 // to true. If not zero is returned and all the booleans are set to false.
2321 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2322 struct DisassembleInfo *info,
2323 bool &classref, bool &selref, bool &msgref,
2329 for (const auto &Load : info->O->load_commands()) {
2330 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2331 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2332 for (unsigned J = 0; J < Seg.nsects; ++J) {
2333 MachO::section_64 Sec = info->O->getSection64(Load, J);
2334 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2335 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2336 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2337 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2338 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2339 ReferenceValue >= Sec.addr &&
2340 ReferenceValue < Sec.addr + Sec.size) {
2341 uint64_t sect_offset = ReferenceValue - Sec.addr;
2342 uint64_t object_offset = Sec.offset + sect_offset;
2343 StringRef MachOContents = info->O->getData();
2344 uint64_t object_size = MachOContents.size();
2345 const char *object_addr = (const char *)MachOContents.data();
2346 if (object_offset < object_size) {
2347 uint64_t pointer_value;
2348 memcpy(&pointer_value, object_addr + object_offset,
2350 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2351 sys::swapByteOrder(pointer_value);
2352 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2354 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2355 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2357 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2358 ReferenceValue + 8 < Sec.addr + Sec.size) {
2360 memcpy(&pointer_value, object_addr + object_offset + 8,
2362 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2363 sys::swapByteOrder(pointer_value);
2364 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2366 return pointer_value;
2373 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2378 // get_pointer_64 returns a pointer to the bytes in the object file at the
2379 // Address from a section in the Mach-O file. And indirectly returns the
2380 // offset into the section, number of bytes left in the section past the offset
2381 // and which section is was being referenced. If the Address is not in a
2382 // section nullptr is returned.
2383 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2384 uint32_t &left, SectionRef &S,
2385 DisassembleInfo *info,
2386 bool objc_only = false) {
2390 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2391 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2392 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2395 ((*(info->Sections))[SectIdx]).getName(SectName);
2396 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2397 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2398 if (SegName != "__OBJC" && SectName != "__cstring")
2401 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2402 S = (*(info->Sections))[SectIdx];
2403 offset = Address - SectAddress;
2404 left = SectSize - offset;
2405 StringRef SectContents;
2406 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2407 return SectContents.data() + offset;
2413 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2414 uint32_t &left, SectionRef &S,
2415 DisassembleInfo *info,
2416 bool objc_only = false) {
2417 return get_pointer_64(Address, offset, left, S, info, objc_only);
2420 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2421 // the symbol indirectly through n_value. Based on the relocation information
2422 // for the specified section offset in the specified section reference.
2423 // If no relocation information is found and a non-zero ReferenceValue for the
2424 // symbol is passed, look up that address in the info's AddrMap.
2425 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2426 DisassembleInfo *info, uint64_t &n_value,
2427 uint64_t ReferenceValue = UnknownAddress) {
2432 // See if there is an external relocation entry at the sect_offset.
2433 bool reloc_found = false;
2435 MachO::any_relocation_info RE;
2436 bool isExtern = false;
2438 for (const RelocationRef &Reloc : S.relocations()) {
2439 uint64_t RelocOffset = Reloc.getOffset();
2440 if (RelocOffset == sect_offset) {
2441 Rel = Reloc.getRawDataRefImpl();
2442 RE = info->O->getRelocation(Rel);
2443 if (info->O->isRelocationScattered(RE))
2445 isExtern = info->O->getPlainRelocationExternal(RE);
2447 symbol_iterator RelocSym = Reloc.getSymbol();
2454 // If there is an external relocation entry for a symbol in this section
2455 // at this section_offset then use that symbol's value for the n_value
2456 // and return its name.
2457 const char *SymbolName = nullptr;
2458 if (reloc_found && isExtern) {
2459 Symbol.getAddress(n_value);
2460 if (n_value == UnknownAddress)
2462 ErrorOr<StringRef> NameOrError = Symbol.getName();
2463 if (std::error_code EC = NameOrError.getError())
2464 report_fatal_error(EC.message());
2465 StringRef Name = *NameOrError;
2466 if (!Name.empty()) {
2467 SymbolName = Name.data();
2472 // TODO: For fully linked images, look through the external relocation
2473 // entries off the dynamic symtab command. For these the r_offset is from the
2474 // start of the first writeable segment in the Mach-O file. So the offset
2475 // to this section from that segment is passed to this routine by the caller,
2476 // as the database_offset. Which is the difference of the section's starting
2477 // address and the first writable segment.
2479 // NOTE: need add passing the database_offset to this routine.
2481 // We did not find an external relocation entry so look up the ReferenceValue
2482 // as an address of a symbol and if found return that symbol's name.
2483 if (ReferenceValue != UnknownAddress)
2484 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2489 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2490 DisassembleInfo *info,
2491 uint32_t ReferenceValue) {
2493 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2496 // These are structs in the Objective-C meta data and read to produce the
2497 // comments for disassembly. While these are part of the ABI they are no
2498 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2500 // The cfstring object in a 64-bit Mach-O file.
2501 struct cfstring64_t {
2502 uint64_t isa; // class64_t * (64-bit pointer)
2503 uint64_t flags; // flag bits
2504 uint64_t characters; // char * (64-bit pointer)
2505 uint64_t length; // number of non-NULL characters in above
2508 // The class object in a 64-bit Mach-O file.
2510 uint64_t isa; // class64_t * (64-bit pointer)
2511 uint64_t superclass; // class64_t * (64-bit pointer)
2512 uint64_t cache; // Cache (64-bit pointer)
2513 uint64_t vtable; // IMP * (64-bit pointer)
2514 uint64_t data; // class_ro64_t * (64-bit pointer)
2518 uint32_t isa; /* class32_t * (32-bit pointer) */
2519 uint32_t superclass; /* class32_t * (32-bit pointer) */
2520 uint32_t cache; /* Cache (32-bit pointer) */
2521 uint32_t vtable; /* IMP * (32-bit pointer) */
2522 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2525 struct class_ro64_t {
2527 uint32_t instanceStart;
2528 uint32_t instanceSize;
2530 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2531 uint64_t name; // const char * (64-bit pointer)
2532 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2533 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2534 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2535 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2536 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2539 struct class_ro32_t {
2541 uint32_t instanceStart;
2542 uint32_t instanceSize;
2543 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2544 uint32_t name; /* const char * (32-bit pointer) */
2545 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2546 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2547 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2548 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2549 uint32_t baseProperties; /* const struct objc_property_list *
2553 /* Values for class_ro{64,32}_t->flags */
2554 #define RO_META (1 << 0)
2555 #define RO_ROOT (1 << 1)
2556 #define RO_HAS_CXX_STRUCTORS (1 << 2)
2558 struct method_list64_t {
2561 /* struct method64_t first; These structures follow inline */
2564 struct method_list32_t {
2567 /* struct method32_t first; These structures follow inline */
2571 uint64_t name; /* SEL (64-bit pointer) */
2572 uint64_t types; /* const char * (64-bit pointer) */
2573 uint64_t imp; /* IMP (64-bit pointer) */
2577 uint32_t name; /* SEL (32-bit pointer) */
2578 uint32_t types; /* const char * (32-bit pointer) */
2579 uint32_t imp; /* IMP (32-bit pointer) */
2582 struct protocol_list64_t {
2583 uint64_t count; /* uintptr_t (a 64-bit value) */
2584 /* struct protocol64_t * list[0]; These pointers follow inline */
2587 struct protocol_list32_t {
2588 uint32_t count; /* uintptr_t (a 32-bit value) */
2589 /* struct protocol32_t * list[0]; These pointers follow inline */
2592 struct protocol64_t {
2593 uint64_t isa; /* id * (64-bit pointer) */
2594 uint64_t name; /* const char * (64-bit pointer) */
2595 uint64_t protocols; /* struct protocol_list64_t *
2597 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2598 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2599 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2600 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2601 uint64_t instanceProperties; /* struct objc_property_list *
2605 struct protocol32_t {
2606 uint32_t isa; /* id * (32-bit pointer) */
2607 uint32_t name; /* const char * (32-bit pointer) */
2608 uint32_t protocols; /* struct protocol_list_t *
2610 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2611 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2612 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2613 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2614 uint32_t instanceProperties; /* struct objc_property_list *
2618 struct ivar_list64_t {
2621 /* struct ivar64_t first; These structures follow inline */
2624 struct ivar_list32_t {
2627 /* struct ivar32_t first; These structures follow inline */
2631 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2632 uint64_t name; /* const char * (64-bit pointer) */
2633 uint64_t type; /* const char * (64-bit pointer) */
2639 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2640 uint32_t name; /* const char * (32-bit pointer) */
2641 uint32_t type; /* const char * (32-bit pointer) */
2646 struct objc_property_list64 {
2649 /* struct objc_property64 first; These structures follow inline */
2652 struct objc_property_list32 {
2655 /* struct objc_property32 first; These structures follow inline */
2658 struct objc_property64 {
2659 uint64_t name; /* const char * (64-bit pointer) */
2660 uint64_t attributes; /* const char * (64-bit pointer) */
2663 struct objc_property32 {
2664 uint32_t name; /* const char * (32-bit pointer) */
2665 uint32_t attributes; /* const char * (32-bit pointer) */
2668 struct category64_t {
2669 uint64_t name; /* const char * (64-bit pointer) */
2670 uint64_t cls; /* struct class_t * (64-bit pointer) */
2671 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2672 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2673 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2674 uint64_t instanceProperties; /* struct objc_property_list *
2678 struct category32_t {
2679 uint32_t name; /* const char * (32-bit pointer) */
2680 uint32_t cls; /* struct class_t * (32-bit pointer) */
2681 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2682 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2683 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2684 uint32_t instanceProperties; /* struct objc_property_list *
2688 struct objc_image_info64 {
2692 struct objc_image_info32 {
2696 struct imageInfo_t {
2700 /* masks for objc_image_info.flags */
2701 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2702 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2704 struct message_ref64 {
2705 uint64_t imp; /* IMP (64-bit pointer) */
2706 uint64_t sel; /* SEL (64-bit pointer) */
2709 struct message_ref32 {
2710 uint32_t imp; /* IMP (32-bit pointer) */
2711 uint32_t sel; /* SEL (32-bit pointer) */
2714 // Objective-C 1 (32-bit only) meta data structs.
2716 struct objc_module_t {
2719 uint32_t name; /* char * (32-bit pointer) */
2720 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2723 struct objc_symtab_t {
2724 uint32_t sel_ref_cnt;
2725 uint32_t refs; /* SEL * (32-bit pointer) */
2726 uint16_t cls_def_cnt;
2727 uint16_t cat_def_cnt;
2728 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2731 struct objc_class_t {
2732 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2733 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2734 uint32_t name; /* const char * (32-bit pointer) */
2737 int32_t instance_size;
2738 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2739 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2740 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2741 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2744 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2745 // class is not a metaclass
2746 #define CLS_CLASS 0x1
2747 // class is a metaclass
2748 #define CLS_META 0x2
2750 struct objc_category_t {
2751 uint32_t category_name; /* char * (32-bit pointer) */
2752 uint32_t class_name; /* char * (32-bit pointer) */
2753 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2754 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2755 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2758 struct objc_ivar_t {
2759 uint32_t ivar_name; /* char * (32-bit pointer) */
2760 uint32_t ivar_type; /* char * (32-bit pointer) */
2761 int32_t ivar_offset;
2764 struct objc_ivar_list_t {
2766 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2769 struct objc_method_list_t {
2770 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2771 int32_t method_count;
2772 // struct objc_method_t method_list[1]; /* variable length structure */
2775 struct objc_method_t {
2776 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2777 uint32_t method_types; /* char * (32-bit pointer) */
2778 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2782 struct objc_protocol_list_t {
2783 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2785 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2786 // (32-bit pointer) */
2789 struct objc_protocol_t {
2790 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2791 uint32_t protocol_name; /* char * (32-bit pointer) */
2792 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2793 uint32_t instance_methods; /* struct objc_method_description_list *
2795 uint32_t class_methods; /* struct objc_method_description_list *
2799 struct objc_method_description_list_t {
2801 // struct objc_method_description_t list[1];
2804 struct objc_method_description_t {
2805 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2806 uint32_t types; /* char * (32-bit pointer) */
2809 inline void swapStruct(struct cfstring64_t &cfs) {
2810 sys::swapByteOrder(cfs.isa);
2811 sys::swapByteOrder(cfs.flags);
2812 sys::swapByteOrder(cfs.characters);
2813 sys::swapByteOrder(cfs.length);
2816 inline void swapStruct(struct class64_t &c) {
2817 sys::swapByteOrder(c.isa);
2818 sys::swapByteOrder(c.superclass);
2819 sys::swapByteOrder(c.cache);
2820 sys::swapByteOrder(c.vtable);
2821 sys::swapByteOrder(c.data);
2824 inline void swapStruct(struct class32_t &c) {
2825 sys::swapByteOrder(c.isa);
2826 sys::swapByteOrder(c.superclass);
2827 sys::swapByteOrder(c.cache);
2828 sys::swapByteOrder(c.vtable);
2829 sys::swapByteOrder(c.data);
2832 inline void swapStruct(struct class_ro64_t &cro) {
2833 sys::swapByteOrder(cro.flags);
2834 sys::swapByteOrder(cro.instanceStart);
2835 sys::swapByteOrder(cro.instanceSize);
2836 sys::swapByteOrder(cro.reserved);
2837 sys::swapByteOrder(cro.ivarLayout);
2838 sys::swapByteOrder(cro.name);
2839 sys::swapByteOrder(cro.baseMethods);
2840 sys::swapByteOrder(cro.baseProtocols);
2841 sys::swapByteOrder(cro.ivars);
2842 sys::swapByteOrder(cro.weakIvarLayout);
2843 sys::swapByteOrder(cro.baseProperties);
2846 inline void swapStruct(struct class_ro32_t &cro) {
2847 sys::swapByteOrder(cro.flags);
2848 sys::swapByteOrder(cro.instanceStart);
2849 sys::swapByteOrder(cro.instanceSize);
2850 sys::swapByteOrder(cro.ivarLayout);
2851 sys::swapByteOrder(cro.name);
2852 sys::swapByteOrder(cro.baseMethods);
2853 sys::swapByteOrder(cro.baseProtocols);
2854 sys::swapByteOrder(cro.ivars);
2855 sys::swapByteOrder(cro.weakIvarLayout);
2856 sys::swapByteOrder(cro.baseProperties);
2859 inline void swapStruct(struct method_list64_t &ml) {
2860 sys::swapByteOrder(ml.entsize);
2861 sys::swapByteOrder(ml.count);
2864 inline void swapStruct(struct method_list32_t &ml) {
2865 sys::swapByteOrder(ml.entsize);
2866 sys::swapByteOrder(ml.count);
2869 inline void swapStruct(struct method64_t &m) {
2870 sys::swapByteOrder(m.name);
2871 sys::swapByteOrder(m.types);
2872 sys::swapByteOrder(m.imp);
2875 inline void swapStruct(struct method32_t &m) {
2876 sys::swapByteOrder(m.name);
2877 sys::swapByteOrder(m.types);
2878 sys::swapByteOrder(m.imp);
2881 inline void swapStruct(struct protocol_list64_t &pl) {
2882 sys::swapByteOrder(pl.count);
2885 inline void swapStruct(struct protocol_list32_t &pl) {
2886 sys::swapByteOrder(pl.count);
2889 inline void swapStruct(struct protocol64_t &p) {
2890 sys::swapByteOrder(p.isa);
2891 sys::swapByteOrder(p.name);
2892 sys::swapByteOrder(p.protocols);
2893 sys::swapByteOrder(p.instanceMethods);
2894 sys::swapByteOrder(p.classMethods);
2895 sys::swapByteOrder(p.optionalInstanceMethods);
2896 sys::swapByteOrder(p.optionalClassMethods);
2897 sys::swapByteOrder(p.instanceProperties);
2900 inline void swapStruct(struct protocol32_t &p) {
2901 sys::swapByteOrder(p.isa);
2902 sys::swapByteOrder(p.name);
2903 sys::swapByteOrder(p.protocols);
2904 sys::swapByteOrder(p.instanceMethods);
2905 sys::swapByteOrder(p.classMethods);
2906 sys::swapByteOrder(p.optionalInstanceMethods);
2907 sys::swapByteOrder(p.optionalClassMethods);
2908 sys::swapByteOrder(p.instanceProperties);
2911 inline void swapStruct(struct ivar_list64_t &il) {
2912 sys::swapByteOrder(il.entsize);
2913 sys::swapByteOrder(il.count);
2916 inline void swapStruct(struct ivar_list32_t &il) {
2917 sys::swapByteOrder(il.entsize);
2918 sys::swapByteOrder(il.count);
2921 inline void swapStruct(struct ivar64_t &i) {
2922 sys::swapByteOrder(i.offset);
2923 sys::swapByteOrder(i.name);
2924 sys::swapByteOrder(i.type);
2925 sys::swapByteOrder(i.alignment);
2926 sys::swapByteOrder(i.size);
2929 inline void swapStruct(struct ivar32_t &i) {
2930 sys::swapByteOrder(i.offset);
2931 sys::swapByteOrder(i.name);
2932 sys::swapByteOrder(i.type);
2933 sys::swapByteOrder(i.alignment);
2934 sys::swapByteOrder(i.size);
2937 inline void swapStruct(struct objc_property_list64 &pl) {
2938 sys::swapByteOrder(pl.entsize);
2939 sys::swapByteOrder(pl.count);
2942 inline void swapStruct(struct objc_property_list32 &pl) {
2943 sys::swapByteOrder(pl.entsize);
2944 sys::swapByteOrder(pl.count);
2947 inline void swapStruct(struct objc_property64 &op) {
2948 sys::swapByteOrder(op.name);
2949 sys::swapByteOrder(op.attributes);
2952 inline void swapStruct(struct objc_property32 &op) {
2953 sys::swapByteOrder(op.name);
2954 sys::swapByteOrder(op.attributes);
2957 inline void swapStruct(struct category64_t &c) {
2958 sys::swapByteOrder(c.name);
2959 sys::swapByteOrder(c.cls);
2960 sys::swapByteOrder(c.instanceMethods);
2961 sys::swapByteOrder(c.classMethods);
2962 sys::swapByteOrder(c.protocols);
2963 sys::swapByteOrder(c.instanceProperties);
2966 inline void swapStruct(struct category32_t &c) {
2967 sys::swapByteOrder(c.name);
2968 sys::swapByteOrder(c.cls);
2969 sys::swapByteOrder(c.instanceMethods);
2970 sys::swapByteOrder(c.classMethods);
2971 sys::swapByteOrder(c.protocols);
2972 sys::swapByteOrder(c.instanceProperties);
2975 inline void swapStruct(struct objc_image_info64 &o) {
2976 sys::swapByteOrder(o.version);
2977 sys::swapByteOrder(o.flags);
2980 inline void swapStruct(struct objc_image_info32 &o) {
2981 sys::swapByteOrder(o.version);
2982 sys::swapByteOrder(o.flags);
2985 inline void swapStruct(struct imageInfo_t &o) {
2986 sys::swapByteOrder(o.version);
2987 sys::swapByteOrder(o.flags);
2990 inline void swapStruct(struct message_ref64 &mr) {
2991 sys::swapByteOrder(mr.imp);
2992 sys::swapByteOrder(mr.sel);
2995 inline void swapStruct(struct message_ref32 &mr) {
2996 sys::swapByteOrder(mr.imp);
2997 sys::swapByteOrder(mr.sel);
3000 inline void swapStruct(struct objc_module_t &module) {
3001 sys::swapByteOrder(module.version);
3002 sys::swapByteOrder(module.size);
3003 sys::swapByteOrder(module.name);
3004 sys::swapByteOrder(module.symtab);
3007 inline void swapStruct(struct objc_symtab_t &symtab) {
3008 sys::swapByteOrder(symtab.sel_ref_cnt);
3009 sys::swapByteOrder(symtab.refs);
3010 sys::swapByteOrder(symtab.cls_def_cnt);
3011 sys::swapByteOrder(symtab.cat_def_cnt);
3014 inline void swapStruct(struct objc_class_t &objc_class) {
3015 sys::swapByteOrder(objc_class.isa);
3016 sys::swapByteOrder(objc_class.super_class);
3017 sys::swapByteOrder(objc_class.name);
3018 sys::swapByteOrder(objc_class.version);
3019 sys::swapByteOrder(objc_class.info);
3020 sys::swapByteOrder(objc_class.instance_size);
3021 sys::swapByteOrder(objc_class.ivars);
3022 sys::swapByteOrder(objc_class.methodLists);
3023 sys::swapByteOrder(objc_class.cache);
3024 sys::swapByteOrder(objc_class.protocols);
3027 inline void swapStruct(struct objc_category_t &objc_category) {
3028 sys::swapByteOrder(objc_category.category_name);
3029 sys::swapByteOrder(objc_category.class_name);
3030 sys::swapByteOrder(objc_category.instance_methods);
3031 sys::swapByteOrder(objc_category.class_methods);
3032 sys::swapByteOrder(objc_category.protocols);
3035 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3036 sys::swapByteOrder(objc_ivar_list.ivar_count);
3039 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3040 sys::swapByteOrder(objc_ivar.ivar_name);
3041 sys::swapByteOrder(objc_ivar.ivar_type);
3042 sys::swapByteOrder(objc_ivar.ivar_offset);
3045 inline void swapStruct(struct objc_method_list_t &method_list) {
3046 sys::swapByteOrder(method_list.obsolete);
3047 sys::swapByteOrder(method_list.method_count);
3050 inline void swapStruct(struct objc_method_t &method) {
3051 sys::swapByteOrder(method.method_name);
3052 sys::swapByteOrder(method.method_types);
3053 sys::swapByteOrder(method.method_imp);
3056 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3057 sys::swapByteOrder(protocol_list.next);
3058 sys::swapByteOrder(protocol_list.count);
3061 inline void swapStruct(struct objc_protocol_t &protocol) {
3062 sys::swapByteOrder(protocol.isa);
3063 sys::swapByteOrder(protocol.protocol_name);
3064 sys::swapByteOrder(protocol.protocol_list);
3065 sys::swapByteOrder(protocol.instance_methods);
3066 sys::swapByteOrder(protocol.class_methods);
3069 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3070 sys::swapByteOrder(mdl.count);
3073 inline void swapStruct(struct objc_method_description_t &md) {
3074 sys::swapByteOrder(md.name);
3075 sys::swapByteOrder(md.types);
3078 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3079 struct DisassembleInfo *info);
3081 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3082 // to an Objective-C class and returns the class name. It is also passed the
3083 // address of the pointer, so when the pointer is zero as it can be in an .o
3084 // file, that is used to look for an external relocation entry with a symbol
3086 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3087 uint64_t ReferenceValue,
3088 struct DisassembleInfo *info) {
3090 uint32_t offset, left;
3093 // The pointer_value can be 0 in an object file and have a relocation
3094 // entry for the class symbol at the ReferenceValue (the address of the
3096 if (pointer_value == 0) {
3097 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3098 if (r == nullptr || left < sizeof(uint64_t))
3101 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3102 if (symbol_name == nullptr)
3104 const char *class_name = strrchr(symbol_name, '$');
3105 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3106 return class_name + 2;
3111 // The case were the pointer_value is non-zero and points to a class defined
3112 // in this Mach-O file.
3113 r = get_pointer_64(pointer_value, offset, left, S, info);
3114 if (r == nullptr || left < sizeof(struct class64_t))
3117 memcpy(&c, r, sizeof(struct class64_t));
3118 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3122 r = get_pointer_64(c.data, offset, left, S, info);
3123 if (r == nullptr || left < sizeof(struct class_ro64_t))
3125 struct class_ro64_t cro;
3126 memcpy(&cro, r, sizeof(struct class_ro64_t));
3127 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3131 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3135 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3136 // pointer to a cfstring and returns its name or nullptr.
3137 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3138 struct DisassembleInfo *info) {
3139 const char *r, *name;
3140 uint32_t offset, left;
3142 struct cfstring64_t cfs;
3143 uint64_t cfs_characters;
3145 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3146 if (r == nullptr || left < sizeof(struct cfstring64_t))
3148 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3149 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3151 if (cfs.characters == 0) {
3153 const char *symbol_name = get_symbol_64(
3154 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3155 if (symbol_name == nullptr)
3157 cfs_characters = n_value;
3159 cfs_characters = cfs.characters;
3160 name = get_pointer_64(cfs_characters, offset, left, S, info);
3165 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
3166 // of a pointer to an Objective-C selector reference when the pointer value is
3167 // zero as in a .o file and is likely to have a external relocation entry with
3168 // who's symbol's n_value is the real pointer to the selector name. If that is
3169 // the case the real pointer to the selector name is returned else 0 is
3171 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3172 struct DisassembleInfo *info) {
3173 uint32_t offset, left;
3176 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3177 if (r == nullptr || left < sizeof(uint64_t))
3180 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3181 if (symbol_name == nullptr)
3186 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3187 const char *sectname) {
3188 for (const SectionRef &Section : O->sections()) {
3190 Section.getName(SectName);
3191 DataRefImpl Ref = Section.getRawDataRefImpl();
3192 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3193 if (SegName == segname && SectName == sectname)
3196 return SectionRef();
3200 walk_pointer_list_64(const char *listname, const SectionRef S,
3201 MachOObjectFile *O, struct DisassembleInfo *info,
3202 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3203 if (S == SectionRef())
3207 S.getName(SectName);
3208 DataRefImpl Ref = S.getRawDataRefImpl();
3209 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3210 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3213 S.getContents(BytesStr);
3214 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3216 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3217 uint32_t left = S.getSize() - i;
3218 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3220 memcpy(&p, Contents + i, size);
3221 if (i + sizeof(uint64_t) > S.getSize())
3222 outs() << listname << " list pointer extends past end of (" << SegName
3223 << "," << SectName << ") section\n";
3224 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3226 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3227 sys::swapByteOrder(p);
3229 uint64_t n_value = 0;
3230 const char *name = get_symbol_64(i, S, info, n_value, p);
3231 if (name == nullptr)
3232 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3235 outs() << format("0x%" PRIx64, n_value);
3237 outs() << " + " << format("0x%" PRIx64, p);
3239 outs() << format("0x%" PRIx64, p);
3240 if (name != nullptr)
3241 outs() << " " << name;
3251 walk_pointer_list_32(const char *listname, const SectionRef S,
3252 MachOObjectFile *O, struct DisassembleInfo *info,
3253 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3254 if (S == SectionRef())
3258 S.getName(SectName);
3259 DataRefImpl Ref = S.getRawDataRefImpl();
3260 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3261 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3264 S.getContents(BytesStr);
3265 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3267 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3268 uint32_t left = S.getSize() - i;
3269 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3271 memcpy(&p, Contents + i, size);
3272 if (i + sizeof(uint32_t) > S.getSize())
3273 outs() << listname << " list pointer extends past end of (" << SegName
3274 << "," << SectName << ") section\n";
3275 uint32_t Address = S.getAddress() + i;
3276 outs() << format("%08" PRIx32, Address) << " ";
3278 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3279 sys::swapByteOrder(p);
3280 outs() << format("0x%" PRIx32, p);
3282 const char *name = get_symbol_32(i, S, info, p);
3283 if (name != nullptr)
3284 outs() << " " << name;
3292 static void print_layout_map(const char *layout_map, uint32_t left) {
3293 outs() << " layout map: ";
3295 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3298 } while (*layout_map != '\0' && left != 0);
3302 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3303 uint32_t offset, left;
3305 const char *layout_map;
3309 layout_map = get_pointer_64(p, offset, left, S, info);
3310 print_layout_map(layout_map, left);
3313 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3314 uint32_t offset, left;
3316 const char *layout_map;
3320 layout_map = get_pointer_32(p, offset, left, S, info);
3321 print_layout_map(layout_map, left);
3324 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3325 const char *indent) {
3326 struct method_list64_t ml;
3327 struct method64_t m;
3329 uint32_t offset, xoffset, left, i;
3331 const char *name, *sym_name;
3334 r = get_pointer_64(p, offset, left, S, info);
3337 memset(&ml, '\0', sizeof(struct method_list64_t));
3338 if (left < sizeof(struct method_list64_t)) {
3339 memcpy(&ml, r, left);
3340 outs() << " (method_list_t entends past the end of the section)\n";
3342 memcpy(&ml, r, sizeof(struct method_list64_t));
3343 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3345 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3346 outs() << indent << "\t\t count " << ml.count << "\n";
3348 p += sizeof(struct method_list64_t);
3349 offset += sizeof(struct method_list64_t);
3350 for (i = 0; i < ml.count; i++) {
3351 r = get_pointer_64(p, offset, left, S, info);
3354 memset(&m, '\0', sizeof(struct method64_t));
3355 if (left < sizeof(struct method64_t)) {
3356 memcpy(&ml, r, left);
3357 outs() << indent << " (method_t entends past the end of the section)\n";
3359 memcpy(&m, r, sizeof(struct method64_t));
3360 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3363 outs() << indent << "\t\t name ";
3364 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3365 info, n_value, m.name);
3367 if (info->verbose && sym_name != nullptr)
3370 outs() << format("0x%" PRIx64, n_value);
3372 outs() << " + " << format("0x%" PRIx64, m.name);
3374 outs() << format("0x%" PRIx64, m.name);
3375 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3376 if (name != nullptr)
3377 outs() << format(" %.*s", left, name);
3380 outs() << indent << "\t\t types ";
3381 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3382 info, n_value, m.types);
3384 if (info->verbose && sym_name != nullptr)
3387 outs() << format("0x%" PRIx64, n_value);
3389 outs() << " + " << format("0x%" PRIx64, m.types);
3391 outs() << format("0x%" PRIx64, m.types);
3392 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3393 if (name != nullptr)
3394 outs() << format(" %.*s", left, name);
3397 outs() << indent << "\t\t imp ";
3398 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3400 if (info->verbose && name == nullptr) {
3402 outs() << format("0x%" PRIx64, n_value) << " ";
3404 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3406 outs() << format("0x%" PRIx64, m.imp) << " ";
3408 if (name != nullptr)
3412 p += sizeof(struct method64_t);
3413 offset += sizeof(struct method64_t);
3417 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3418 const char *indent) {
3419 struct method_list32_t ml;
3420 struct method32_t m;
3421 const char *r, *name;
3422 uint32_t offset, xoffset, left, i;
3425 r = get_pointer_32(p, offset, left, S, info);
3428 memset(&ml, '\0', sizeof(struct method_list32_t));
3429 if (left < sizeof(struct method_list32_t)) {
3430 memcpy(&ml, r, left);
3431 outs() << " (method_list_t entends past the end of the section)\n";
3433 memcpy(&ml, r, sizeof(struct method_list32_t));
3434 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3436 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3437 outs() << indent << "\t\t count " << ml.count << "\n";
3439 p += sizeof(struct method_list32_t);
3440 offset += sizeof(struct method_list32_t);
3441 for (i = 0; i < ml.count; i++) {
3442 r = get_pointer_32(p, offset, left, S, info);
3445 memset(&m, '\0', sizeof(struct method32_t));
3446 if (left < sizeof(struct method32_t)) {
3447 memcpy(&ml, r, left);
3448 outs() << indent << " (method_t entends past the end of the section)\n";
3450 memcpy(&m, r, sizeof(struct method32_t));
3451 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3454 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3455 name = get_pointer_32(m.name, xoffset, left, xS, info);
3456 if (name != nullptr)
3457 outs() << format(" %.*s", left, name);
3460 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3461 name = get_pointer_32(m.types, xoffset, left, xS, info);
3462 if (name != nullptr)
3463 outs() << format(" %.*s", left, name);
3466 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3467 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3469 if (name != nullptr)
3470 outs() << " " << name;
3473 p += sizeof(struct method32_t);
3474 offset += sizeof(struct method32_t);
3478 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3479 uint32_t offset, left, xleft;
3481 struct objc_method_list_t method_list;
3482 struct objc_method_t method;
3483 const char *r, *methods, *name, *SymbolName;
3486 r = get_pointer_32(p, offset, left, S, info, true);
3491 if (left > sizeof(struct objc_method_list_t)) {
3492 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3494 outs() << "\t\t objc_method_list extends past end of the section\n";
3495 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3496 memcpy(&method_list, r, left);
3498 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3499 swapStruct(method_list);
3501 outs() << "\t\t obsolete "
3502 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3503 outs() << "\t\t method_count " << method_list.method_count << "\n";
3505 methods = r + sizeof(struct objc_method_list_t);
3506 for (i = 0; i < method_list.method_count; i++) {
3507 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3508 outs() << "\t\t remaining method's extend past the of the section\n";
3511 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3512 sizeof(struct objc_method_t));
3513 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3516 outs() << "\t\t method_name "
3517 << format("0x%08" PRIx32, method.method_name);
3518 if (info->verbose) {
3519 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3520 if (name != nullptr)
3521 outs() << format(" %.*s", xleft, name);
3523 outs() << " (not in an __OBJC section)";
3527 outs() << "\t\t method_types "
3528 << format("0x%08" PRIx32, method.method_types);
3529 if (info->verbose) {
3530 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3531 if (name != nullptr)
3532 outs() << format(" %.*s", xleft, name);
3534 outs() << " (not in an __OBJC section)";
3538 outs() << "\t\t method_imp "
3539 << format("0x%08" PRIx32, method.method_imp) << " ";
3540 if (info->verbose) {
3541 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3542 if (SymbolName != nullptr)
3543 outs() << SymbolName;
3550 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3551 struct protocol_list64_t pl;
3552 uint64_t q, n_value;
3553 struct protocol64_t pc;
3555 uint32_t offset, xoffset, left, i;
3557 const char *name, *sym_name;
3559 r = get_pointer_64(p, offset, left, S, info);
3562 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3563 if (left < sizeof(struct protocol_list64_t)) {
3564 memcpy(&pl, r, left);
3565 outs() << " (protocol_list_t entends past the end of the section)\n";
3567 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3568 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3570 outs() << " count " << pl.count << "\n";
3572 p += sizeof(struct protocol_list64_t);
3573 offset += sizeof(struct protocol_list64_t);
3574 for (i = 0; i < pl.count; i++) {
3575 r = get_pointer_64(p, offset, left, S, info);
3579 if (left < sizeof(uint64_t)) {
3580 memcpy(&q, r, left);
3581 outs() << " (protocol_t * entends past the end of the section)\n";
3583 memcpy(&q, r, sizeof(uint64_t));
3584 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3585 sys::swapByteOrder(q);
3587 outs() << "\t\t list[" << i << "] ";
3588 sym_name = get_symbol_64(offset, S, info, n_value, q);
3590 if (info->verbose && sym_name != nullptr)
3593 outs() << format("0x%" PRIx64, n_value);
3595 outs() << " + " << format("0x%" PRIx64, q);
3597 outs() << format("0x%" PRIx64, q);
3598 outs() << " (struct protocol_t *)\n";
3600 r = get_pointer_64(q + n_value, offset, left, S, info);
3603 memset(&pc, '\0', sizeof(struct protocol64_t));
3604 if (left < sizeof(struct protocol64_t)) {
3605 memcpy(&pc, r, left);
3606 outs() << " (protocol_t entends past the end of the section)\n";
3608 memcpy(&pc, r, sizeof(struct protocol64_t));
3609 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3612 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3614 outs() << "\t\t\t name ";
3615 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3616 info, n_value, pc.name);
3618 if (info->verbose && sym_name != nullptr)
3621 outs() << format("0x%" PRIx64, n_value);
3623 outs() << " + " << format("0x%" PRIx64, pc.name);
3625 outs() << format("0x%" PRIx64, pc.name);
3626 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3627 if (name != nullptr)
3628 outs() << format(" %.*s", left, name);
3631 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3633 outs() << "\t\t instanceMethods ";
3635 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3636 S, info, n_value, pc.instanceMethods);
3638 if (info->verbose && sym_name != nullptr)
3641 outs() << format("0x%" PRIx64, n_value);
3642 if (pc.instanceMethods != 0)
3643 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3645 outs() << format("0x%" PRIx64, pc.instanceMethods);
3646 outs() << " (struct method_list_t *)\n";
3647 if (pc.instanceMethods + n_value != 0)
3648 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3650 outs() << "\t\t classMethods ";
3652 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3653 info, n_value, pc.classMethods);
3655 if (info->verbose && sym_name != nullptr)
3658 outs() << format("0x%" PRIx64, n_value);
3659 if (pc.classMethods != 0)
3660 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3662 outs() << format("0x%" PRIx64, pc.classMethods);
3663 outs() << " (struct method_list_t *)\n";
3664 if (pc.classMethods + n_value != 0)
3665 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3667 outs() << "\t optionalInstanceMethods "
3668 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3669 outs() << "\t optionalClassMethods "
3670 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3671 outs() << "\t instanceProperties "
3672 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3674 p += sizeof(uint64_t);
3675 offset += sizeof(uint64_t);
3679 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3680 struct protocol_list32_t pl;
3682 struct protocol32_t pc;
3684 uint32_t offset, xoffset, left, i;
3688 r = get_pointer_32(p, offset, left, S, info);
3691 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3692 if (left < sizeof(struct protocol_list32_t)) {
3693 memcpy(&pl, r, left);
3694 outs() << " (protocol_list_t entends past the end of the section)\n";
3696 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3697 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3699 outs() << " count " << pl.count << "\n";
3701 p += sizeof(struct protocol_list32_t);
3702 offset += sizeof(struct protocol_list32_t);
3703 for (i = 0; i < pl.count; i++) {
3704 r = get_pointer_32(p, offset, left, S, info);
3708 if (left < sizeof(uint32_t)) {
3709 memcpy(&q, r, left);
3710 outs() << " (protocol_t * entends past the end of the section)\n";
3712 memcpy(&q, r, sizeof(uint32_t));
3713 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3714 sys::swapByteOrder(q);
3715 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3716 << " (struct protocol_t *)\n";
3717 r = get_pointer_32(q, offset, left, S, info);
3720 memset(&pc, '\0', sizeof(struct protocol32_t));
3721 if (left < sizeof(struct protocol32_t)) {
3722 memcpy(&pc, r, left);
3723 outs() << " (protocol_t entends past the end of the section)\n";
3725 memcpy(&pc, r, sizeof(struct protocol32_t));
3726 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3728 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3729 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3730 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3731 if (name != nullptr)
3732 outs() << format(" %.*s", left, name);
3734 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3735 outs() << "\t\t instanceMethods "
3736 << format("0x%" PRIx32, pc.instanceMethods)
3737 << " (struct method_list_t *)\n";
3738 if (pc.instanceMethods != 0)
3739 print_method_list32_t(pc.instanceMethods, info, "\t");
3740 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3741 << " (struct method_list_t *)\n";
3742 if (pc.classMethods != 0)
3743 print_method_list32_t(pc.classMethods, info, "\t");
3744 outs() << "\t optionalInstanceMethods "
3745 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3746 outs() << "\t optionalClassMethods "
3747 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3748 outs() << "\t instanceProperties "
3749 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3750 p += sizeof(uint32_t);
3751 offset += sizeof(uint32_t);
3755 static void print_indent(uint32_t indent) {
3756 for (uint32_t i = 0; i < indent;) {
3757 if (indent - i >= 8) {
3761 for (uint32_t j = i; j < indent; j++)
3768 static bool print_method_description_list(uint32_t p, uint32_t indent,
3769 struct DisassembleInfo *info) {
3770 uint32_t offset, left, xleft;
3772 struct objc_method_description_list_t mdl;
3773 struct objc_method_description_t md;
3774 const char *r, *list, *name;
3777 r = get_pointer_32(p, offset, left, S, info, true);
3782 if (left > sizeof(struct objc_method_description_list_t)) {
3783 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3785 print_indent(indent);
3786 outs() << " objc_method_description_list extends past end of the section\n";
3787 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3788 memcpy(&mdl, r, left);
3790 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3793 print_indent(indent);
3794 outs() << " count " << mdl.count << "\n";
3796 list = r + sizeof(struct objc_method_description_list_t);
3797 for (i = 0; i < mdl.count; i++) {
3798 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3799 print_indent(indent);
3800 outs() << " remaining list entries extend past the of the section\n";
3803 print_indent(indent);
3804 outs() << " list[" << i << "]\n";
3805 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3806 sizeof(struct objc_method_description_t));
3807 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3810 print_indent(indent);
3811 outs() << " name " << format("0x%08" PRIx32, md.name);
3812 if (info->verbose) {
3813 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3814 if (name != nullptr)
3815 outs() << format(" %.*s", xleft, name);
3817 outs() << " (not in an __OBJC section)";
3821 print_indent(indent);
3822 outs() << " types " << format("0x%08" PRIx32, md.types);
3823 if (info->verbose) {
3824 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3825 if (name != nullptr)
3826 outs() << format(" %.*s", xleft, name);
3828 outs() << " (not in an __OBJC section)";
3835 static bool print_protocol_list(uint32_t p, uint32_t indent,
3836 struct DisassembleInfo *info);
3838 static bool print_protocol(uint32_t p, uint32_t indent,
3839 struct DisassembleInfo *info) {
3840 uint32_t offset, left;
3842 struct objc_protocol_t protocol;
3843 const char *r, *name;
3845 r = get_pointer_32(p, offset, left, S, info, true);
3850 if (left >= sizeof(struct objc_protocol_t)) {
3851 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3853 print_indent(indent);
3854 outs() << " Protocol extends past end of the section\n";
3855 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3856 memcpy(&protocol, r, left);
3858 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3859 swapStruct(protocol);
3861 print_indent(indent);
3862 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3865 print_indent(indent);
3866 outs() << " protocol_name "
3867 << format("0x%08" PRIx32, protocol.protocol_name);
3868 if (info->verbose) {
3869 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3870 if (name != nullptr)
3871 outs() << format(" %.*s", left, name);
3873 outs() << " (not in an __OBJC section)";
3877 print_indent(indent);
3878 outs() << " protocol_list "
3879 << format("0x%08" PRIx32, protocol.protocol_list);
3880 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3881 outs() << " (not in an __OBJC section)\n";
3883 print_indent(indent);
3884 outs() << " instance_methods "
3885 << format("0x%08" PRIx32, protocol.instance_methods);
3886 if (print_method_description_list(protocol.instance_methods, indent, info))
3887 outs() << " (not in an __OBJC section)\n";
3889 print_indent(indent);
3890 outs() << " class_methods "
3891 << format("0x%08" PRIx32, protocol.class_methods);
3892 if (print_method_description_list(protocol.class_methods, indent, info))
3893 outs() << " (not in an __OBJC section)\n";
3898 static bool print_protocol_list(uint32_t p, uint32_t indent,
3899 struct DisassembleInfo *info) {
3900 uint32_t offset, left, l;
3902 struct objc_protocol_list_t protocol_list;
3903 const char *r, *list;
3906 r = get_pointer_32(p, offset, left, S, info, true);
3911 if (left > sizeof(struct objc_protocol_list_t)) {
3912 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3914 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3915 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3916 memcpy(&protocol_list, r, left);
3918 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3919 swapStruct(protocol_list);
3921 print_indent(indent);
3922 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3924 print_indent(indent);
3925 outs() << " count " << protocol_list.count << "\n";
3927 list = r + sizeof(struct objc_protocol_list_t);
3928 for (i = 0; i < protocol_list.count; i++) {
3929 if ((i + 1) * sizeof(uint32_t) > left) {
3930 outs() << "\t\t remaining list entries extend past the of the section\n";
3933 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3934 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3935 sys::swapByteOrder(l);
3937 print_indent(indent);
3938 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3939 if (print_protocol(l, indent, info))
3940 outs() << "(not in an __OBJC section)\n";
3945 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3946 struct ivar_list64_t il;
3949 uint32_t offset, xoffset, left, j;
3951 const char *name, *sym_name, *ivar_offset_p;
3952 uint64_t ivar_offset, n_value;
3954 r = get_pointer_64(p, offset, left, S, info);
3957 memset(&il, '\0', sizeof(struct ivar_list64_t));
3958 if (left < sizeof(struct ivar_list64_t)) {
3959 memcpy(&il, r, left);
3960 outs() << " (ivar_list_t entends past the end of the section)\n";
3962 memcpy(&il, r, sizeof(struct ivar_list64_t));
3963 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3965 outs() << " entsize " << il.entsize << "\n";
3966 outs() << " count " << il.count << "\n";
3968 p += sizeof(struct ivar_list64_t);
3969 offset += sizeof(struct ivar_list64_t);
3970 for (j = 0; j < il.count; j++) {
3971 r = get_pointer_64(p, offset, left, S, info);
3974 memset(&i, '\0', sizeof(struct ivar64_t));
3975 if (left < sizeof(struct ivar64_t)) {
3976 memcpy(&i, r, left);
3977 outs() << " (ivar_t entends past the end of the section)\n";
3979 memcpy(&i, r, sizeof(struct ivar64_t));
3980 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3983 outs() << "\t\t\t offset ";
3984 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3985 info, n_value, i.offset);
3987 if (info->verbose && sym_name != nullptr)
3990 outs() << format("0x%" PRIx64, n_value);
3992 outs() << " + " << format("0x%" PRIx64, i.offset);
3994 outs() << format("0x%" PRIx64, i.offset);
3995 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3996 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3997 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3998 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3999 sys::swapByteOrder(ivar_offset);
4000 outs() << " " << ivar_offset << "\n";
4004 outs() << "\t\t\t name ";
4005 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4008 if (info->verbose && sym_name != nullptr)
4011 outs() << format("0x%" PRIx64, n_value);
4013 outs() << " + " << format("0x%" PRIx64, i.name);
4015 outs() << format("0x%" PRIx64, i.name);
4016 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4017 if (name != nullptr)
4018 outs() << format(" %.*s", left, name);
4021 outs() << "\t\t\t type ";
4022 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4024 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4026 if (info->verbose && sym_name != nullptr)
4029 outs() << format("0x%" PRIx64, n_value);
4031 outs() << " + " << format("0x%" PRIx64, i.type);
4033 outs() << format("0x%" PRIx64, i.type);
4034 if (name != nullptr)
4035 outs() << format(" %.*s", left, name);
4038 outs() << "\t\t\talignment " << i.alignment << "\n";
4039 outs() << "\t\t\t size " << i.size << "\n";
4041 p += sizeof(struct ivar64_t);
4042 offset += sizeof(struct ivar64_t);
4046 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4047 struct ivar_list32_t il;
4050 uint32_t offset, xoffset, left, j;
4052 const char *name, *ivar_offset_p;
4053 uint32_t ivar_offset;
4055 r = get_pointer_32(p, offset, left, S, info);
4058 memset(&il, '\0', sizeof(struct ivar_list32_t));
4059 if (left < sizeof(struct ivar_list32_t)) {
4060 memcpy(&il, r, left);
4061 outs() << " (ivar_list_t entends past the end of the section)\n";
4063 memcpy(&il, r, sizeof(struct ivar_list32_t));
4064 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4066 outs() << " entsize " << il.entsize << "\n";
4067 outs() << " count " << il.count << "\n";
4069 p += sizeof(struct ivar_list32_t);
4070 offset += sizeof(struct ivar_list32_t);
4071 for (j = 0; j < il.count; j++) {
4072 r = get_pointer_32(p, offset, left, S, info);
4075 memset(&i, '\0', sizeof(struct ivar32_t));
4076 if (left < sizeof(struct ivar32_t)) {
4077 memcpy(&i, r, left);
4078 outs() << " (ivar_t entends past the end of the section)\n";
4080 memcpy(&i, r, sizeof(struct ivar32_t));
4081 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4084 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4085 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4086 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4087 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4088 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4089 sys::swapByteOrder(ivar_offset);
4090 outs() << " " << ivar_offset << "\n";
4094 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4095 name = get_pointer_32(i.name, xoffset, left, xS, info);
4096 if (name != nullptr)
4097 outs() << format(" %.*s", left, name);
4100 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4101 name = get_pointer_32(i.type, xoffset, left, xS, info);
4102 if (name != nullptr)
4103 outs() << format(" %.*s", left, name);
4106 outs() << "\t\t\talignment " << i.alignment << "\n";
4107 outs() << "\t\t\t size " << i.size << "\n";
4109 p += sizeof(struct ivar32_t);
4110 offset += sizeof(struct ivar32_t);
4114 static void print_objc_property_list64(uint64_t p,
4115 struct DisassembleInfo *info) {
4116 struct objc_property_list64 opl;
4117 struct objc_property64 op;
4119 uint32_t offset, xoffset, left, j;
4121 const char *name, *sym_name;
4124 r = get_pointer_64(p, offset, left, S, info);
4127 memset(&opl, '\0', sizeof(struct objc_property_list64));
4128 if (left < sizeof(struct objc_property_list64)) {
4129 memcpy(&opl, r, left);
4130 outs() << " (objc_property_list entends past the end of the section)\n";
4132 memcpy(&opl, r, sizeof(struct objc_property_list64));
4133 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4135 outs() << " entsize " << opl.entsize << "\n";
4136 outs() << " count " << opl.count << "\n";
4138 p += sizeof(struct objc_property_list64);
4139 offset += sizeof(struct objc_property_list64);
4140 for (j = 0; j < opl.count; j++) {
4141 r = get_pointer_64(p, offset, left, S, info);
4144 memset(&op, '\0', sizeof(struct objc_property64));
4145 if (left < sizeof(struct objc_property64)) {
4146 memcpy(&op, r, left);
4147 outs() << " (objc_property entends past the end of the section)\n";
4149 memcpy(&op, r, sizeof(struct objc_property64));
4150 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4153 outs() << "\t\t\t name ";
4154 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4155 info, n_value, op.name);
4157 if (info->verbose && sym_name != nullptr)
4160 outs() << format("0x%" PRIx64, n_value);
4162 outs() << " + " << format("0x%" PRIx64, op.name);
4164 outs() << format("0x%" PRIx64, op.name);
4165 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4166 if (name != nullptr)
4167 outs() << format(" %.*s", left, name);
4170 outs() << "\t\t\tattributes ";
4172 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4173 info, n_value, op.attributes);
4175 if (info->verbose && sym_name != nullptr)
4178 outs() << format("0x%" PRIx64, n_value);
4179 if (op.attributes != 0)
4180 outs() << " + " << format("0x%" PRIx64, op.attributes);
4182 outs() << format("0x%" PRIx64, op.attributes);
4183 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4184 if (name != nullptr)
4185 outs() << format(" %.*s", left, name);
4188 p += sizeof(struct objc_property64);
4189 offset += sizeof(struct objc_property64);
4193 static void print_objc_property_list32(uint32_t p,
4194 struct DisassembleInfo *info) {
4195 struct objc_property_list32 opl;
4196 struct objc_property32 op;
4198 uint32_t offset, xoffset, left, j;
4202 r = get_pointer_32(p, offset, left, S, info);
4205 memset(&opl, '\0', sizeof(struct objc_property_list32));
4206 if (left < sizeof(struct objc_property_list32)) {
4207 memcpy(&opl, r, left);
4208 outs() << " (objc_property_list entends past the end of the section)\n";
4210 memcpy(&opl, r, sizeof(struct objc_property_list32));
4211 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4213 outs() << " entsize " << opl.entsize << "\n";
4214 outs() << " count " << opl.count << "\n";
4216 p += sizeof(struct objc_property_list32);
4217 offset += sizeof(struct objc_property_list32);
4218 for (j = 0; j < opl.count; j++) {
4219 r = get_pointer_32(p, offset, left, S, info);
4222 memset(&op, '\0', sizeof(struct objc_property32));
4223 if (left < sizeof(struct objc_property32)) {
4224 memcpy(&op, r, left);
4225 outs() << " (objc_property entends past the end of the section)\n";
4227 memcpy(&op, r, sizeof(struct objc_property32));
4228 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4231 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4232 name = get_pointer_32(op.name, xoffset, left, xS, info);
4233 if (name != nullptr)
4234 outs() << format(" %.*s", left, name);
4237 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4238 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4239 if (name != nullptr)
4240 outs() << format(" %.*s", left, name);
4243 p += sizeof(struct objc_property32);
4244 offset += sizeof(struct objc_property32);
4248 static void print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
4249 bool &is_meta_class) {
4250 struct class_ro64_t cro;
4252 uint32_t offset, xoffset, left;
4254 const char *name, *sym_name;
4257 r = get_pointer_64(p, offset, left, S, info);
4258 if (r == nullptr || left < sizeof(struct class_ro64_t))
4260 memset(&cro, '\0', sizeof(struct class_ro64_t));
4261 if (left < sizeof(struct class_ro64_t)) {
4262 memcpy(&cro, r, left);
4263 outs() << " (class_ro_t entends past the end of the section)\n";
4265 memcpy(&cro, r, sizeof(struct class_ro64_t));
4266 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4268 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4269 if (cro.flags & RO_META)
4270 outs() << " RO_META";
4271 if (cro.flags & RO_ROOT)
4272 outs() << " RO_ROOT";
4273 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4274 outs() << " RO_HAS_CXX_STRUCTORS";
4276 outs() << " instanceStart " << cro.instanceStart << "\n";
4277 outs() << " instanceSize " << cro.instanceSize << "\n";
4278 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4280 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4282 print_layout_map64(cro.ivarLayout, info);
4285 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4286 info, n_value, cro.name);
4288 if (info->verbose && sym_name != nullptr)
4291 outs() << format("0x%" PRIx64, n_value);
4293 outs() << " + " << format("0x%" PRIx64, cro.name);
4295 outs() << format("0x%" PRIx64, cro.name);
4296 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4297 if (name != nullptr)
4298 outs() << format(" %.*s", left, name);
4301 outs() << " baseMethods ";
4302 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4303 S, info, n_value, cro.baseMethods);
4305 if (info->verbose && sym_name != nullptr)
4308 outs() << format("0x%" PRIx64, n_value);
4309 if (cro.baseMethods != 0)
4310 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4312 outs() << format("0x%" PRIx64, cro.baseMethods);
4313 outs() << " (struct method_list_t *)\n";
4314 if (cro.baseMethods + n_value != 0)
4315 print_method_list64_t(cro.baseMethods + n_value, info, "");
4317 outs() << " baseProtocols ";
4319 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4320 info, n_value, cro.baseProtocols);
4322 if (info->verbose && sym_name != nullptr)
4325 outs() << format("0x%" PRIx64, n_value);
4326 if (cro.baseProtocols != 0)
4327 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4329 outs() << format("0x%" PRIx64, cro.baseProtocols);
4331 if (cro.baseProtocols + n_value != 0)
4332 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4334 outs() << " ivars ";
4335 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
4336 info, n_value, cro.ivars);
4338 if (info->verbose && sym_name != nullptr)
4341 outs() << format("0x%" PRIx64, n_value);
4343 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4345 outs() << format("0x%" PRIx64, cro.ivars);
4347 if (cro.ivars + n_value != 0)
4348 print_ivar_list64_t(cro.ivars + n_value, info);
4350 outs() << " weakIvarLayout ";
4352 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4353 info, n_value, cro.weakIvarLayout);
4355 if (info->verbose && sym_name != nullptr)
4358 outs() << format("0x%" PRIx64, n_value);
4359 if (cro.weakIvarLayout != 0)
4360 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4362 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4364 print_layout_map64(cro.weakIvarLayout + n_value, info);
4366 outs() << " baseProperties ";
4368 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4369 info, n_value, cro.baseProperties);
4371 if (info->verbose && sym_name != nullptr)
4374 outs() << format("0x%" PRIx64, n_value);
4375 if (cro.baseProperties != 0)
4376 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4378 outs() << format("0x%" PRIx64, cro.baseProperties);
4380 if (cro.baseProperties + n_value != 0)
4381 print_objc_property_list64(cro.baseProperties + n_value, info);
4383 is_meta_class = (cro.flags & RO_META) ? true : false;
4386 static void print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
4387 bool &is_meta_class) {
4388 struct class_ro32_t cro;
4390 uint32_t offset, xoffset, left;
4394 r = get_pointer_32(p, offset, left, S, info);
4397 memset(&cro, '\0', sizeof(struct class_ro32_t));
4398 if (left < sizeof(struct class_ro32_t)) {
4399 memcpy(&cro, r, left);
4400 outs() << " (class_ro_t entends past the end of the section)\n";
4402 memcpy(&cro, r, sizeof(struct class_ro32_t));
4403 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4405 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4406 if (cro.flags & RO_META)
4407 outs() << " RO_META";
4408 if (cro.flags & RO_ROOT)
4409 outs() << " RO_ROOT";
4410 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4411 outs() << " RO_HAS_CXX_STRUCTORS";
4413 outs() << " instanceStart " << cro.instanceStart << "\n";
4414 outs() << " instanceSize " << cro.instanceSize << "\n";
4415 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4417 print_layout_map32(cro.ivarLayout, info);
4419 outs() << " name " << format("0x%" PRIx32, cro.name);
4420 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4421 if (name != nullptr)
4422 outs() << format(" %.*s", left, name);
4425 outs() << " baseMethods "
4426 << format("0x%" PRIx32, cro.baseMethods)
4427 << " (struct method_list_t *)\n";
4428 if (cro.baseMethods != 0)
4429 print_method_list32_t(cro.baseMethods, info, "");
4431 outs() << " baseProtocols "
4432 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4433 if (cro.baseProtocols != 0)
4434 print_protocol_list32_t(cro.baseProtocols, info);
4435 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4438 print_ivar_list32_t(cro.ivars, info);
4439 outs() << " weakIvarLayout "
4440 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4441 print_layout_map32(cro.weakIvarLayout, info);
4442 outs() << " baseProperties "
4443 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4444 if (cro.baseProperties != 0)
4445 print_objc_property_list32(cro.baseProperties, info);
4446 is_meta_class = (cro.flags & RO_META) ? true : false;
4449 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4452 uint32_t offset, left;
4455 uint64_t isa_n_value, n_value;
4457 r = get_pointer_64(p, offset, left, S, info);
4458 if (r == nullptr || left < sizeof(struct class64_t))
4460 memset(&c, '\0', sizeof(struct class64_t));
4461 if (left < sizeof(struct class64_t)) {
4462 memcpy(&c, r, left);
4463 outs() << " (class_t entends past the end of the section)\n";
4465 memcpy(&c, r, sizeof(struct class64_t));
4466 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4469 outs() << " isa " << format("0x%" PRIx64, c.isa);
4470 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4471 isa_n_value, c.isa);
4472 if (name != nullptr)
4473 outs() << " " << name;
4476 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4477 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4478 n_value, c.superclass);
4479 if (name != nullptr)
4480 outs() << " " << name;
4483 outs() << " cache " << format("0x%" PRIx64, c.cache);
4484 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4486 if (name != nullptr)
4487 outs() << " " << name;
4490 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4491 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4493 if (name != nullptr)
4494 outs() << " " << name;
4497 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4501 if (info->verbose && name != nullptr)
4504 outs() << format("0x%" PRIx64, n_value);
4506 outs() << " + " << format("0x%" PRIx64, c.data);
4508 outs() << format("0x%" PRIx64, c.data);
4509 outs() << " (struct class_ro_t *)";
4511 // This is a Swift class if some of the low bits of the pointer are set.
4512 if ((c.data + n_value) & 0x7)
4513 outs() << " Swift class";
4516 print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class);
4518 if (is_meta_class == false) {
4519 outs() << "Meta Class\n";
4520 print_class64_t(c.isa + isa_n_value, info);
4524 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4527 uint32_t offset, left;
4531 r = get_pointer_32(p, offset, left, S, info);
4534 memset(&c, '\0', sizeof(struct class32_t));
4535 if (left < sizeof(struct class32_t)) {
4536 memcpy(&c, r, left);
4537 outs() << " (class_t entends past the end of the section)\n";
4539 memcpy(&c, r, sizeof(struct class32_t));
4540 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4543 outs() << " isa " << format("0x%" PRIx32, c.isa);
4545 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4546 if (name != nullptr)
4547 outs() << " " << name;
4550 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4551 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4553 if (name != nullptr)
4554 outs() << " " << name;
4557 outs() << " cache " << format("0x%" PRIx32, c.cache);
4558 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4560 if (name != nullptr)
4561 outs() << " " << name;
4564 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4565 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4567 if (name != nullptr)
4568 outs() << " " << name;
4572 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4573 outs() << " data " << format("0x%" PRIx32, c.data)
4574 << " (struct class_ro_t *)";
4576 // This is a Swift class if some of the low bits of the pointer are set.
4578 outs() << " Swift class";
4581 print_class_ro32_t(c.data & ~0x3, info, is_meta_class);
4583 if (is_meta_class == false) {
4584 outs() << "Meta Class\n";
4585 print_class32_t(c.isa, info);
4589 static void print_objc_class_t(struct objc_class_t *objc_class,
4590 struct DisassembleInfo *info) {
4591 uint32_t offset, left, xleft;
4592 const char *name, *p, *ivar_list;
4595 struct objc_ivar_list_t objc_ivar_list;
4596 struct objc_ivar_t ivar;
4598 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4599 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4600 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4601 if (name != nullptr)
4602 outs() << format(" %.*s", left, name);
4604 outs() << " (not in an __OBJC section)";
4608 outs() << "\t super_class "
4609 << format("0x%08" PRIx32, objc_class->super_class);
4610 if (info->verbose) {
4611 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4612 if (name != nullptr)
4613 outs() << format(" %.*s", left, name);
4615 outs() << " (not in an __OBJC section)";
4619 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4620 if (info->verbose) {
4621 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4622 if (name != nullptr)
4623 outs() << format(" %.*s", left, name);
4625 outs() << " (not in an __OBJC section)";
4629 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4632 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4633 if (info->verbose) {
4634 if (CLS_GETINFO(objc_class, CLS_CLASS))
4635 outs() << " CLS_CLASS";
4636 else if (CLS_GETINFO(objc_class, CLS_META))
4637 outs() << " CLS_META";
4641 outs() << "\t instance_size "
4642 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4644 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4645 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4647 if (left > sizeof(struct objc_ivar_list_t)) {
4649 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4651 outs() << " (entends past the end of the section)\n";
4652 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4653 memcpy(&objc_ivar_list, p, left);
4655 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4656 swapStruct(objc_ivar_list);
4657 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4658 ivar_list = p + sizeof(struct objc_ivar_list_t);
4659 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4660 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4661 outs() << "\t\t remaining ivar's extend past the of the section\n";
4664 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4665 sizeof(struct objc_ivar_t));
4666 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4669 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4670 if (info->verbose) {
4671 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4672 if (name != nullptr)
4673 outs() << format(" %.*s", xleft, name);
4675 outs() << " (not in an __OBJC section)";
4679 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4680 if (info->verbose) {
4681 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4682 if (name != nullptr)
4683 outs() << format(" %.*s", xleft, name);
4685 outs() << " (not in an __OBJC section)";
4689 outs() << "\t\t ivar_offset "
4690 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4693 outs() << " (not in an __OBJC section)\n";
4696 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4697 if (print_method_list(objc_class->methodLists, info))
4698 outs() << " (not in an __OBJC section)\n";
4700 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4703 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4704 if (print_protocol_list(objc_class->protocols, 16, info))
4705 outs() << " (not in an __OBJC section)\n";
4708 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4709 struct DisassembleInfo *info) {
4710 uint32_t offset, left;
4714 outs() << "\t category name "
4715 << format("0x%08" PRIx32, objc_category->category_name);
4716 if (info->verbose) {
4717 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4719 if (name != nullptr)
4720 outs() << format(" %.*s", left, name);
4722 outs() << " (not in an __OBJC section)";
4726 outs() << "\t\t class name "
4727 << format("0x%08" PRIx32, objc_category->class_name);
4728 if (info->verbose) {
4730 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4731 if (name != nullptr)
4732 outs() << format(" %.*s", left, name);
4734 outs() << " (not in an __OBJC section)";
4738 outs() << "\t instance methods "
4739 << format("0x%08" PRIx32, objc_category->instance_methods);
4740 if (print_method_list(objc_category->instance_methods, info))
4741 outs() << " (not in an __OBJC section)\n";
4743 outs() << "\t class methods "
4744 << format("0x%08" PRIx32, objc_category->class_methods);
4745 if (print_method_list(objc_category->class_methods, info))
4746 outs() << " (not in an __OBJC section)\n";
4749 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4750 struct category64_t c;
4752 uint32_t offset, xoffset, left;
4754 const char *name, *sym_name;
4757 r = get_pointer_64(p, offset, left, S, info);
4760 memset(&c, '\0', sizeof(struct category64_t));
4761 if (left < sizeof(struct category64_t)) {
4762 memcpy(&c, r, left);
4763 outs() << " (category_t entends past the end of the section)\n";
4765 memcpy(&c, r, sizeof(struct category64_t));
4766 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4770 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4771 info, n_value, c.name);
4773 if (info->verbose && sym_name != nullptr)
4776 outs() << format("0x%" PRIx64, n_value);
4778 outs() << " + " << format("0x%" PRIx64, c.name);
4780 outs() << format("0x%" PRIx64, c.name);
4781 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4782 if (name != nullptr)
4783 outs() << format(" %.*s", left, name);
4787 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4790 if (info->verbose && sym_name != nullptr)
4793 outs() << format("0x%" PRIx64, n_value);
4795 outs() << " + " << format("0x%" PRIx64, c.cls);
4797 outs() << format("0x%" PRIx64, c.cls);
4799 if (c.cls + n_value != 0)
4800 print_class64_t(c.cls + n_value, info);
4802 outs() << " instanceMethods ";
4804 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4805 info, n_value, c.instanceMethods);
4807 if (info->verbose && sym_name != nullptr)
4810 outs() << format("0x%" PRIx64, n_value);
4811 if (c.instanceMethods != 0)
4812 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4814 outs() << format("0x%" PRIx64, c.instanceMethods);
4816 if (c.instanceMethods + n_value != 0)
4817 print_method_list64_t(c.instanceMethods + n_value, info, "");
4819 outs() << " classMethods ";
4820 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4821 S, info, n_value, c.classMethods);
4823 if (info->verbose && sym_name != nullptr)
4826 outs() << format("0x%" PRIx64, n_value);
4827 if (c.classMethods != 0)
4828 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4830 outs() << format("0x%" PRIx64, c.classMethods);
4832 if (c.classMethods + n_value != 0)
4833 print_method_list64_t(c.classMethods + n_value, info, "");
4835 outs() << " protocols ";
4836 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4837 info, n_value, c.protocols);
4839 if (info->verbose && sym_name != nullptr)
4842 outs() << format("0x%" PRIx64, n_value);
4843 if (c.protocols != 0)
4844 outs() << " + " << format("0x%" PRIx64, c.protocols);
4846 outs() << format("0x%" PRIx64, c.protocols);
4848 if (c.protocols + n_value != 0)
4849 print_protocol_list64_t(c.protocols + n_value, info);
4851 outs() << "instanceProperties ";
4853 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4854 S, info, n_value, c.instanceProperties);
4856 if (info->verbose && sym_name != nullptr)
4859 outs() << format("0x%" PRIx64, n_value);
4860 if (c.instanceProperties != 0)
4861 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4863 outs() << format("0x%" PRIx64, c.instanceProperties);
4865 if (c.instanceProperties + n_value != 0)
4866 print_objc_property_list64(c.instanceProperties + n_value, info);
4869 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4870 struct category32_t c;
4872 uint32_t offset, left;
4876 r = get_pointer_32(p, offset, left, S, info);
4879 memset(&c, '\0', sizeof(struct category32_t));
4880 if (left < sizeof(struct category32_t)) {
4881 memcpy(&c, r, left);
4882 outs() << " (category_t entends past the end of the section)\n";
4884 memcpy(&c, r, sizeof(struct category32_t));
4885 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4888 outs() << " name " << format("0x%" PRIx32, c.name);
4889 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4892 outs() << " " << name;
4895 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4897 print_class32_t(c.cls, info);
4898 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4900 if (c.instanceMethods != 0)
4901 print_method_list32_t(c.instanceMethods, info, "");
4902 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4904 if (c.classMethods != 0)
4905 print_method_list32_t(c.classMethods, info, "");
4906 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4907 if (c.protocols != 0)
4908 print_protocol_list32_t(c.protocols, info);
4909 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4911 if (c.instanceProperties != 0)
4912 print_objc_property_list32(c.instanceProperties, info);
4915 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4916 uint32_t i, left, offset, xoffset;
4917 uint64_t p, n_value;
4918 struct message_ref64 mr;
4919 const char *name, *sym_name;
4923 if (S == SectionRef())
4927 S.getName(SectName);
4928 DataRefImpl Ref = S.getRawDataRefImpl();
4929 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4930 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4932 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4933 p = S.getAddress() + i;
4934 r = get_pointer_64(p, offset, left, S, info);
4937 memset(&mr, '\0', sizeof(struct message_ref64));
4938 if (left < sizeof(struct message_ref64)) {
4939 memcpy(&mr, r, left);
4940 outs() << " (message_ref entends past the end of the section)\n";
4942 memcpy(&mr, r, sizeof(struct message_ref64));
4943 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4947 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4950 outs() << format("0x%" PRIx64, n_value) << " ";
4952 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4954 outs() << format("0x%" PRIx64, mr.imp) << " ";
4955 if (name != nullptr)
4956 outs() << " " << name;
4960 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4961 info, n_value, mr.sel);
4963 if (info->verbose && sym_name != nullptr)
4966 outs() << format("0x%" PRIx64, n_value);
4968 outs() << " + " << format("0x%" PRIx64, mr.sel);
4970 outs() << format("0x%" PRIx64, mr.sel);
4971 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4972 if (name != nullptr)
4973 outs() << format(" %.*s", left, name);
4976 offset += sizeof(struct message_ref64);
4980 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
4981 uint32_t i, left, offset, xoffset, p;
4982 struct message_ref32 mr;
4983 const char *name, *r;
4986 if (S == SectionRef())
4990 S.getName(SectName);
4991 DataRefImpl Ref = S.getRawDataRefImpl();
4992 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4993 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4995 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4996 p = S.getAddress() + i;
4997 r = get_pointer_32(p, offset, left, S, info);
5000 memset(&mr, '\0', sizeof(struct message_ref32));
5001 if (left < sizeof(struct message_ref32)) {
5002 memcpy(&mr, r, left);
5003 outs() << " (message_ref entends past the end of the section)\n";
5005 memcpy(&mr, r, sizeof(struct message_ref32));
5006 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5009 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5010 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5012 if (name != nullptr)
5013 outs() << " " << name;
5016 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5017 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5018 if (name != nullptr)
5019 outs() << " " << name;
5022 offset += sizeof(struct message_ref32);
5026 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5027 uint32_t left, offset, swift_version;
5029 struct objc_image_info64 o;
5033 S.getName(SectName);
5034 DataRefImpl Ref = S.getRawDataRefImpl();
5035 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5036 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5038 r = get_pointer_64(p, offset, left, S, info);
5041 memset(&o, '\0', sizeof(struct objc_image_info64));
5042 if (left < sizeof(struct objc_image_info64)) {
5043 memcpy(&o, r, left);
5044 outs() << " (objc_image_info entends past the end of the section)\n";
5046 memcpy(&o, r, sizeof(struct objc_image_info64));
5047 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5049 outs() << " version " << o.version << "\n";
5050 outs() << " flags " << format("0x%" PRIx32, o.flags);
5051 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5052 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5053 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5054 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5055 swift_version = (o.flags >> 8) & 0xff;
5056 if (swift_version != 0) {
5057 if (swift_version == 1)
5058 outs() << " Swift 1.0";
5059 else if (swift_version == 2)
5060 outs() << " Swift 1.1";
5062 outs() << " unknown future Swift version (" << swift_version << ")";
5067 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5068 uint32_t left, offset, swift_version, p;
5069 struct objc_image_info32 o;
5073 S.getName(SectName);
5074 DataRefImpl Ref = S.getRawDataRefImpl();
5075 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5076 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5078 r = get_pointer_32(p, offset, left, S, info);
5081 memset(&o, '\0', sizeof(struct objc_image_info32));
5082 if (left < sizeof(struct objc_image_info32)) {
5083 memcpy(&o, r, left);
5084 outs() << " (objc_image_info entends past the end of the section)\n";
5086 memcpy(&o, r, sizeof(struct objc_image_info32));
5087 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5089 outs() << " version " << o.version << "\n";
5090 outs() << " flags " << format("0x%" PRIx32, o.flags);
5091 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5092 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5093 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5094 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5095 swift_version = (o.flags >> 8) & 0xff;
5096 if (swift_version != 0) {
5097 if (swift_version == 1)
5098 outs() << " Swift 1.0";
5099 else if (swift_version == 2)
5100 outs() << " Swift 1.1";
5102 outs() << " unknown future Swift version (" << swift_version << ")";
5107 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5108 uint32_t left, offset, p;
5109 struct imageInfo_t o;
5113 S.getName(SectName);
5114 DataRefImpl Ref = S.getRawDataRefImpl();
5115 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5116 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5118 r = get_pointer_32(p, offset, left, S, info);
5121 memset(&o, '\0', sizeof(struct imageInfo_t));
5122 if (left < sizeof(struct imageInfo_t)) {
5123 memcpy(&o, r, left);
5124 outs() << " (imageInfo entends past the end of the section)\n";
5126 memcpy(&o, r, sizeof(struct imageInfo_t));
5127 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5129 outs() << " version " << o.version << "\n";
5130 outs() << " flags " << format("0x%" PRIx32, o.flags);
5136 outs() << " GC-only";
5142 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5143 SymbolAddressMap AddrMap;
5145 CreateSymbolAddressMap(O, &AddrMap);
5147 std::vector<SectionRef> Sections;
5148 for (const SectionRef &Section : O->sections()) {
5150 Section.getName(SectName);
5151 Sections.push_back(Section);
5154 struct DisassembleInfo info;
5155 // Set up the block of info used by the Symbolizer call backs.
5156 info.verbose = verbose;
5158 info.AddrMap = &AddrMap;
5159 info.Sections = &Sections;
5160 info.class_name = nullptr;
5161 info.selector_name = nullptr;
5162 info.method = nullptr;
5163 info.demangled_name = nullptr;
5164 info.bindtable = nullptr;
5168 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5169 if (CL != SectionRef()) {
5171 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5173 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5175 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5178 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5179 if (CR != SectionRef()) {
5181 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5183 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5185 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5188 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5189 if (SR != SectionRef()) {
5191 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5193 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5195 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5198 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5199 if (CA != SectionRef()) {
5201 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5203 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5205 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5208 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5209 if (PL != SectionRef()) {
5211 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5213 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5215 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5218 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5219 if (MR != SectionRef()) {
5221 print_message_refs64(MR, &info);
5223 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5225 print_message_refs64(MR, &info);
5228 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5229 if (II != SectionRef()) {
5231 print_image_info64(II, &info);
5233 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5235 print_image_info64(II, &info);
5238 if (info.bindtable != nullptr)
5239 delete info.bindtable;
5242 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5243 SymbolAddressMap AddrMap;
5245 CreateSymbolAddressMap(O, &AddrMap);
5247 std::vector<SectionRef> Sections;
5248 for (const SectionRef &Section : O->sections()) {
5250 Section.getName(SectName);
5251 Sections.push_back(Section);
5254 struct DisassembleInfo info;
5255 // Set up the block of info used by the Symbolizer call backs.
5256 info.verbose = verbose;
5258 info.AddrMap = &AddrMap;
5259 info.Sections = &Sections;
5260 info.class_name = nullptr;
5261 info.selector_name = nullptr;
5262 info.method = nullptr;
5263 info.demangled_name = nullptr;
5264 info.bindtable = nullptr;
5268 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5269 if (CL != SectionRef()) {
5271 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5273 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5275 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5278 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5279 if (CR != SectionRef()) {
5281 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5283 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5285 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5288 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5289 if (SR != SectionRef()) {
5291 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5293 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5295 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5298 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5299 if (CA != SectionRef()) {
5301 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5303 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5305 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5308 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5309 if (PL != SectionRef()) {
5311 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5313 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5315 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5318 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5319 if (MR != SectionRef()) {
5321 print_message_refs32(MR, &info);
5323 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5325 print_message_refs32(MR, &info);
5328 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5329 if (II != SectionRef()) {
5331 print_image_info32(II, &info);
5333 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5335 print_image_info32(II, &info);
5339 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5340 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5341 const char *r, *name, *defs;
5342 struct objc_module_t module;
5344 struct objc_symtab_t symtab;
5345 struct objc_class_t objc_class;
5346 struct objc_category_t objc_category;
5348 outs() << "Objective-C segment\n";
5349 S = get_section(O, "__OBJC", "__module_info");
5350 if (S == SectionRef())
5353 SymbolAddressMap AddrMap;
5355 CreateSymbolAddressMap(O, &AddrMap);
5357 std::vector<SectionRef> Sections;
5358 for (const SectionRef &Section : O->sections()) {
5360 Section.getName(SectName);
5361 Sections.push_back(Section);
5364 struct DisassembleInfo info;
5365 // Set up the block of info used by the Symbolizer call backs.
5366 info.verbose = verbose;
5368 info.AddrMap = &AddrMap;
5369 info.Sections = &Sections;
5370 info.class_name = nullptr;
5371 info.selector_name = nullptr;
5372 info.method = nullptr;
5373 info.demangled_name = nullptr;
5374 info.bindtable = nullptr;
5378 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5379 p = S.getAddress() + i;
5380 r = get_pointer_32(p, offset, left, S, &info, true);
5383 memset(&module, '\0', sizeof(struct objc_module_t));
5384 if (left < sizeof(struct objc_module_t)) {
5385 memcpy(&module, r, left);
5386 outs() << " (module extends past end of __module_info section)\n";
5388 memcpy(&module, r, sizeof(struct objc_module_t));
5389 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5392 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5393 outs() << " version " << module.version << "\n";
5394 outs() << " size " << module.size << "\n";
5396 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5397 if (name != nullptr)
5398 outs() << format("%.*s", left, name);
5400 outs() << format("0x%08" PRIx32, module.name)
5401 << "(not in an __OBJC section)";
5404 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5405 if (module.symtab == 0 || r == nullptr) {
5406 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5407 << " (not in an __OBJC section)\n";
5410 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5411 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5414 if (left < sizeof(struct objc_symtab_t)) {
5415 memcpy(&symtab, r, left);
5416 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5418 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5419 if (left > sizeof(struct objc_symtab_t)) {
5420 defs_left = left - sizeof(struct objc_symtab_t);
5421 defs = r + sizeof(struct objc_symtab_t);
5424 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5427 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5428 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5429 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5431 outs() << " (not in an __OBJC section)";
5433 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5434 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5435 if (symtab.cls_def_cnt > 0)
5436 outs() << "\tClass Definitions\n";
5437 for (j = 0; j < symtab.cls_def_cnt; j++) {
5438 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5439 outs() << "\t(remaining class defs entries entends past the end of the "
5443 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5444 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5445 sys::swapByteOrder(def);
5447 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5448 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5450 if (left > sizeof(struct objc_class_t)) {
5452 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5454 outs() << " (entends past the end of the section)\n";
5455 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5456 memcpy(&objc_class, r, left);
5458 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5459 swapStruct(objc_class);
5460 print_objc_class_t(&objc_class, &info);
5462 outs() << "(not in an __OBJC section)\n";
5465 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5466 outs() << "\tMeta Class";
5467 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5469 if (left > sizeof(struct objc_class_t)) {
5471 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5473 outs() << " (entends past the end of the section)\n";
5474 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5475 memcpy(&objc_class, r, left);
5477 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5478 swapStruct(objc_class);
5479 print_objc_class_t(&objc_class, &info);
5481 outs() << "(not in an __OBJC section)\n";
5485 if (symtab.cat_def_cnt > 0)
5486 outs() << "\tCategory Definitions\n";
5487 for (j = 0; j < symtab.cat_def_cnt; j++) {
5488 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5489 outs() << "\t(remaining category defs entries entends past the end of "
5490 << "the section)\n";
5493 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5495 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5496 sys::swapByteOrder(def);
5498 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5499 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5500 << format("0x%08" PRIx32, def);
5502 if (left > sizeof(struct objc_category_t)) {
5504 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5506 outs() << " (entends past the end of the section)\n";
5507 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5508 memcpy(&objc_category, r, left);
5510 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5511 swapStruct(objc_category);
5512 print_objc_objc_category_t(&objc_category, &info);
5514 outs() << "(not in an __OBJC section)\n";
5518 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5519 if (II != SectionRef())
5520 print_image_info(II, &info);
5525 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5526 uint32_t size, uint32_t addr) {
5527 SymbolAddressMap AddrMap;
5528 CreateSymbolAddressMap(O, &AddrMap);
5530 std::vector<SectionRef> Sections;
5531 for (const SectionRef &Section : O->sections()) {
5533 Section.getName(SectName);
5534 Sections.push_back(Section);
5537 struct DisassembleInfo info;
5538 // Set up the block of info used by the Symbolizer call backs.
5539 info.verbose = true;
5541 info.AddrMap = &AddrMap;
5542 info.Sections = &Sections;
5543 info.class_name = nullptr;
5544 info.selector_name = nullptr;
5545 info.method = nullptr;
5546 info.demangled_name = nullptr;
5547 info.bindtable = nullptr;
5552 struct objc_protocol_t protocol;
5553 uint32_t left, paddr;
5554 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5555 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5556 left = size - (p - sect);
5557 if (left < sizeof(struct objc_protocol_t)) {
5558 outs() << "Protocol extends past end of __protocol section\n";
5559 memcpy(&protocol, p, left);
5561 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5562 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5563 swapStruct(protocol);
5564 paddr = addr + (p - sect);
5565 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5566 if (print_protocol(paddr, 0, &info))
5567 outs() << "(not in an __OBJC section)\n";
5571 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5573 printObjc2_64bit_MetaData(O, verbose);
5575 MachO::mach_header H;
5577 if (H.cputype == MachO::CPU_TYPE_ARM)
5578 printObjc2_32bit_MetaData(O, verbose);
5580 // This is the 32-bit non-arm cputype case. Which is normally
5581 // the first Objective-C ABI. But it may be the case of a
5582 // binary for the iOS simulator which is the second Objective-C
5583 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5584 // and return false.
5585 if (printObjc1_32bit_MetaData(O, verbose) == false)
5586 printObjc2_32bit_MetaData(O, verbose);
5591 // GuessLiteralPointer returns a string which for the item in the Mach-O file
5592 // for the address passed in as ReferenceValue for printing as a comment with
5593 // the instruction and also returns the corresponding type of that item
5594 // indirectly through ReferenceType.
5596 // If ReferenceValue is an address of literal cstring then a pointer to the
5597 // cstring is returned and ReferenceType is set to
5598 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5600 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5601 // Class ref that name is returned and the ReferenceType is set accordingly.
5603 // Lastly, literals which are Symbol address in a literal pool are looked for
5604 // and if found the symbol name is returned and ReferenceType is set to
5605 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5607 // If there is no item in the Mach-O file for the address passed in as
5608 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
5609 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5610 uint64_t ReferencePC,
5611 uint64_t *ReferenceType,
5612 struct DisassembleInfo *info) {
5613 // First see if there is an external relocation entry at the ReferencePC.
5614 uint64_t sect_addr = info->S.getAddress();
5615 uint64_t sect_offset = ReferencePC - sect_addr;
5616 bool reloc_found = false;
5618 MachO::any_relocation_info RE;
5619 bool isExtern = false;
5621 for (const RelocationRef &Reloc : info->S.relocations()) {
5622 uint64_t RelocOffset = Reloc.getOffset();
5623 if (RelocOffset == sect_offset) {
5624 Rel = Reloc.getRawDataRefImpl();
5625 RE = info->O->getRelocation(Rel);
5626 if (info->O->isRelocationScattered(RE))
5628 isExtern = info->O->getPlainRelocationExternal(RE);
5630 symbol_iterator RelocSym = Reloc.getSymbol();
5637 // If there is an external relocation entry for a symbol in a section
5638 // then used that symbol's value for the value of the reference.
5639 if (reloc_found && isExtern) {
5640 if (info->O->getAnyRelocationPCRel(RE)) {
5641 unsigned Type = info->O->getAnyRelocationType(RE);
5642 if (Type == MachO::X86_64_RELOC_SIGNED) {
5643 Symbol.getAddress(ReferenceValue);
5648 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5649 // Message refs and Class refs.
5650 bool classref, selref, msgref, cfstring;
5651 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5652 selref, msgref, cfstring);
5653 if (classref && pointer_value == 0) {
5654 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5655 // And the pointer_value in that section is typically zero as it will be
5656 // set by dyld as part of the "bind information".
5657 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5658 if (name != nullptr) {
5659 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5660 const char *class_name = strrchr(name, '$');
5661 if (class_name != nullptr && class_name[1] == '_' &&
5662 class_name[2] != '\0') {
5663 info->class_name = class_name + 2;
5670 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5672 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5673 if (name != nullptr)
5674 info->class_name = name;
5676 name = "bad class ref";
5681 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5682 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5686 if (selref && pointer_value == 0)
5687 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5689 if (pointer_value != 0)
5690 ReferenceValue = pointer_value;
5692 const char *name = GuessCstringPointer(ReferenceValue, info);
5694 if (pointer_value != 0 && selref) {
5695 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5696 info->selector_name = name;
5697 } else if (pointer_value != 0 && msgref) {
5698 info->class_name = nullptr;
5699 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5700 info->selector_name = name;
5702 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5706 // Lastly look for an indirect symbol with this ReferenceValue which is in
5707 // a literal pool. If found return that symbol name.
5708 name = GuessIndirectSymbol(ReferenceValue, info);
5710 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5717 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
5718 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
5719 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5720 // is created and returns the symbol name that matches the ReferenceValue or
5721 // nullptr if none. The ReferenceType is passed in for the IN type of
5722 // reference the instruction is making from the values in defined in the header
5723 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5724 // Out type and the ReferenceName will also be set which is added as a comment
5725 // to the disassembled instruction.
5728 // If the symbol name is a C++ mangled name then the demangled name is
5729 // returned through ReferenceName and ReferenceType is set to
5730 // LLVMDisassembler_ReferenceType_DeMangled_Name .
5733 // When this is called to get a symbol name for a branch target then the
5734 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5735 // SymbolValue will be looked for in the indirect symbol table to determine if
5736 // it is an address for a symbol stub. If so then the symbol name for that
5737 // stub is returned indirectly through ReferenceName and then ReferenceType is
5738 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5740 // When this is called with an value loaded via a PC relative load then
5741 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5742 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
5743 // or an Objective-C meta data reference. If so the output ReferenceType is
5744 // set to correspond to that as well as setting the ReferenceName.
5745 static const char *SymbolizerSymbolLookUp(void *DisInfo,
5746 uint64_t ReferenceValue,
5747 uint64_t *ReferenceType,
5748 uint64_t ReferencePC,
5749 const char **ReferenceName) {
5750 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
5751 // If no verbose symbolic information is wanted then just return nullptr.
5752 if (!info->verbose) {
5753 *ReferenceName = nullptr;
5754 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5758 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
5760 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5761 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
5762 if (*ReferenceName != nullptr) {
5763 method_reference(info, ReferenceType, ReferenceName);
5764 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5765 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5768 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5769 if (info->demangled_name != nullptr)
5770 free(info->demangled_name);
5772 info->demangled_name =
5773 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5774 if (info->demangled_name != nullptr) {
5775 *ReferenceName = info->demangled_name;
5776 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5778 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5781 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5782 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5784 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5786 method_reference(info, ReferenceType, ReferenceName);
5788 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5789 // If this is arm64 and the reference is an adrp instruction save the
5790 // instruction, passed in ReferenceValue and the address of the instruction
5791 // for use later if we see and add immediate instruction.
5792 } else if (info->O->getArch() == Triple::aarch64 &&
5793 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5794 info->adrp_inst = ReferenceValue;
5795 info->adrp_addr = ReferencePC;
5796 SymbolName = nullptr;
5797 *ReferenceName = nullptr;
5798 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5799 // If this is arm64 and reference is an add immediate instruction and we
5801 // seen an adrp instruction just before it and the adrp's Xd register
5803 // this add's Xn register reconstruct the value being referenced and look to
5804 // see if it is a literal pointer. Note the add immediate instruction is
5805 // passed in ReferenceValue.
5806 } else if (info->O->getArch() == Triple::aarch64 &&
5807 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5808 ReferencePC - 4 == info->adrp_addr &&
5809 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5810 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5811 uint32_t addxri_inst;
5812 uint64_t adrp_imm, addxri_imm;
5815 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5816 if (info->adrp_inst & 0x0200000)
5817 adrp_imm |= 0xfffffffffc000000LL;
5819 addxri_inst = ReferenceValue;
5820 addxri_imm = (addxri_inst >> 10) & 0xfff;
5821 if (((addxri_inst >> 22) & 0x3) == 1)
5824 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5825 (adrp_imm << 12) + addxri_imm;
5828 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5829 if (*ReferenceName == nullptr)
5830 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5831 // If this is arm64 and the reference is a load register instruction and we
5832 // have seen an adrp instruction just before it and the adrp's Xd register
5833 // matches this add's Xn register reconstruct the value being referenced and
5834 // look to see if it is a literal pointer. Note the load register
5835 // instruction is passed in ReferenceValue.
5836 } else if (info->O->getArch() == Triple::aarch64 &&
5837 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5838 ReferencePC - 4 == info->adrp_addr &&
5839 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5840 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5841 uint32_t ldrxui_inst;
5842 uint64_t adrp_imm, ldrxui_imm;
5845 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5846 if (info->adrp_inst & 0x0200000)
5847 adrp_imm |= 0xfffffffffc000000LL;
5849 ldrxui_inst = ReferenceValue;
5850 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5852 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5853 (adrp_imm << 12) + (ldrxui_imm << 3);
5856 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5857 if (*ReferenceName == nullptr)
5858 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5860 // If this arm64 and is an load register (PC-relative) instruction the
5861 // ReferenceValue is the PC plus the immediate value.
5862 else if (info->O->getArch() == Triple::aarch64 &&
5863 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5864 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5866 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5867 if (*ReferenceName == nullptr)
5868 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5871 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5872 if (info->demangled_name != nullptr)
5873 free(info->demangled_name);
5875 info->demangled_name =
5876 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5877 if (info->demangled_name != nullptr) {
5878 *ReferenceName = info->demangled_name;
5879 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5884 *ReferenceName = nullptr;
5885 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5891 /// \brief Emits the comments that are stored in the CommentStream.
5892 /// Each comment in the CommentStream must end with a newline.
5893 static void emitComments(raw_svector_ostream &CommentStream,
5894 SmallString<128> &CommentsToEmit,
5895 formatted_raw_ostream &FormattedOS,
5896 const MCAsmInfo &MAI) {
5897 // Flush the stream before taking its content.
5898 CommentStream.flush();
5899 StringRef Comments = CommentsToEmit.str();
5900 // Get the default information for printing a comment.
5901 const char *CommentBegin = MAI.getCommentString();
5902 unsigned CommentColumn = MAI.getCommentColumn();
5903 bool IsFirst = true;
5904 while (!Comments.empty()) {
5906 FormattedOS << '\n';
5907 // Emit a line of comments.
5908 FormattedOS.PadToColumn(CommentColumn);
5909 size_t Position = Comments.find('\n');
5910 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5911 // Move after the newline character.
5912 Comments = Comments.substr(Position + 1);
5915 FormattedOS.flush();
5917 // Tell the comment stream that the vector changed underneath it.
5918 CommentsToEmit.clear();
5919 CommentStream.resync();
5922 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5923 StringRef DisSegName, StringRef DisSectName) {
5924 const char *McpuDefault = nullptr;
5925 const Target *ThumbTarget = nullptr;
5926 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
5928 // GetTarget prints out stuff.
5931 if (MCPU.empty() && McpuDefault)
5934 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
5935 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
5937 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
5939 // Package up features to be passed to target/subtarget
5940 std::string FeaturesStr;
5941 if (MAttrs.size()) {
5942 SubtargetFeatures Features;
5943 for (unsigned i = 0; i != MAttrs.size(); ++i)
5944 Features.AddFeature(MAttrs[i]);
5945 FeaturesStr = Features.getString();
5948 // Set up disassembler.
5949 std::unique_ptr<const MCRegisterInfo> MRI(
5950 TheTarget->createMCRegInfo(TripleName));
5951 std::unique_ptr<const MCAsmInfo> AsmInfo(
5952 TheTarget->createMCAsmInfo(*MRI, TripleName));
5953 std::unique_ptr<const MCSubtargetInfo> STI(
5954 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
5955 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
5956 std::unique_ptr<MCDisassembler> DisAsm(
5957 TheTarget->createMCDisassembler(*STI, Ctx));
5958 std::unique_ptr<MCSymbolizer> Symbolizer;
5959 struct DisassembleInfo SymbolizerInfo;
5960 std::unique_ptr<MCRelocationInfo> RelInfo(
5961 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5963 Symbolizer.reset(TheTarget->createMCSymbolizer(
5964 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5965 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
5966 DisAsm->setSymbolizer(std::move(Symbolizer));
5968 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
5969 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
5970 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
5971 // Set the display preference for hex vs. decimal immediates.
5972 IP->setPrintImmHex(PrintImmHex);
5973 // Comment stream and backing vector.
5974 SmallString<128> CommentsToEmit;
5975 raw_svector_ostream CommentStream(CommentsToEmit);
5976 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5977 // if it is done then arm64 comments for string literals don't get printed
5978 // and some constant get printed instead and not setting it causes intel
5979 // (32-bit and 64-bit) comments printed with different spacing before the
5980 // comment causing different diffs with the 'C' disassembler library API.
5981 // IP->setCommentStream(CommentStream);
5983 if (!AsmInfo || !STI || !DisAsm || !IP) {
5984 errs() << "error: couldn't initialize disassembler for target "
5985 << TripleName << '\n';
5989 // Set up thumb disassembler.
5990 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5991 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5992 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
5993 std::unique_ptr<MCDisassembler> ThumbDisAsm;
5994 std::unique_ptr<MCInstPrinter> ThumbIP;
5995 std::unique_ptr<MCContext> ThumbCtx;
5996 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5997 struct DisassembleInfo ThumbSymbolizerInfo;
5998 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
6000 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6002 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6004 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6005 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6006 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
6007 MCContext *PtrThumbCtx = ThumbCtx.get();
6009 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6011 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6012 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
6013 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
6014 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6016 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6017 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
6018 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6019 *ThumbInstrInfo, *ThumbMRI));
6020 // Set the display preference for hex vs. decimal immediates.
6021 ThumbIP->setPrintImmHex(PrintImmHex);
6024 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
6025 errs() << "error: couldn't initialize disassembler for target "
6026 << ThumbTripleName << '\n';
6030 MachO::mach_header Header = MachOOF->getHeader();
6032 // FIXME: Using the -cfg command line option, this code used to be able to
6033 // annotate relocations with the referenced symbol's name, and if this was
6034 // inside a __[cf]string section, the data it points to. This is now replaced
6035 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
6036 std::vector<SectionRef> Sections;
6037 std::vector<SymbolRef> Symbols;
6038 SmallVector<uint64_t, 8> FoundFns;
6039 uint64_t BaseSegmentAddress;
6041 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
6042 BaseSegmentAddress);
6044 // Sort the symbols by address, just in case they didn't come in that way.
6045 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
6047 // Build a data in code table that is sorted on by the address of each entry.
6048 uint64_t BaseAddress = 0;
6049 if (Header.filetype == MachO::MH_OBJECT)
6050 BaseAddress = Sections[0].getAddress();
6052 BaseAddress = BaseSegmentAddress;
6054 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
6057 DI->getOffset(Offset);
6058 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6060 array_pod_sort(Dices.begin(), Dices.end());
6063 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6065 raw_ostream &DebugOut = nulls();
6068 std::unique_ptr<DIContext> diContext;
6069 ObjectFile *DbgObj = MachOOF;
6070 // Try to find debug info and set up the DIContext for it.
6072 // A separate DSym file path was specified, parse it as a macho file,
6073 // get the sections and supply it to the section name parsing machinery.
6074 if (!DSYMFile.empty()) {
6075 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
6076 MemoryBuffer::getFileOrSTDIN(DSYMFile);
6077 if (std::error_code EC = BufOrErr.getError()) {
6078 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
6082 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6087 // Setup the DIContext
6088 diContext.reset(new DWARFContextInMemory(*DbgObj));
6091 if (DumpSections.size() == 0)
6092 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
6094 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
6096 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6099 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
6101 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
6102 if (SegmentName != DisSegName)
6106 Sections[SectIdx].getContents(BytesStr);
6107 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6109 uint64_t SectAddress = Sections[SectIdx].getAddress();
6111 bool symbolTableWorked = false;
6113 // Parse relocations.
6114 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
6115 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
6116 uint64_t RelocOffset = Reloc.getOffset();
6117 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6118 RelocOffset -= SectionAddress;
6120 symbol_iterator RelocSym = Reloc.getSymbol();
6122 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
6124 array_pod_sort(Relocs.begin(), Relocs.end());
6126 // Create a map of symbol addresses to symbol names for use by
6127 // the SymbolizerSymbolLookUp() routine.
6128 SymbolAddressMap AddrMap;
6129 bool DisSymNameFound = false;
6130 for (const SymbolRef &Symbol : MachOOF->symbols()) {
6131 SymbolRef::Type ST = Symbol.getType();
6132 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6133 ST == SymbolRef::ST_Other) {
6135 Symbol.getAddress(Address);
6136 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6137 if (std::error_code EC = SymNameOrErr.getError())
6138 report_fatal_error(EC.message());
6139 StringRef SymName = *SymNameOrErr;
6140 AddrMap[Address] = SymName;
6141 if (!DisSymName.empty() && DisSymName == SymName)
6142 DisSymNameFound = true;
6145 if (!DisSymName.empty() && !DisSymNameFound) {
6146 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6149 // Set up the block of info used by the Symbolizer call backs.
6150 SymbolizerInfo.verbose = !NoSymbolicOperands;
6151 SymbolizerInfo.O = MachOOF;
6152 SymbolizerInfo.S = Sections[SectIdx];
6153 SymbolizerInfo.AddrMap = &AddrMap;
6154 SymbolizerInfo.Sections = &Sections;
6155 SymbolizerInfo.class_name = nullptr;
6156 SymbolizerInfo.selector_name = nullptr;
6157 SymbolizerInfo.method = nullptr;
6158 SymbolizerInfo.demangled_name = nullptr;
6159 SymbolizerInfo.bindtable = nullptr;
6160 SymbolizerInfo.adrp_addr = 0;
6161 SymbolizerInfo.adrp_inst = 0;
6162 // Same for the ThumbSymbolizer
6163 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
6164 ThumbSymbolizerInfo.O = MachOOF;
6165 ThumbSymbolizerInfo.S = Sections[SectIdx];
6166 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6167 ThumbSymbolizerInfo.Sections = &Sections;
6168 ThumbSymbolizerInfo.class_name = nullptr;
6169 ThumbSymbolizerInfo.selector_name = nullptr;
6170 ThumbSymbolizerInfo.method = nullptr;
6171 ThumbSymbolizerInfo.demangled_name = nullptr;
6172 ThumbSymbolizerInfo.bindtable = nullptr;
6173 ThumbSymbolizerInfo.adrp_addr = 0;
6174 ThumbSymbolizerInfo.adrp_inst = 0;
6176 // Disassemble symbol by symbol.
6177 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
6178 ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6179 if (std::error_code EC = SymNameOrErr.getError())
6180 report_fatal_error(EC.message());
6181 StringRef SymName = *SymNameOrErr;
6183 SymbolRef::Type ST = Symbols[SymIdx].getType();
6184 if (ST != SymbolRef::ST_Function)
6187 // Make sure the symbol is defined in this section.
6188 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
6192 // If we are only disassembling one symbol see if this is that symbol.
6193 if (!DisSymName.empty() && DisSymName != SymName)
6196 // Start at the address of the symbol relative to the section's address.
6198 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6199 Symbols[SymIdx].getAddress(Start);
6200 Start -= SectionAddress;
6202 // Stop disassembling either at the beginning of the next symbol or at
6203 // the end of the section.
6204 bool containsNextSym = false;
6205 uint64_t NextSym = 0;
6206 uint64_t NextSymIdx = SymIdx + 1;
6207 while (Symbols.size() > NextSymIdx) {
6208 SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
6209 if (NextSymType == SymbolRef::ST_Function) {
6211 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
6212 Symbols[NextSymIdx].getAddress(NextSym);
6213 NextSym -= SectionAddress;
6219 uint64_t SectSize = Sections[SectIdx].getSize();
6220 uint64_t End = containsNextSym ? NextSym : SectSize;
6223 symbolTableWorked = true;
6225 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6227 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6229 outs() << SymName << ":\n";
6230 DILineInfo lastLine;
6231 for (uint64_t Index = Start; Index < End; Index += Size) {
6234 uint64_t PC = SectAddress + Index;
6235 if (!NoLeadingAddr) {
6236 if (FullLeadingAddr) {
6237 if (MachOOF->is64Bit())
6238 outs() << format("%016" PRIx64, PC);
6240 outs() << format("%08" PRIx64, PC);
6242 outs() << format("%8" PRIx64 ":", PC);
6248 // Check the data in code table here to see if this is data not an
6249 // instruction to be disassembled.
6251 Dice.push_back(std::make_pair(PC, DiceRef()));
6252 dice_table_iterator DTI =
6253 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6254 compareDiceTableEntries);
6255 if (DTI != Dices.end()) {
6257 DTI->second.getLength(Length);
6259 DTI->second.getKind(Kind);
6260 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
6261 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6262 (PC == (DTI->first + Length - 1)) && (Length & 1))
6267 SmallVector<char, 64> AnnotationsBytes;
6268 raw_svector_ostream Annotations(AnnotationsBytes);
6272 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
6273 PC, DebugOut, Annotations);
6275 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
6276 DebugOut, Annotations);
6278 if (!NoShowRawInsn) {
6279 dumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, Size), outs());
6281 formatted_raw_ostream FormattedOS(outs());
6282 Annotations.flush();
6283 StringRef AnnotationsStr = Annotations.str();
6285 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
6287 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
6288 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
6290 // Print debug info.
6292 DILineInfo dli = diContext->getLineInfoForAddress(PC);
6293 // Print valid line info if it changed.
6294 if (dli != lastLine && dli.Line != 0)
6295 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6301 unsigned int Arch = MachOOF->getArch();
6302 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6303 outs() << format("\t.byte 0x%02x #bad opcode\n",
6304 *(Bytes.data() + Index) & 0xff);
6305 Size = 1; // skip exactly one illegible byte and move on.
6306 } else if (Arch == Triple::aarch64) {
6307 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6308 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6309 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6310 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6311 outs() << format("\t.long\t0x%08x\n", opcode);
6314 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6316 Size = 1; // skip illegible bytes
6321 if (!symbolTableWorked) {
6322 // Reading the symbol table didn't work, disassemble the whole section.
6323 uint64_t SectAddress = Sections[SectIdx].getAddress();
6324 uint64_t SectSize = Sections[SectIdx].getSize();
6326 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
6329 uint64_t PC = SectAddress + Index;
6330 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6331 DebugOut, nulls())) {
6332 if (!NoLeadingAddr) {
6333 if (FullLeadingAddr) {
6334 if (MachOOF->is64Bit())
6335 outs() << format("%016" PRIx64, PC);
6337 outs() << format("%08" PRIx64, PC);
6339 outs() << format("%8" PRIx64 ":", PC);
6342 if (!NoShowRawInsn) {
6344 dumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, InstSize), outs());
6346 IP->printInst(&Inst, outs(), "", *STI);
6349 unsigned int Arch = MachOOF->getArch();
6350 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6351 outs() << format("\t.byte 0x%02x #bad opcode\n",
6352 *(Bytes.data() + Index) & 0xff);
6353 InstSize = 1; // skip exactly one illegible byte and move on.
6355 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6357 InstSize = 1; // skip illegible bytes
6362 // The TripleName's need to be reset if we are called again for a different
6365 ThumbTripleName = "";
6367 if (SymbolizerInfo.method != nullptr)
6368 free(SymbolizerInfo.method);
6369 if (SymbolizerInfo.demangled_name != nullptr)
6370 free(SymbolizerInfo.demangled_name);
6371 if (SymbolizerInfo.bindtable != nullptr)
6372 delete SymbolizerInfo.bindtable;
6373 if (ThumbSymbolizerInfo.method != nullptr)
6374 free(ThumbSymbolizerInfo.method);
6375 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6376 free(ThumbSymbolizerInfo.demangled_name);
6377 if (ThumbSymbolizerInfo.bindtable != nullptr)
6378 delete ThumbSymbolizerInfo.bindtable;
6382 //===----------------------------------------------------------------------===//
6383 // __compact_unwind section dumping
6384 //===----------------------------------------------------------------------===//
6388 template <typename T> static uint64_t readNext(const char *&Buf) {
6389 using llvm::support::little;
6390 using llvm::support::unaligned;
6392 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6397 struct CompactUnwindEntry {
6398 uint32_t OffsetInSection;
6400 uint64_t FunctionAddr;
6402 uint32_t CompactEncoding;
6403 uint64_t PersonalityAddr;
6406 RelocationRef FunctionReloc;
6407 RelocationRef PersonalityReloc;
6408 RelocationRef LSDAReloc;
6410 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
6411 : OffsetInSection(Offset) {
6413 read<uint64_t>(Contents.data() + Offset);
6415 read<uint32_t>(Contents.data() + Offset);
6419 template <typename UIntPtr> void read(const char *Buf) {
6420 FunctionAddr = readNext<UIntPtr>(Buf);
6421 Length = readNext<uint32_t>(Buf);
6422 CompactEncoding = readNext<uint32_t>(Buf);
6423 PersonalityAddr = readNext<UIntPtr>(Buf);
6424 LSDAAddr = readNext<UIntPtr>(Buf);
6429 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
6430 /// and data being relocated, determine the best base Name and Addend to use for
6431 /// display purposes.
6433 /// 1. An Extern relocation will directly reference a symbol (and the data is
6434 /// then already an addend), so use that.
6435 /// 2. Otherwise the data is an offset in the object file's layout; try to find
6436 // a symbol before it in the same section, and use the offset from there.
6437 /// 3. Finally, if all that fails, fall back to an offset from the start of the
6438 /// referenced section.
6439 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6440 std::map<uint64_t, SymbolRef> &Symbols,
6441 const RelocationRef &Reloc, uint64_t Addr,
6442 StringRef &Name, uint64_t &Addend) {
6443 if (Reloc.getSymbol() != Obj->symbol_end()) {
6444 ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6445 if (std::error_code EC = NameOrErr.getError())
6446 report_fatal_error(EC.message());
6452 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
6453 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
6455 uint64_t SectionAddr = RelocSection.getAddress();
6457 auto Sym = Symbols.upper_bound(Addr);
6458 if (Sym == Symbols.begin()) {
6459 // The first symbol in the object is after this reference, the best we can
6460 // do is section-relative notation.
6461 RelocSection.getName(Name);
6462 Addend = Addr - SectionAddr;
6466 // Go back one so that SymbolAddress <= Addr.
6469 section_iterator SymSection = Obj->section_end();
6470 Sym->second.getSection(SymSection);
6471 if (RelocSection == *SymSection) {
6472 // There's a valid symbol in the same section before this reference.
6473 ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6474 if (std::error_code EC = NameOrErr.getError())
6475 report_fatal_error(EC.message());
6477 Addend = Addr - Sym->first;
6481 // There is a symbol before this reference, but it's in a different
6482 // section. Probably not helpful to mention it, so use the section name.
6483 RelocSection.getName(Name);
6484 Addend = Addr - SectionAddr;
6487 static void printUnwindRelocDest(const MachOObjectFile *Obj,
6488 std::map<uint64_t, SymbolRef> &Symbols,
6489 const RelocationRef &Reloc, uint64_t Addr) {
6493 if (!Reloc.getObject())
6496 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6500 outs() << " + " << format("0x%" PRIx64, Addend);
6504 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6505 std::map<uint64_t, SymbolRef> &Symbols,
6506 const SectionRef &CompactUnwind) {
6508 assert(Obj->isLittleEndian() &&
6509 "There should not be a big-endian .o with __compact_unwind");
6511 bool Is64 = Obj->is64Bit();
6512 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6513 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6516 CompactUnwind.getContents(Contents);
6518 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6520 // First populate the initial raw offsets, encodings and so on from the entry.
6521 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6522 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6523 CompactUnwinds.push_back(Entry);
6526 // Next we need to look at the relocations to find out what objects are
6527 // actually being referred to.
6528 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
6529 uint64_t RelocAddress = Reloc.getOffset();
6531 uint32_t EntryIdx = RelocAddress / EntrySize;
6532 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6533 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6535 if (OffsetInEntry == 0)
6536 Entry.FunctionReloc = Reloc;
6537 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6538 Entry.PersonalityReloc = Reloc;
6539 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6540 Entry.LSDAReloc = Reloc;
6542 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6545 // Finally, we're ready to print the data we've gathered.
6546 outs() << "Contents of __compact_unwind section:\n";
6547 for (auto &Entry : CompactUnwinds) {
6548 outs() << " Entry at offset "
6549 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
6551 // 1. Start of the region this entry applies to.
6552 outs() << " start: " << format("0x%" PRIx64,
6553 Entry.FunctionAddr) << ' ';
6554 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
6557 // 2. Length of the region this entry applies to.
6558 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6560 // 3. The 32-bit compact encoding.
6561 outs() << " compact encoding: "
6562 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
6564 // 4. The personality function, if present.
6565 if (Entry.PersonalityReloc.getObject()) {
6566 outs() << " personality function: "
6567 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
6568 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6569 Entry.PersonalityAddr);
6573 // 5. This entry's language-specific data area.
6574 if (Entry.LSDAReloc.getObject()) {
6575 outs() << " LSDA: " << format("0x%" PRIx64,
6576 Entry.LSDAAddr) << ' ';
6577 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6583 //===----------------------------------------------------------------------===//
6584 // __unwind_info section dumping
6585 //===----------------------------------------------------------------------===//
6587 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6588 const char *Pos = PageStart;
6589 uint32_t Kind = readNext<uint32_t>(Pos);
6591 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6593 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6594 uint16_t NumEntries = readNext<uint16_t>(Pos);
6596 Pos = PageStart + EntriesStart;
6597 for (unsigned i = 0; i < NumEntries; ++i) {
6598 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6599 uint32_t Encoding = readNext<uint32_t>(Pos);
6601 outs() << " [" << i << "]: "
6602 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6604 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
6608 static void printCompressedSecondLevelUnwindPage(
6609 const char *PageStart, uint32_t FunctionBase,
6610 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6611 const char *Pos = PageStart;
6612 uint32_t Kind = readNext<uint32_t>(Pos);
6614 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6616 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6617 uint16_t NumEntries = readNext<uint16_t>(Pos);
6619 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6620 readNext<uint16_t>(Pos);
6621 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6622 PageStart + EncodingsStart);
6624 Pos = PageStart + EntriesStart;
6625 for (unsigned i = 0; i < NumEntries; ++i) {
6626 uint32_t Entry = readNext<uint32_t>(Pos);
6627 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6628 uint32_t EncodingIdx = Entry >> 24;
6631 if (EncodingIdx < CommonEncodings.size())
6632 Encoding = CommonEncodings[EncodingIdx];
6634 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6636 outs() << " [" << i << "]: "
6637 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6639 << "encoding[" << EncodingIdx
6640 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
6644 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6645 std::map<uint64_t, SymbolRef> &Symbols,
6646 const SectionRef &UnwindInfo) {
6648 assert(Obj->isLittleEndian() &&
6649 "There should not be a big-endian .o with __unwind_info");
6651 outs() << "Contents of __unwind_info section:\n";
6654 UnwindInfo.getContents(Contents);
6655 const char *Pos = Contents.data();
6657 //===----------------------------------
6659 //===----------------------------------
6661 uint32_t Version = readNext<uint32_t>(Pos);
6662 outs() << " Version: "
6663 << format("0x%" PRIx32, Version) << '\n';
6664 assert(Version == 1 && "only understand version 1");
6666 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6667 outs() << " Common encodings array section offset: "
6668 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6669 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6670 outs() << " Number of common encodings in array: "
6671 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6673 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6674 outs() << " Personality function array section offset: "
6675 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6676 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6677 outs() << " Number of personality functions in array: "
6678 << format("0x%" PRIx32, NumPersonalities) << '\n';
6680 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6681 outs() << " Index array section offset: "
6682 << format("0x%" PRIx32, IndicesStart) << '\n';
6683 uint32_t NumIndices = readNext<uint32_t>(Pos);
6684 outs() << " Number of indices in array: "
6685 << format("0x%" PRIx32, NumIndices) << '\n';
6687 //===----------------------------------
6688 // A shared list of common encodings
6689 //===----------------------------------
6691 // These occupy indices in the range [0, N] whenever an encoding is referenced
6692 // from a compressed 2nd level index table. In practice the linker only
6693 // creates ~128 of these, so that indices are available to embed encodings in
6694 // the 2nd level index.
6696 SmallVector<uint32_t, 64> CommonEncodings;
6697 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6698 Pos = Contents.data() + CommonEncodingsStart;
6699 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6700 uint32_t Encoding = readNext<uint32_t>(Pos);
6701 CommonEncodings.push_back(Encoding);
6703 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6707 //===----------------------------------
6708 // Personality functions used in this executable
6709 //===----------------------------------
6711 // There should be only a handful of these (one per source language,
6712 // roughly). Particularly since they only get 2 bits in the compact encoding.
6714 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6715 Pos = Contents.data() + PersonalitiesStart;
6716 for (unsigned i = 0; i < NumPersonalities; ++i) {
6717 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6718 outs() << " personality[" << i + 1
6719 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6722 //===----------------------------------
6723 // The level 1 index entries
6724 //===----------------------------------
6726 // These specify an approximate place to start searching for the more detailed
6727 // information, sorted by PC.
6730 uint32_t FunctionOffset;
6731 uint32_t SecondLevelPageStart;
6735 SmallVector<IndexEntry, 4> IndexEntries;
6737 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6738 Pos = Contents.data() + IndicesStart;
6739 for (unsigned i = 0; i < NumIndices; ++i) {
6742 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6743 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6744 Entry.LSDAStart = readNext<uint32_t>(Pos);
6745 IndexEntries.push_back(Entry);
6747 outs() << " [" << i << "]: "
6748 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6750 << "2nd level page offset="
6751 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
6752 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
6755 //===----------------------------------
6756 // Next come the LSDA tables
6757 //===----------------------------------
6759 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6760 // the first top-level index's LSDAOffset to the last (sentinel).
6762 outs() << " LSDA descriptors:\n";
6763 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6764 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6765 (2 * sizeof(uint32_t));
6766 for (int i = 0; i < NumLSDAs; ++i) {
6767 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6768 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6769 outs() << " [" << i << "]: "
6770 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6772 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
6775 //===----------------------------------
6776 // Finally, the 2nd level indices
6777 //===----------------------------------
6779 // Generally these are 4K in size, and have 2 possible forms:
6780 // + Regular stores up to 511 entries with disparate encodings
6781 // + Compressed stores up to 1021 entries if few enough compact encoding
6783 outs() << " Second level indices:\n";
6784 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6785 // The final sentinel top-level index has no associated 2nd level page
6786 if (IndexEntries[i].SecondLevelPageStart == 0)
6789 outs() << " Second level index[" << i << "]: "
6790 << "offset in section="
6791 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6793 << "base function offset="
6794 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6796 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
6797 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
6799 printRegularSecondLevelUnwindPage(Pos);
6801 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6804 llvm_unreachable("Do not know how to print this kind of 2nd level page");
6808 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6809 std::map<uint64_t, SymbolRef> Symbols;
6810 for (const SymbolRef &SymRef : Obj->symbols()) {
6811 // Discard any undefined or absolute symbols. They're not going to take part
6812 // in the convenience lookup for unwind info and just take up resources.
6813 section_iterator Section = Obj->section_end();
6814 SymRef.getSection(Section);
6815 if (Section == Obj->section_end())
6819 SymRef.getAddress(Addr);
6820 Symbols.insert(std::make_pair(Addr, SymRef));
6823 for (const SectionRef &Section : Obj->sections()) {
6825 Section.getName(SectName);
6826 if (SectName == "__compact_unwind")
6827 printMachOCompactUnwindSection(Obj, Symbols, Section);
6828 else if (SectName == "__unwind_info")
6829 printMachOUnwindInfoSection(Obj, Symbols, Section);
6830 else if (SectName == "__eh_frame")
6831 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
6835 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6836 uint32_t cpusubtype, uint32_t filetype,
6837 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6839 outs() << "Mach header\n";
6840 outs() << " magic cputype cpusubtype caps filetype ncmds "
6841 "sizeofcmds flags\n";
6843 if (magic == MachO::MH_MAGIC)
6844 outs() << " MH_MAGIC";
6845 else if (magic == MachO::MH_MAGIC_64)
6846 outs() << "MH_MAGIC_64";
6848 outs() << format(" 0x%08" PRIx32, magic);
6850 case MachO::CPU_TYPE_I386:
6852 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6853 case MachO::CPU_SUBTYPE_I386_ALL:
6857 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6861 case MachO::CPU_TYPE_X86_64:
6862 outs() << " X86_64";
6863 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6864 case MachO::CPU_SUBTYPE_X86_64_ALL:
6867 case MachO::CPU_SUBTYPE_X86_64_H:
6868 outs() << " Haswell";
6871 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6875 case MachO::CPU_TYPE_ARM:
6877 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6878 case MachO::CPU_SUBTYPE_ARM_ALL:
6881 case MachO::CPU_SUBTYPE_ARM_V4T:
6884 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6887 case MachO::CPU_SUBTYPE_ARM_XSCALE:
6888 outs() << " XSCALE";
6890 case MachO::CPU_SUBTYPE_ARM_V6:
6893 case MachO::CPU_SUBTYPE_ARM_V6M:
6896 case MachO::CPU_SUBTYPE_ARM_V7:
6899 case MachO::CPU_SUBTYPE_ARM_V7EM:
6902 case MachO::CPU_SUBTYPE_ARM_V7K:
6905 case MachO::CPU_SUBTYPE_ARM_V7M:
6908 case MachO::CPU_SUBTYPE_ARM_V7S:
6912 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6916 case MachO::CPU_TYPE_ARM64:
6918 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6919 case MachO::CPU_SUBTYPE_ARM64_ALL:
6923 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6927 case MachO::CPU_TYPE_POWERPC:
6929 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6930 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6934 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6938 case MachO::CPU_TYPE_POWERPC64:
6940 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6941 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6945 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6950 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
6953 outs() << format(" 0x%02" PRIx32,
6954 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
6957 case MachO::MH_OBJECT:
6958 outs() << " OBJECT";
6960 case MachO::MH_EXECUTE:
6961 outs() << " EXECUTE";
6963 case MachO::MH_FVMLIB:
6964 outs() << " FVMLIB";
6966 case MachO::MH_CORE:
6969 case MachO::MH_PRELOAD:
6970 outs() << " PRELOAD";
6972 case MachO::MH_DYLIB:
6975 case MachO::MH_DYLIB_STUB:
6976 outs() << " DYLIB_STUB";
6978 case MachO::MH_DYLINKER:
6979 outs() << " DYLINKER";
6981 case MachO::MH_BUNDLE:
6982 outs() << " BUNDLE";
6984 case MachO::MH_DSYM:
6987 case MachO::MH_KEXT_BUNDLE:
6988 outs() << " KEXTBUNDLE";
6991 outs() << format(" %10u", filetype);
6994 outs() << format(" %5u", ncmds);
6995 outs() << format(" %10u", sizeofcmds);
6997 if (f & MachO::MH_NOUNDEFS) {
6998 outs() << " NOUNDEFS";
6999 f &= ~MachO::MH_NOUNDEFS;
7001 if (f & MachO::MH_INCRLINK) {
7002 outs() << " INCRLINK";
7003 f &= ~MachO::MH_INCRLINK;
7005 if (f & MachO::MH_DYLDLINK) {
7006 outs() << " DYLDLINK";
7007 f &= ~MachO::MH_DYLDLINK;
7009 if (f & MachO::MH_BINDATLOAD) {
7010 outs() << " BINDATLOAD";
7011 f &= ~MachO::MH_BINDATLOAD;
7013 if (f & MachO::MH_PREBOUND) {
7014 outs() << " PREBOUND";
7015 f &= ~MachO::MH_PREBOUND;
7017 if (f & MachO::MH_SPLIT_SEGS) {
7018 outs() << " SPLIT_SEGS";
7019 f &= ~MachO::MH_SPLIT_SEGS;
7021 if (f & MachO::MH_LAZY_INIT) {
7022 outs() << " LAZY_INIT";
7023 f &= ~MachO::MH_LAZY_INIT;
7025 if (f & MachO::MH_TWOLEVEL) {
7026 outs() << " TWOLEVEL";
7027 f &= ~MachO::MH_TWOLEVEL;
7029 if (f & MachO::MH_FORCE_FLAT) {
7030 outs() << " FORCE_FLAT";
7031 f &= ~MachO::MH_FORCE_FLAT;
7033 if (f & MachO::MH_NOMULTIDEFS) {
7034 outs() << " NOMULTIDEFS";
7035 f &= ~MachO::MH_NOMULTIDEFS;
7037 if (f & MachO::MH_NOFIXPREBINDING) {
7038 outs() << " NOFIXPREBINDING";
7039 f &= ~MachO::MH_NOFIXPREBINDING;
7041 if (f & MachO::MH_PREBINDABLE) {
7042 outs() << " PREBINDABLE";
7043 f &= ~MachO::MH_PREBINDABLE;
7045 if (f & MachO::MH_ALLMODSBOUND) {
7046 outs() << " ALLMODSBOUND";
7047 f &= ~MachO::MH_ALLMODSBOUND;
7049 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7050 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7051 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7053 if (f & MachO::MH_CANONICAL) {
7054 outs() << " CANONICAL";
7055 f &= ~MachO::MH_CANONICAL;
7057 if (f & MachO::MH_WEAK_DEFINES) {
7058 outs() << " WEAK_DEFINES";
7059 f &= ~MachO::MH_WEAK_DEFINES;
7061 if (f & MachO::MH_BINDS_TO_WEAK) {
7062 outs() << " BINDS_TO_WEAK";
7063 f &= ~MachO::MH_BINDS_TO_WEAK;
7065 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7066 outs() << " ALLOW_STACK_EXECUTION";
7067 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7069 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7070 outs() << " DEAD_STRIPPABLE_DYLIB";
7071 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7073 if (f & MachO::MH_PIE) {
7075 f &= ~MachO::MH_PIE;
7077 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7078 outs() << " NO_REEXPORTED_DYLIBS";
7079 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7081 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7082 outs() << " MH_HAS_TLV_DESCRIPTORS";
7083 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7085 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7086 outs() << " MH_NO_HEAP_EXECUTION";
7087 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7089 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7090 outs() << " APP_EXTENSION_SAFE";
7091 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7093 if (f != 0 || flags == 0)
7094 outs() << format(" 0x%08" PRIx32, f);
7096 outs() << format(" 0x%08" PRIx32, magic);
7097 outs() << format(" %7d", cputype);
7098 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7099 outs() << format(" 0x%02" PRIx32,
7100 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7101 outs() << format(" %10u", filetype);
7102 outs() << format(" %5u", ncmds);
7103 outs() << format(" %10u", sizeofcmds);
7104 outs() << format(" 0x%08" PRIx32, flags);
7109 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7110 StringRef SegName, uint64_t vmaddr,
7111 uint64_t vmsize, uint64_t fileoff,
7112 uint64_t filesize, uint32_t maxprot,
7113 uint32_t initprot, uint32_t nsects,
7114 uint32_t flags, uint32_t object_size,
7116 uint64_t expected_cmdsize;
7117 if (cmd == MachO::LC_SEGMENT) {
7118 outs() << " cmd LC_SEGMENT\n";
7119 expected_cmdsize = nsects;
7120 expected_cmdsize *= sizeof(struct MachO::section);
7121 expected_cmdsize += sizeof(struct MachO::segment_command);
7123 outs() << " cmd LC_SEGMENT_64\n";
7124 expected_cmdsize = nsects;
7125 expected_cmdsize *= sizeof(struct MachO::section_64);
7126 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7128 outs() << " cmdsize " << cmdsize;
7129 if (cmdsize != expected_cmdsize)
7130 outs() << " Inconsistent size\n";
7133 outs() << " segname " << SegName << "\n";
7134 if (cmd == MachO::LC_SEGMENT_64) {
7135 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7136 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7138 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7139 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
7141 outs() << " fileoff " << fileoff;
7142 if (fileoff > object_size)
7143 outs() << " (past end of file)\n";
7146 outs() << " filesize " << filesize;
7147 if (fileoff + filesize > object_size)
7148 outs() << " (past end of file)\n";
7153 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7154 MachO::VM_PROT_EXECUTE)) != 0)
7155 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7157 if (maxprot & MachO::VM_PROT_READ)
7158 outs() << " maxprot r";
7160 outs() << " maxprot -";
7161 if (maxprot & MachO::VM_PROT_WRITE)
7165 if (maxprot & MachO::VM_PROT_EXECUTE)
7171 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7172 MachO::VM_PROT_EXECUTE)) != 0)
7173 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7175 if (initprot & MachO::VM_PROT_READ)
7176 outs() << " initprot r";
7178 outs() << " initprot -";
7179 if (initprot & MachO::VM_PROT_WRITE)
7183 if (initprot & MachO::VM_PROT_EXECUTE)
7189 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7190 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7192 outs() << " nsects " << nsects << "\n";
7196 outs() << " (none)\n";
7198 if (flags & MachO::SG_HIGHVM) {
7199 outs() << " HIGHVM";
7200 flags &= ~MachO::SG_HIGHVM;
7202 if (flags & MachO::SG_FVMLIB) {
7203 outs() << " FVMLIB";
7204 flags &= ~MachO::SG_FVMLIB;
7206 if (flags & MachO::SG_NORELOC) {
7207 outs() << " NORELOC";
7208 flags &= ~MachO::SG_NORELOC;
7210 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7211 outs() << " PROTECTED_VERSION_1";
7212 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7215 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7220 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7224 static void PrintSection(const char *sectname, const char *segname,
7225 uint64_t addr, uint64_t size, uint32_t offset,
7226 uint32_t align, uint32_t reloff, uint32_t nreloc,
7227 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7228 uint32_t cmd, const char *sg_segname,
7229 uint32_t filetype, uint32_t object_size,
7231 outs() << "Section\n";
7232 outs() << " sectname " << format("%.16s\n", sectname);
7233 outs() << " segname " << format("%.16s", segname);
7234 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7235 outs() << " (does not match segment)\n";
7238 if (cmd == MachO::LC_SEGMENT_64) {
7239 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7240 outs() << " size " << format("0x%016" PRIx64, size);
7242 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7243 outs() << " size " << format("0x%08" PRIx64, size);
7245 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7246 outs() << " (past end of file)\n";
7249 outs() << " offset " << offset;
7250 if (offset > object_size)
7251 outs() << " (past end of file)\n";
7254 uint32_t align_shifted = 1 << align;
7255 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7256 outs() << " reloff " << reloff;
7257 if (reloff > object_size)
7258 outs() << " (past end of file)\n";
7261 outs() << " nreloc " << nreloc;
7262 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7263 outs() << " (past end of file)\n";
7266 uint32_t section_type = flags & MachO::SECTION_TYPE;
7269 if (section_type == MachO::S_REGULAR)
7270 outs() << " S_REGULAR\n";
7271 else if (section_type == MachO::S_ZEROFILL)
7272 outs() << " S_ZEROFILL\n";
7273 else if (section_type == MachO::S_CSTRING_LITERALS)
7274 outs() << " S_CSTRING_LITERALS\n";
7275 else if (section_type == MachO::S_4BYTE_LITERALS)
7276 outs() << " S_4BYTE_LITERALS\n";
7277 else if (section_type == MachO::S_8BYTE_LITERALS)
7278 outs() << " S_8BYTE_LITERALS\n";
7279 else if (section_type == MachO::S_16BYTE_LITERALS)
7280 outs() << " S_16BYTE_LITERALS\n";
7281 else if (section_type == MachO::S_LITERAL_POINTERS)
7282 outs() << " S_LITERAL_POINTERS\n";
7283 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7284 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7285 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7286 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7287 else if (section_type == MachO::S_SYMBOL_STUBS)
7288 outs() << " S_SYMBOL_STUBS\n";
7289 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7290 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7291 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7292 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7293 else if (section_type == MachO::S_COALESCED)
7294 outs() << " S_COALESCED\n";
7295 else if (section_type == MachO::S_INTERPOSING)
7296 outs() << " S_INTERPOSING\n";
7297 else if (section_type == MachO::S_DTRACE_DOF)
7298 outs() << " S_DTRACE_DOF\n";
7299 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7300 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7301 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7302 outs() << " S_THREAD_LOCAL_REGULAR\n";
7303 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7304 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7305 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7306 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7307 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7308 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7309 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7310 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7312 outs() << format("0x%08" PRIx32, section_type) << "\n";
7313 outs() << "attributes";
7314 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7315 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7316 outs() << " PURE_INSTRUCTIONS";
7317 if (section_attributes & MachO::S_ATTR_NO_TOC)
7318 outs() << " NO_TOC";
7319 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7320 outs() << " STRIP_STATIC_SYMS";
7321 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7322 outs() << " NO_DEAD_STRIP";
7323 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7324 outs() << " LIVE_SUPPORT";
7325 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7326 outs() << " SELF_MODIFYING_CODE";
7327 if (section_attributes & MachO::S_ATTR_DEBUG)
7329 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7330 outs() << " SOME_INSTRUCTIONS";
7331 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7332 outs() << " EXT_RELOC";
7333 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7334 outs() << " LOC_RELOC";
7335 if (section_attributes == 0)
7336 outs() << " (none)";
7339 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7340 outs() << " reserved1 " << reserved1;
7341 if (section_type == MachO::S_SYMBOL_STUBS ||
7342 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7343 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7344 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7345 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7346 outs() << " (index into indirect symbol table)\n";
7349 outs() << " reserved2 " << reserved2;
7350 if (section_type == MachO::S_SYMBOL_STUBS)
7351 outs() << " (size of stubs)\n";
7356 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
7357 uint32_t object_size) {
7358 outs() << " cmd LC_SYMTAB\n";
7359 outs() << " cmdsize " << st.cmdsize;
7360 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7361 outs() << " Incorrect size\n";
7364 outs() << " symoff " << st.symoff;
7365 if (st.symoff > object_size)
7366 outs() << " (past end of file)\n";
7369 outs() << " nsyms " << st.nsyms;
7372 big_size = st.nsyms;
7373 big_size *= sizeof(struct MachO::nlist_64);
7374 big_size += st.symoff;
7375 if (big_size > object_size)
7376 outs() << " (past end of file)\n";
7380 big_size = st.nsyms;
7381 big_size *= sizeof(struct MachO::nlist);
7382 big_size += st.symoff;
7383 if (big_size > object_size)
7384 outs() << " (past end of file)\n";
7388 outs() << " stroff " << st.stroff;
7389 if (st.stroff > object_size)
7390 outs() << " (past end of file)\n";
7393 outs() << " strsize " << st.strsize;
7394 big_size = st.stroff;
7395 big_size += st.strsize;
7396 if (big_size > object_size)
7397 outs() << " (past end of file)\n";
7402 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7403 uint32_t nsyms, uint32_t object_size,
7405 outs() << " cmd LC_DYSYMTAB\n";
7406 outs() << " cmdsize " << dyst.cmdsize;
7407 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7408 outs() << " Incorrect size\n";
7411 outs() << " ilocalsym " << dyst.ilocalsym;
7412 if (dyst.ilocalsym > nsyms)
7413 outs() << " (greater than the number of symbols)\n";
7416 outs() << " nlocalsym " << dyst.nlocalsym;
7418 big_size = dyst.ilocalsym;
7419 big_size += dyst.nlocalsym;
7420 if (big_size > nsyms)
7421 outs() << " (past the end of the symbol table)\n";
7424 outs() << " iextdefsym " << dyst.iextdefsym;
7425 if (dyst.iextdefsym > nsyms)
7426 outs() << " (greater than the number of symbols)\n";
7429 outs() << " nextdefsym " << dyst.nextdefsym;
7430 big_size = dyst.iextdefsym;
7431 big_size += dyst.nextdefsym;
7432 if (big_size > nsyms)
7433 outs() << " (past the end of the symbol table)\n";
7436 outs() << " iundefsym " << dyst.iundefsym;
7437 if (dyst.iundefsym > nsyms)
7438 outs() << " (greater than the number of symbols)\n";
7441 outs() << " nundefsym " << dyst.nundefsym;
7442 big_size = dyst.iundefsym;
7443 big_size += dyst.nundefsym;
7444 if (big_size > nsyms)
7445 outs() << " (past the end of the symbol table)\n";
7448 outs() << " tocoff " << dyst.tocoff;
7449 if (dyst.tocoff > object_size)
7450 outs() << " (past end of file)\n";
7453 outs() << " ntoc " << dyst.ntoc;
7454 big_size = dyst.ntoc;
7455 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7456 big_size += dyst.tocoff;
7457 if (big_size > object_size)
7458 outs() << " (past end of file)\n";
7461 outs() << " modtaboff " << dyst.modtaboff;
7462 if (dyst.modtaboff > object_size)
7463 outs() << " (past end of file)\n";
7466 outs() << " nmodtab " << dyst.nmodtab;
7469 modtabend = dyst.nmodtab;
7470 modtabend *= sizeof(struct MachO::dylib_module_64);
7471 modtabend += dyst.modtaboff;
7473 modtabend = dyst.nmodtab;
7474 modtabend *= sizeof(struct MachO::dylib_module);
7475 modtabend += dyst.modtaboff;
7477 if (modtabend > object_size)
7478 outs() << " (past end of file)\n";
7481 outs() << " extrefsymoff " << dyst.extrefsymoff;
7482 if (dyst.extrefsymoff > object_size)
7483 outs() << " (past end of file)\n";
7486 outs() << " nextrefsyms " << dyst.nextrefsyms;
7487 big_size = dyst.nextrefsyms;
7488 big_size *= sizeof(struct MachO::dylib_reference);
7489 big_size += dyst.extrefsymoff;
7490 if (big_size > object_size)
7491 outs() << " (past end of file)\n";
7494 outs() << " indirectsymoff " << dyst.indirectsymoff;
7495 if (dyst.indirectsymoff > object_size)
7496 outs() << " (past end of file)\n";
7499 outs() << " nindirectsyms " << dyst.nindirectsyms;
7500 big_size = dyst.nindirectsyms;
7501 big_size *= sizeof(uint32_t);
7502 big_size += dyst.indirectsymoff;
7503 if (big_size > object_size)
7504 outs() << " (past end of file)\n";
7507 outs() << " extreloff " << dyst.extreloff;
7508 if (dyst.extreloff > object_size)
7509 outs() << " (past end of file)\n";
7512 outs() << " nextrel " << dyst.nextrel;
7513 big_size = dyst.nextrel;
7514 big_size *= sizeof(struct MachO::relocation_info);
7515 big_size += dyst.extreloff;
7516 if (big_size > object_size)
7517 outs() << " (past end of file)\n";
7520 outs() << " locreloff " << dyst.locreloff;
7521 if (dyst.locreloff > object_size)
7522 outs() << " (past end of file)\n";
7525 outs() << " nlocrel " << dyst.nlocrel;
7526 big_size = dyst.nlocrel;
7527 big_size *= sizeof(struct MachO::relocation_info);
7528 big_size += dyst.locreloff;
7529 if (big_size > object_size)
7530 outs() << " (past end of file)\n";
7535 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7536 uint32_t object_size) {
7537 if (dc.cmd == MachO::LC_DYLD_INFO)
7538 outs() << " cmd LC_DYLD_INFO\n";
7540 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7541 outs() << " cmdsize " << dc.cmdsize;
7542 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7543 outs() << " Incorrect size\n";
7546 outs() << " rebase_off " << dc.rebase_off;
7547 if (dc.rebase_off > object_size)
7548 outs() << " (past end of file)\n";
7551 outs() << " rebase_size " << dc.rebase_size;
7553 big_size = dc.rebase_off;
7554 big_size += dc.rebase_size;
7555 if (big_size > object_size)
7556 outs() << " (past end of file)\n";
7559 outs() << " bind_off " << dc.bind_off;
7560 if (dc.bind_off > object_size)
7561 outs() << " (past end of file)\n";
7564 outs() << " bind_size " << dc.bind_size;
7565 big_size = dc.bind_off;
7566 big_size += dc.bind_size;
7567 if (big_size > object_size)
7568 outs() << " (past end of file)\n";
7571 outs() << " weak_bind_off " << dc.weak_bind_off;
7572 if (dc.weak_bind_off > object_size)
7573 outs() << " (past end of file)\n";
7576 outs() << " weak_bind_size " << dc.weak_bind_size;
7577 big_size = dc.weak_bind_off;
7578 big_size += dc.weak_bind_size;
7579 if (big_size > object_size)
7580 outs() << " (past end of file)\n";
7583 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7584 if (dc.lazy_bind_off > object_size)
7585 outs() << " (past end of file)\n";
7588 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7589 big_size = dc.lazy_bind_off;
7590 big_size += dc.lazy_bind_size;
7591 if (big_size > object_size)
7592 outs() << " (past end of file)\n";
7595 outs() << " export_off " << dc.export_off;
7596 if (dc.export_off > object_size)
7597 outs() << " (past end of file)\n";
7600 outs() << " export_size " << dc.export_size;
7601 big_size = dc.export_off;
7602 big_size += dc.export_size;
7603 if (big_size > object_size)
7604 outs() << " (past end of file)\n";
7609 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7611 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7612 outs() << " cmd LC_ID_DYLINKER\n";
7613 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7614 outs() << " cmd LC_LOAD_DYLINKER\n";
7615 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7616 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7618 outs() << " cmd ?(" << dyld.cmd << ")\n";
7619 outs() << " cmdsize " << dyld.cmdsize;
7620 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7621 outs() << " Incorrect size\n";
7624 if (dyld.name >= dyld.cmdsize)
7625 outs() << " name ?(bad offset " << dyld.name << ")\n";
7627 const char *P = (const char *)(Ptr) + dyld.name;
7628 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7632 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7633 outs() << " cmd LC_UUID\n";
7634 outs() << " cmdsize " << uuid.cmdsize;
7635 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7636 outs() << " Incorrect size\n";
7640 outs() << format("%02" PRIX32, uuid.uuid[0]);
7641 outs() << format("%02" PRIX32, uuid.uuid[1]);
7642 outs() << format("%02" PRIX32, uuid.uuid[2]);
7643 outs() << format("%02" PRIX32, uuid.uuid[3]);
7645 outs() << format("%02" PRIX32, uuid.uuid[4]);
7646 outs() << format("%02" PRIX32, uuid.uuid[5]);
7648 outs() << format("%02" PRIX32, uuid.uuid[6]);
7649 outs() << format("%02" PRIX32, uuid.uuid[7]);
7651 outs() << format("%02" PRIX32, uuid.uuid[8]);
7652 outs() << format("%02" PRIX32, uuid.uuid[9]);
7654 outs() << format("%02" PRIX32, uuid.uuid[10]);
7655 outs() << format("%02" PRIX32, uuid.uuid[11]);
7656 outs() << format("%02" PRIX32, uuid.uuid[12]);
7657 outs() << format("%02" PRIX32, uuid.uuid[13]);
7658 outs() << format("%02" PRIX32, uuid.uuid[14]);
7659 outs() << format("%02" PRIX32, uuid.uuid[15]);
7663 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
7664 outs() << " cmd LC_RPATH\n";
7665 outs() << " cmdsize " << rpath.cmdsize;
7666 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7667 outs() << " Incorrect size\n";
7670 if (rpath.path >= rpath.cmdsize)
7671 outs() << " path ?(bad offset " << rpath.path << ")\n";
7673 const char *P = (const char *)(Ptr) + rpath.path;
7674 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7678 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
7679 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
7680 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
7681 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
7682 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
7684 outs() << " cmd " << vd.cmd << " (?)\n";
7685 outs() << " cmdsize " << vd.cmdsize;
7686 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7687 outs() << " Incorrect size\n";
7690 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
7691 << ((vd.version >> 8) & 0xff);
7692 if ((vd.version & 0xff) != 0)
7693 outs() << "." << (vd.version & 0xff);
7696 outs() << " sdk n/a";
7698 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
7699 << ((vd.sdk >> 8) & 0xff);
7701 if ((vd.sdk & 0xff) != 0)
7702 outs() << "." << (vd.sdk & 0xff);
7706 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7707 outs() << " cmd LC_SOURCE_VERSION\n";
7708 outs() << " cmdsize " << sd.cmdsize;
7709 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7710 outs() << " Incorrect size\n";
7713 uint64_t a = (sd.version >> 40) & 0xffffff;
7714 uint64_t b = (sd.version >> 30) & 0x3ff;
7715 uint64_t c = (sd.version >> 20) & 0x3ff;
7716 uint64_t d = (sd.version >> 10) & 0x3ff;
7717 uint64_t e = sd.version & 0x3ff;
7718 outs() << " version " << a << "." << b;
7720 outs() << "." << c << "." << d << "." << e;
7722 outs() << "." << c << "." << d;
7728 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7729 outs() << " cmd LC_MAIN\n";
7730 outs() << " cmdsize " << ep.cmdsize;
7731 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7732 outs() << " Incorrect size\n";
7735 outs() << " entryoff " << ep.entryoff << "\n";
7736 outs() << " stacksize " << ep.stacksize << "\n";
7739 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7740 uint32_t object_size) {
7741 outs() << " cmd LC_ENCRYPTION_INFO\n";
7742 outs() << " cmdsize " << ec.cmdsize;
7743 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7744 outs() << " Incorrect size\n";
7747 outs() << " cryptoff " << ec.cryptoff;
7748 if (ec.cryptoff > object_size)
7749 outs() << " (past end of file)\n";
7752 outs() << " cryptsize " << ec.cryptsize;
7753 if (ec.cryptsize > object_size)
7754 outs() << " (past end of file)\n";
7757 outs() << " cryptid " << ec.cryptid << "\n";
7760 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
7761 uint32_t object_size) {
7762 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7763 outs() << " cmdsize " << ec.cmdsize;
7764 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7765 outs() << " Incorrect size\n";
7768 outs() << " cryptoff " << ec.cryptoff;
7769 if (ec.cryptoff > object_size)
7770 outs() << " (past end of file)\n";
7773 outs() << " cryptsize " << ec.cryptsize;
7774 if (ec.cryptsize > object_size)
7775 outs() << " (past end of file)\n";
7778 outs() << " cryptid " << ec.cryptid << "\n";
7779 outs() << " pad " << ec.pad << "\n";
7782 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7784 outs() << " cmd LC_LINKER_OPTION\n";
7785 outs() << " cmdsize " << lo.cmdsize;
7786 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7787 outs() << " Incorrect size\n";
7790 outs() << " count " << lo.count << "\n";
7791 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7792 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7795 while (*string == '\0' && left > 0) {
7801 outs() << " string #" << i << " " << format("%.*s\n", left, string);
7802 uint32_t NullPos = StringRef(string, left).find('\0');
7803 uint32_t len = std::min(NullPos, left) + 1;
7809 outs() << " count " << lo.count << " does not match number of strings "
7813 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7815 outs() << " cmd LC_SUB_FRAMEWORK\n";
7816 outs() << " cmdsize " << sub.cmdsize;
7817 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7818 outs() << " Incorrect size\n";
7821 if (sub.umbrella < sub.cmdsize) {
7822 const char *P = Ptr + sub.umbrella;
7823 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7825 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7829 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7831 outs() << " cmd LC_SUB_UMBRELLA\n";
7832 outs() << " cmdsize " << sub.cmdsize;
7833 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7834 outs() << " Incorrect size\n";
7837 if (sub.sub_umbrella < sub.cmdsize) {
7838 const char *P = Ptr + sub.sub_umbrella;
7839 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7841 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7845 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
7847 outs() << " cmd LC_SUB_LIBRARY\n";
7848 outs() << " cmdsize " << sub.cmdsize;
7849 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7850 outs() << " Incorrect size\n";
7853 if (sub.sub_library < sub.cmdsize) {
7854 const char *P = Ptr + sub.sub_library;
7855 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7857 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7861 static void PrintSubClientCommand(MachO::sub_client_command sub,
7863 outs() << " cmd LC_SUB_CLIENT\n";
7864 outs() << " cmdsize " << sub.cmdsize;
7865 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7866 outs() << " Incorrect size\n";
7869 if (sub.client < sub.cmdsize) {
7870 const char *P = Ptr + sub.client;
7871 outs() << " client " << P << " (offset " << sub.client << ")\n";
7873 outs() << " client ?(bad offset " << sub.client << ")\n";
7877 static void PrintRoutinesCommand(MachO::routines_command r) {
7878 outs() << " cmd LC_ROUTINES\n";
7879 outs() << " cmdsize " << r.cmdsize;
7880 if (r.cmdsize != sizeof(struct MachO::routines_command))
7881 outs() << " Incorrect size\n";
7884 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7885 outs() << " init_module " << r.init_module << "\n";
7886 outs() << " reserved1 " << r.reserved1 << "\n";
7887 outs() << " reserved2 " << r.reserved2 << "\n";
7888 outs() << " reserved3 " << r.reserved3 << "\n";
7889 outs() << " reserved4 " << r.reserved4 << "\n";
7890 outs() << " reserved5 " << r.reserved5 << "\n";
7891 outs() << " reserved6 " << r.reserved6 << "\n";
7894 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7895 outs() << " cmd LC_ROUTINES_64\n";
7896 outs() << " cmdsize " << r.cmdsize;
7897 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
7898 outs() << " Incorrect size\n";
7901 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
7902 outs() << " init_module " << r.init_module << "\n";
7903 outs() << " reserved1 " << r.reserved1 << "\n";
7904 outs() << " reserved2 " << r.reserved2 << "\n";
7905 outs() << " reserved3 " << r.reserved3 << "\n";
7906 outs() << " reserved4 " << r.reserved4 << "\n";
7907 outs() << " reserved5 " << r.reserved5 << "\n";
7908 outs() << " reserved6 " << r.reserved6 << "\n";
7911 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
7912 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
7913 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
7914 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
7915 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
7916 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
7917 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
7918 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
7919 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
7920 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
7921 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
7922 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
7923 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
7924 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
7925 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
7926 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
7927 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
7928 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
7929 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
7930 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
7931 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
7932 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
7935 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
7937 outs() << "\t mmst_reg ";
7938 for (f = 0; f < 10; f++)
7939 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
7941 outs() << "\t mmst_rsrv ";
7942 for (f = 0; f < 6; f++)
7943 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
7947 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
7949 outs() << "\t xmm_reg ";
7950 for (f = 0; f < 16; f++)
7951 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
7955 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
7956 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
7957 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
7958 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
7959 outs() << " denorm " << fpu.fpu_fcw.denorm;
7960 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
7961 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
7962 outs() << " undfl " << fpu.fpu_fcw.undfl;
7963 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
7964 outs() << "\t\t pc ";
7965 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
7966 outs() << "FP_PREC_24B ";
7967 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
7968 outs() << "FP_PREC_53B ";
7969 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
7970 outs() << "FP_PREC_64B ";
7972 outs() << fpu.fpu_fcw.pc << " ";
7974 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
7975 outs() << "FP_RND_NEAR ";
7976 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
7977 outs() << "FP_RND_DOWN ";
7978 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
7979 outs() << "FP_RND_UP ";
7980 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
7981 outs() << "FP_CHOP ";
7983 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
7984 outs() << " denorm " << fpu.fpu_fsw.denorm;
7985 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
7986 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
7987 outs() << " undfl " << fpu.fpu_fsw.undfl;
7988 outs() << " precis " << fpu.fpu_fsw.precis;
7989 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
7990 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
7991 outs() << " c0 " << fpu.fpu_fsw.c0;
7992 outs() << " c1 " << fpu.fpu_fsw.c1;
7993 outs() << " c2 " << fpu.fpu_fsw.c2;
7994 outs() << " tos " << fpu.fpu_fsw.tos;
7995 outs() << " c3 " << fpu.fpu_fsw.c3;
7996 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
7997 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
7998 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
7999 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8000 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8001 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8002 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8003 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8004 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8005 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8006 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8007 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8009 outs() << "\t fpu_stmm0:\n";
8010 Print_mmst_reg(fpu.fpu_stmm0);
8011 outs() << "\t fpu_stmm1:\n";
8012 Print_mmst_reg(fpu.fpu_stmm1);
8013 outs() << "\t fpu_stmm2:\n";
8014 Print_mmst_reg(fpu.fpu_stmm2);
8015 outs() << "\t fpu_stmm3:\n";
8016 Print_mmst_reg(fpu.fpu_stmm3);
8017 outs() << "\t fpu_stmm4:\n";
8018 Print_mmst_reg(fpu.fpu_stmm4);
8019 outs() << "\t fpu_stmm5:\n";
8020 Print_mmst_reg(fpu.fpu_stmm5);
8021 outs() << "\t fpu_stmm6:\n";
8022 Print_mmst_reg(fpu.fpu_stmm6);
8023 outs() << "\t fpu_stmm7:\n";
8024 Print_mmst_reg(fpu.fpu_stmm7);
8025 outs() << "\t fpu_xmm0:\n";
8026 Print_xmm_reg(fpu.fpu_xmm0);
8027 outs() << "\t fpu_xmm1:\n";
8028 Print_xmm_reg(fpu.fpu_xmm1);
8029 outs() << "\t fpu_xmm2:\n";
8030 Print_xmm_reg(fpu.fpu_xmm2);
8031 outs() << "\t fpu_xmm3:\n";
8032 Print_xmm_reg(fpu.fpu_xmm3);
8033 outs() << "\t fpu_xmm4:\n";
8034 Print_xmm_reg(fpu.fpu_xmm4);
8035 outs() << "\t fpu_xmm5:\n";
8036 Print_xmm_reg(fpu.fpu_xmm5);
8037 outs() << "\t fpu_xmm6:\n";
8038 Print_xmm_reg(fpu.fpu_xmm6);
8039 outs() << "\t fpu_xmm7:\n";
8040 Print_xmm_reg(fpu.fpu_xmm7);
8041 outs() << "\t fpu_xmm8:\n";
8042 Print_xmm_reg(fpu.fpu_xmm8);
8043 outs() << "\t fpu_xmm9:\n";
8044 Print_xmm_reg(fpu.fpu_xmm9);
8045 outs() << "\t fpu_xmm10:\n";
8046 Print_xmm_reg(fpu.fpu_xmm10);
8047 outs() << "\t fpu_xmm11:\n";
8048 Print_xmm_reg(fpu.fpu_xmm11);
8049 outs() << "\t fpu_xmm12:\n";
8050 Print_xmm_reg(fpu.fpu_xmm12);
8051 outs() << "\t fpu_xmm13:\n";
8052 Print_xmm_reg(fpu.fpu_xmm13);
8053 outs() << "\t fpu_xmm14:\n";
8054 Print_xmm_reg(fpu.fpu_xmm14);
8055 outs() << "\t fpu_xmm15:\n";
8056 Print_xmm_reg(fpu.fpu_xmm15);
8057 outs() << "\t fpu_rsrv4:\n";
8058 for (uint32_t f = 0; f < 6; f++) {
8060 for (uint32_t g = 0; g < 16; g++)
8061 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
8064 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8068 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8069 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8070 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8071 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8074 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8075 bool isLittleEndian, uint32_t cputype) {
8076 if (t.cmd == MachO::LC_THREAD)
8077 outs() << " cmd LC_THREAD\n";
8078 else if (t.cmd == MachO::LC_UNIXTHREAD)
8079 outs() << " cmd LC_UNIXTHREAD\n";
8081 outs() << " cmd " << t.cmd << " (unknown)\n";
8082 outs() << " cmdsize " << t.cmdsize;
8083 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8084 outs() << " Incorrect size\n";
8088 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8089 const char *end = Ptr + t.cmdsize;
8090 uint32_t flavor, count, left;
8091 if (cputype == MachO::CPU_TYPE_X86_64) {
8092 while (begin < end) {
8093 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8094 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8095 begin += sizeof(uint32_t);
8100 if (isLittleEndian != sys::IsLittleEndianHost)
8101 sys::swapByteOrder(flavor);
8102 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8103 memcpy((char *)&count, begin, sizeof(uint32_t));
8104 begin += sizeof(uint32_t);
8109 if (isLittleEndian != sys::IsLittleEndianHost)
8110 sys::swapByteOrder(count);
8111 if (flavor == MachO::x86_THREAD_STATE64) {
8112 outs() << " flavor x86_THREAD_STATE64\n";
8113 if (count == MachO::x86_THREAD_STATE64_COUNT)
8114 outs() << " count x86_THREAD_STATE64_COUNT\n";
8116 outs() << " count " << count
8117 << " (not x86_THREAD_STATE64_COUNT)\n";
8118 MachO::x86_thread_state64_t cpu64;
8120 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8121 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8122 begin += sizeof(MachO::x86_thread_state64_t);
8124 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8125 memcpy(&cpu64, begin, left);
8128 if (isLittleEndian != sys::IsLittleEndianHost)
8130 Print_x86_thread_state64_t(cpu64);
8131 } else if (flavor == MachO::x86_THREAD_STATE) {
8132 outs() << " flavor x86_THREAD_STATE\n";
8133 if (count == MachO::x86_THREAD_STATE_COUNT)
8134 outs() << " count x86_THREAD_STATE_COUNT\n";
8136 outs() << " count " << count
8137 << " (not x86_THREAD_STATE_COUNT)\n";
8138 struct MachO::x86_thread_state_t ts;
8140 if (left >= sizeof(MachO::x86_thread_state_t)) {
8141 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8142 begin += sizeof(MachO::x86_thread_state_t);
8144 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8145 memcpy(&ts, begin, left);
8148 if (isLittleEndian != sys::IsLittleEndianHost)
8150 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8151 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8152 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8153 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8155 outs() << "tsh.count " << ts.tsh.count
8156 << " (not x86_THREAD_STATE64_COUNT\n";
8157 Print_x86_thread_state64_t(ts.uts.ts64);
8159 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8160 << ts.tsh.count << "\n";
8162 } else if (flavor == MachO::x86_FLOAT_STATE) {
8163 outs() << " flavor x86_FLOAT_STATE\n";
8164 if (count == MachO::x86_FLOAT_STATE_COUNT)
8165 outs() << " count x86_FLOAT_STATE_COUNT\n";
8167 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
8168 struct MachO::x86_float_state_t fs;
8170 if (left >= sizeof(MachO::x86_float_state_t)) {
8171 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8172 begin += sizeof(MachO::x86_float_state_t);
8174 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8175 memcpy(&fs, begin, left);
8178 if (isLittleEndian != sys::IsLittleEndianHost)
8180 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8181 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
8182 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
8183 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8185 outs() << "fsh.count " << fs.fsh.count
8186 << " (not x86_FLOAT_STATE64_COUNT\n";
8187 Print_x86_float_state_t(fs.ufs.fs64);
8189 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8190 << fs.fsh.count << "\n";
8192 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8193 outs() << " flavor x86_EXCEPTION_STATE\n";
8194 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8195 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8197 outs() << " count " << count
8198 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8199 struct MachO::x86_exception_state_t es;
8201 if (left >= sizeof(MachO::x86_exception_state_t)) {
8202 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8203 begin += sizeof(MachO::x86_exception_state_t);
8205 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8206 memcpy(&es, begin, left);
8209 if (isLittleEndian != sys::IsLittleEndianHost)
8211 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8212 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
8213 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
8214 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8216 outs() << "\t esh.count " << es.esh.count
8217 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8218 Print_x86_exception_state_t(es.ues.es64);
8220 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8221 << es.esh.count << "\n";
8224 outs() << " flavor " << flavor << " (unknown)\n";
8225 outs() << " count " << count << "\n";
8226 outs() << " state (unknown)\n";
8227 begin += count * sizeof(uint32_t);
8231 while (begin < end) {
8232 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8233 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8234 begin += sizeof(uint32_t);
8239 if (isLittleEndian != sys::IsLittleEndianHost)
8240 sys::swapByteOrder(flavor);
8241 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8242 memcpy((char *)&count, begin, sizeof(uint32_t));
8243 begin += sizeof(uint32_t);
8248 if (isLittleEndian != sys::IsLittleEndianHost)
8249 sys::swapByteOrder(count);
8250 outs() << " flavor " << flavor << "\n";
8251 outs() << " count " << count << "\n";
8252 outs() << " state (Unknown cputype/cpusubtype)\n";
8253 begin += count * sizeof(uint32_t);
8258 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8259 if (dl.cmd == MachO::LC_ID_DYLIB)
8260 outs() << " cmd LC_ID_DYLIB\n";
8261 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8262 outs() << " cmd LC_LOAD_DYLIB\n";
8263 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8264 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8265 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8266 outs() << " cmd LC_REEXPORT_DYLIB\n";
8267 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8268 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8269 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8270 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8272 outs() << " cmd " << dl.cmd << " (unknown)\n";
8273 outs() << " cmdsize " << dl.cmdsize;
8274 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8275 outs() << " Incorrect size\n";
8278 if (dl.dylib.name < dl.cmdsize) {
8279 const char *P = (const char *)(Ptr) + dl.dylib.name;
8280 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8282 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8284 outs() << " time stamp " << dl.dylib.timestamp << " ";
8285 time_t t = dl.dylib.timestamp;
8286 outs() << ctime(&t);
8287 outs() << " current version ";
8288 if (dl.dylib.current_version == 0xffffffff)
8291 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8292 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8293 << (dl.dylib.current_version & 0xff) << "\n";
8294 outs() << "compatibility version ";
8295 if (dl.dylib.compatibility_version == 0xffffffff)
8298 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8299 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8300 << (dl.dylib.compatibility_version & 0xff) << "\n";
8303 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8304 uint32_t object_size) {
8305 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8306 outs() << " cmd LC_FUNCTION_STARTS\n";
8307 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8308 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8309 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8310 outs() << " cmd LC_FUNCTION_STARTS\n";
8311 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8312 outs() << " cmd LC_DATA_IN_CODE\n";
8313 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8314 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8315 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8316 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8318 outs() << " cmd " << ld.cmd << " (?)\n";
8319 outs() << " cmdsize " << ld.cmdsize;
8320 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8321 outs() << " Incorrect size\n";
8324 outs() << " dataoff " << ld.dataoff;
8325 if (ld.dataoff > object_size)
8326 outs() << " (past end of file)\n";
8329 outs() << " datasize " << ld.datasize;
8330 uint64_t big_size = ld.dataoff;
8331 big_size += ld.datasize;
8332 if (big_size > object_size)
8333 outs() << " (past end of file)\n";
8338 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8339 uint32_t cputype, bool verbose) {
8340 StringRef Buf = Obj->getData();
8342 for (const auto &Command : Obj->load_commands()) {
8343 outs() << "Load command " << Index++ << "\n";
8344 if (Command.C.cmd == MachO::LC_SEGMENT) {
8345 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8346 const char *sg_segname = SLC.segname;
8347 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8348 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8349 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8351 for (unsigned j = 0; j < SLC.nsects; j++) {
8352 MachO::section S = Obj->getSection(Command, j);
8353 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8354 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8355 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8357 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8358 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8359 const char *sg_segname = SLC_64.segname;
8360 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8361 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8362 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8363 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8364 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8365 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8366 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8367 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8368 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8369 sg_segname, filetype, Buf.size(), verbose);
8371 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8372 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8373 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
8374 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8375 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8376 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8377 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8379 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8380 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8381 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8382 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8383 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8384 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8385 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8386 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8387 PrintDyldLoadCommand(Dyld, Command.Ptr);
8388 } else if (Command.C.cmd == MachO::LC_UUID) {
8389 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8390 PrintUuidLoadCommand(Uuid);
8391 } else if (Command.C.cmd == MachO::LC_RPATH) {
8392 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8393 PrintRpathLoadCommand(Rpath, Command.Ptr);
8394 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
8395 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
8396 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8397 PrintVersionMinLoadCommand(Vd);
8398 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8399 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8400 PrintSourceVersionCommand(Sd);
8401 } else if (Command.C.cmd == MachO::LC_MAIN) {
8402 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8403 PrintEntryPointCommand(Ep);
8404 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
8405 MachO::encryption_info_command Ei =
8406 Obj->getEncryptionInfoCommand(Command);
8407 PrintEncryptionInfoCommand(Ei, Buf.size());
8408 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
8409 MachO::encryption_info_command_64 Ei =
8410 Obj->getEncryptionInfoCommand64(Command);
8411 PrintEncryptionInfoCommand64(Ei, Buf.size());
8412 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
8413 MachO::linker_option_command Lo =
8414 Obj->getLinkerOptionLoadCommand(Command);
8415 PrintLinkerOptionCommand(Lo, Command.Ptr);
8416 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8417 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8418 PrintSubFrameworkCommand(Sf, Command.Ptr);
8419 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8420 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8421 PrintSubUmbrellaCommand(Sf, Command.Ptr);
8422 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8423 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8424 PrintSubLibraryCommand(Sl, Command.Ptr);
8425 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8426 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8427 PrintSubClientCommand(Sc, Command.Ptr);
8428 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8429 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8430 PrintRoutinesCommand(Rc);
8431 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8432 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8433 PrintRoutinesCommand64(Rc);
8434 } else if (Command.C.cmd == MachO::LC_THREAD ||
8435 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8436 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8437 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
8438 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8439 Command.C.cmd == MachO::LC_ID_DYLIB ||
8440 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8441 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8442 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8443 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
8444 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8445 PrintDylibCommand(Dl, Command.Ptr);
8446 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8447 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8448 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8449 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8450 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8451 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8452 MachO::linkedit_data_command Ld =
8453 Obj->getLinkeditDataLoadCommand(Command);
8454 PrintLinkEditDataCommand(Ld, Buf.size());
8456 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8458 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8459 // TODO: get and print the raw bytes of the load command.
8461 // TODO: print all the other kinds of load commands.
8465 static void getAndPrintMachHeader(const MachOObjectFile *Obj,
8466 uint32_t &filetype, uint32_t &cputype,
8468 if (Obj->is64Bit()) {
8469 MachO::mach_header_64 H_64;
8470 H_64 = Obj->getHeader64();
8471 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8472 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8473 filetype = H_64.filetype;
8474 cputype = H_64.cputype;
8476 MachO::mach_header H;
8477 H = Obj->getHeader();
8478 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8479 H.sizeofcmds, H.flags, verbose);
8480 filetype = H.filetype;
8481 cputype = H.cputype;
8485 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8486 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
8487 uint32_t filetype = 0;
8488 uint32_t cputype = 0;
8489 getAndPrintMachHeader(file, filetype, cputype, !NonVerbose);
8490 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
8493 //===----------------------------------------------------------------------===//
8494 // export trie dumping
8495 //===----------------------------------------------------------------------===//
8497 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
8498 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8499 uint64_t Flags = Entry.flags();
8500 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8501 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8502 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8503 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8504 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8505 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8506 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8508 outs() << "[re-export] ";
8510 outs() << format("0x%08llX ",
8511 Entry.address()); // FIXME:add in base address
8512 outs() << Entry.name();
8513 if (WeakDef || ThreadLocal || Resolver || Abs) {
8514 bool NeedsComma = false;
8517 outs() << "weak_def";
8523 outs() << "per-thread";
8529 outs() << "absolute";
8535 outs() << format("resolver=0x%08llX", Entry.other());
8541 StringRef DylibName = "unknown";
8542 int Ordinal = Entry.other() - 1;
8543 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8544 if (Entry.otherName().empty())
8545 outs() << " (from " << DylibName << ")";
8547 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
8553 //===----------------------------------------------------------------------===//
8554 // rebase table dumping
8555 //===----------------------------------------------------------------------===//
8560 SegInfo(const object::MachOObjectFile *Obj);
8562 StringRef segmentName(uint32_t SegIndex);
8563 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8564 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
8567 struct SectionInfo {
8570 StringRef SectionName;
8571 StringRef SegmentName;
8572 uint64_t OffsetInSegment;
8573 uint64_t SegmentStartAddress;
8574 uint32_t SegmentIndex;
8576 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8577 SmallVector<SectionInfo, 32> Sections;
8581 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8582 // Build table of sections so segIndex/offset pairs can be translated.
8583 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
8584 StringRef CurSegName;
8585 uint64_t CurSegAddress;
8586 for (const SectionRef &Section : Obj->sections()) {
8588 if (error(Section.getName(Info.SectionName)))
8590 Info.Address = Section.getAddress();
8591 Info.Size = Section.getSize();
8593 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8594 if (!Info.SegmentName.equals(CurSegName)) {
8596 CurSegName = Info.SegmentName;
8597 CurSegAddress = Info.Address;
8599 Info.SegmentIndex = CurSegIndex - 1;
8600 Info.OffsetInSegment = Info.Address - CurSegAddress;
8601 Info.SegmentStartAddress = CurSegAddress;
8602 Sections.push_back(Info);
8606 StringRef SegInfo::segmentName(uint32_t SegIndex) {
8607 for (const SectionInfo &SI : Sections) {
8608 if (SI.SegmentIndex == SegIndex)
8609 return SI.SegmentName;
8611 llvm_unreachable("invalid segIndex");
8614 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8615 uint64_t OffsetInSeg) {
8616 for (const SectionInfo &SI : Sections) {
8617 if (SI.SegmentIndex != SegIndex)
8619 if (SI.OffsetInSegment > OffsetInSeg)
8621 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8625 llvm_unreachable("segIndex and offset not in any section");
8628 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8629 return findSection(SegIndex, OffsetInSeg).SectionName;
8632 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8633 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8634 return SI.SegmentStartAddress + OffsetInSeg;
8637 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8638 // Build table of sections so names can used in final output.
8639 SegInfo sectionTable(Obj);
8641 outs() << "segment section address type\n";
8642 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8643 uint32_t SegIndex = Entry.segmentIndex();
8644 uint64_t OffsetInSeg = Entry.segmentOffset();
8645 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8646 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8647 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8649 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
8650 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8651 SegmentName.str().c_str(), SectionName.str().c_str(),
8652 Address, Entry.typeName().str().c_str());
8656 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8657 StringRef DylibName;
8659 case MachO::BIND_SPECIAL_DYLIB_SELF:
8660 return "this-image";
8661 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8662 return "main-executable";
8663 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8664 return "flat-namespace";
8667 std::error_code EC =
8668 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
8670 return "<<bad library ordinal>>";
8674 return "<<unknown special ordinal>>";
8677 //===----------------------------------------------------------------------===//
8678 // bind table dumping
8679 //===----------------------------------------------------------------------===//
8681 void llvm::printMachOBindTable(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 type "
8686 "addend dylib symbol\n";
8687 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
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 pointer 0 libSystem ___stack_chk_guard
8697 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
8698 Attr = " (weak_import)";
8699 outs() << left_justify(SegmentName, 8) << " "
8700 << left_justify(SectionName, 18) << " "
8701 << format_hex(Address, 10, true) << " "
8702 << left_justify(Entry.typeName(), 8) << " "
8703 << format_decimal(Entry.addend(), 8) << " "
8704 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8705 << Entry.symbolName() << Attr << "\n";
8709 //===----------------------------------------------------------------------===//
8710 // lazy bind table dumping
8711 //===----------------------------------------------------------------------===//
8713 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8714 // Build table of sections so names can used in final output.
8715 SegInfo sectionTable(Obj);
8717 outs() << "segment section address "
8719 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8720 uint32_t SegIndex = Entry.segmentIndex();
8721 uint64_t OffsetInSeg = Entry.segmentOffset();
8722 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8723 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8724 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8726 // Table lines look like:
8727 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
8728 outs() << left_justify(SegmentName, 8) << " "
8729 << left_justify(SectionName, 18) << " "
8730 << format_hex(Address, 10, true) << " "
8731 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8732 << Entry.symbolName() << "\n";
8736 //===----------------------------------------------------------------------===//
8737 // weak bind table dumping
8738 //===----------------------------------------------------------------------===//
8740 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8741 // Build table of sections so names can used in final output.
8742 SegInfo sectionTable(Obj);
8744 outs() << "segment section address "
8745 "type addend symbol\n";
8746 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8747 // Strong symbols don't have a location to update.
8748 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
8749 outs() << " strong "
8750 << Entry.symbolName() << "\n";
8753 uint32_t SegIndex = Entry.segmentIndex();
8754 uint64_t OffsetInSeg = Entry.segmentOffset();
8755 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8756 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8757 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8759 // Table lines look like:
8760 // __DATA __data 0x00001000 pointer 0 _foo
8761 outs() << left_justify(SegmentName, 8) << " "
8762 << left_justify(SectionName, 18) << " "
8763 << format_hex(Address, 10, true) << " "
8764 << left_justify(Entry.typeName(), 8) << " "
8765 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8770 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
8771 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8772 // information for that address. If the address is found its binding symbol
8773 // name is returned. If not nullptr is returned.
8774 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8775 struct DisassembleInfo *info) {
8776 if (info->bindtable == nullptr) {
8777 info->bindtable = new (BindTable);
8778 SegInfo sectionTable(info->O);
8779 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8780 uint32_t SegIndex = Entry.segmentIndex();
8781 uint64_t OffsetInSeg = Entry.segmentOffset();
8782 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8783 const char *SymbolName = nullptr;
8784 StringRef name = Entry.symbolName();
8786 SymbolName = name.data();
8787 info->bindtable->push_back(std::make_pair(Address, SymbolName));
8790 for (bind_table_iterator BI = info->bindtable->begin(),
8791 BE = info->bindtable->end();
8793 uint64_t Address = BI->first;
8794 if (ReferenceValue == Address) {
8795 const char *SymbolName = BI->second;