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/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/DebugInfo/DIContext.h"
22 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCDisassembler.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstPrinter.h"
28 #include "llvm/MC/MCInstrDesc.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/Object/MachO.h"
33 #include "llvm/Object/MachOUniversal.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Endian.h"
38 #include "llvm/Support/Format.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/GraphWriter.h"
41 #include "llvm/Support/LEB128.h"
42 #include "llvm/Support/MachO.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/raw_ostream.h"
49 #include <system_error>
56 using namespace object;
60 cl::desc("Print line information from debug info if available"));
62 static cl::opt<std::string> DSYMFile("dsym",
63 cl::desc("Use .dSYM file for debug info"));
65 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
66 cl::desc("Print full leading address"));
68 static cl::opt<bool> NoLeadingAddr("no-leading-addr",
69 cl::desc("Print no leading address"));
71 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
72 cl::desc("Print Mach-O universal headers "
73 "(requires -macho)"));
76 llvm::ArchiveHeaders("archive-headers",
77 cl::desc("Print archive headers for Mach-O archives "
78 "(requires -macho)"));
81 ArchiveMemberOffsets("archive-member-offsets",
82 cl::desc("Print the offset to each archive member for "
83 "Mach-O archives (requires -macho and "
84 "-archive-headers)"));
87 llvm::IndirectSymbols("indirect-symbols",
88 cl::desc("Print indirect symbol table for Mach-O "
89 "objects (requires -macho)"));
92 llvm::DataInCode("data-in-code",
93 cl::desc("Print the data in code table for Mach-O objects "
94 "(requires -macho)"));
97 llvm::LinkOptHints("link-opt-hints",
98 cl::desc("Print the linker optimization hints for "
99 "Mach-O objects (requires -macho)"));
102 llvm::InfoPlist("info-plist",
103 cl::desc("Print the info plist section as strings for "
104 "Mach-O objects (requires -macho)"));
107 llvm::DylibsUsed("dylibs-used",
108 cl::desc("Print the shared libraries used for linked "
109 "Mach-O files (requires -macho)"));
112 llvm::DylibId("dylib-id",
113 cl::desc("Print the shared library's id for the dylib Mach-O "
114 "file (requires -macho)"));
117 llvm::NonVerbose("non-verbose",
118 cl::desc("Print the info for Mach-O objects in "
119 "non-verbose or numeric form (requires -macho)"));
122 llvm::ObjcMetaData("objc-meta-data",
123 cl::desc("Print the Objective-C runtime meta data for "
124 "Mach-O files (requires -macho)"));
126 cl::opt<std::string> llvm::DisSymName(
128 cl::desc("disassemble just this symbol's instructions (requires -macho"));
130 static cl::opt<bool> NoSymbolicOperands(
131 "no-symbolic-operands",
132 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
134 static cl::list<std::string>
135 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
138 bool ArchAll = false;
140 static std::string ThumbTripleName;
142 static const Target *GetTarget(const MachOObjectFile *MachOObj,
143 const char **McpuDefault,
144 const Target **ThumbTarget) {
145 // Figure out the target triple.
146 if (TripleName.empty()) {
147 llvm::Triple TT("unknown-unknown-unknown");
148 llvm::Triple ThumbTriple = Triple();
149 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
150 TripleName = TT.str();
151 ThumbTripleName = ThumbTriple.str();
154 // Get the target specific parser.
156 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
157 if (TheTarget && ThumbTripleName.empty())
160 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
164 errs() << "llvm-objdump: error: unable to get target for '";
166 errs() << TripleName;
168 errs() << ThumbTripleName;
169 errs() << "', see --version and --triple.\n";
173 struct SymbolSorter {
174 bool operator()(const SymbolRef &A, const SymbolRef &B) {
175 uint64_t AAddr = (A.getType() != SymbolRef::ST_Function) ? 0 : A.getValue();
176 uint64_t BAddr = (B.getType() != SymbolRef::ST_Function) ? 0 : B.getValue();
177 return AAddr < BAddr;
181 // Types for the storted data in code table that is built before disassembly
182 // and the predicate function to sort them.
183 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
184 typedef std::vector<DiceTableEntry> DiceTable;
185 typedef DiceTable::iterator dice_table_iterator;
187 // This is used to search for a data in code table entry for the PC being
188 // disassembled. The j parameter has the PC in j.first. A single data in code
189 // table entry can cover many bytes for each of its Kind's. So if the offset,
190 // aka the i.first value, of the data in code table entry plus its Length
191 // covers the PC being searched for this will return true. If not it will
193 static bool compareDiceTableEntries(const DiceTableEntry &i,
194 const DiceTableEntry &j) {
196 i.second.getLength(Length);
198 return j.first >= i.first && j.first < i.first + Length;
201 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
202 unsigned short Kind) {
203 uint32_t Value, Size = 1;
207 case MachO::DICE_KIND_DATA:
210 dumpBytes(makeArrayRef(bytes, 4), outs());
211 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
212 outs() << "\t.long " << Value;
214 } else if (Length >= 2) {
216 dumpBytes(makeArrayRef(bytes, 2), outs());
217 Value = bytes[1] << 8 | bytes[0];
218 outs() << "\t.short " << Value;
222 dumpBytes(makeArrayRef(bytes, 2), outs());
224 outs() << "\t.byte " << Value;
227 if (Kind == MachO::DICE_KIND_DATA)
228 outs() << "\t@ KIND_DATA\n";
230 outs() << "\t@ data in code kind = " << Kind << "\n";
232 case MachO::DICE_KIND_JUMP_TABLE8:
234 dumpBytes(makeArrayRef(bytes, 1), outs());
236 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
239 case MachO::DICE_KIND_JUMP_TABLE16:
241 dumpBytes(makeArrayRef(bytes, 2), outs());
242 Value = bytes[1] << 8 | bytes[0];
243 outs() << "\t.short " << format("%5u", Value & 0xffff)
244 << "\t@ KIND_JUMP_TABLE16\n";
247 case MachO::DICE_KIND_JUMP_TABLE32:
248 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
250 dumpBytes(makeArrayRef(bytes, 4), outs());
251 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
252 outs() << "\t.long " << Value;
253 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
254 outs() << "\t@ KIND_JUMP_TABLE32\n";
256 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
263 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
264 std::vector<SectionRef> &Sections,
265 std::vector<SymbolRef> &Symbols,
266 SmallVectorImpl<uint64_t> &FoundFns,
267 uint64_t &BaseSegmentAddress) {
268 for (const SymbolRef &Symbol : MachOObj->symbols()) {
269 ErrorOr<StringRef> SymName = Symbol.getName();
270 if (std::error_code EC = SymName.getError())
271 report_fatal_error(EC.message());
272 if (!SymName->startswith("ltmp"))
273 Symbols.push_back(Symbol);
276 for (const SectionRef &Section : MachOObj->sections()) {
278 Section.getName(SectName);
279 Sections.push_back(Section);
282 bool BaseSegmentAddressSet = false;
283 for (const auto &Command : MachOObj->load_commands()) {
284 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
285 // We found a function starts segment, parse the addresses for later
287 MachO::linkedit_data_command LLC =
288 MachOObj->getLinkeditDataLoadCommand(Command);
290 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
291 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
292 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
293 StringRef SegName = SLC.segname;
294 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
295 BaseSegmentAddressSet = true;
296 BaseSegmentAddress = SLC.vmaddr;
302 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
303 uint32_t n, uint32_t count,
304 uint32_t stride, uint64_t addr) {
305 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
306 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
307 if (n > nindirectsyms)
308 outs() << " (entries start past the end of the indirect symbol "
309 "table) (reserved1 field greater than the table size)";
310 else if (n + count > nindirectsyms)
311 outs() << " (entries extends past the end of the indirect symbol "
314 uint32_t cputype = O->getHeader().cputype;
315 if (cputype & MachO::CPU_ARCH_ABI64)
316 outs() << "address index";
318 outs() << "address index";
323 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
324 if (cputype & MachO::CPU_ARCH_ABI64)
325 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
327 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
328 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
329 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
330 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
334 if (indirect_symbol ==
335 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
336 outs() << "LOCAL ABSOLUTE\n";
339 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
340 outs() << "ABSOLUTE\n";
343 outs() << format("%5u ", indirect_symbol);
345 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
346 if (indirect_symbol < Symtab.nsyms) {
347 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
348 SymbolRef Symbol = *Sym;
349 ErrorOr<StringRef> SymName = Symbol.getName();
350 if (std::error_code EC = SymName.getError())
351 report_fatal_error(EC.message());
361 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
362 for (const auto &Load : O->load_commands()) {
363 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
364 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
365 for (unsigned J = 0; J < Seg.nsects; ++J) {
366 MachO::section_64 Sec = O->getSection64(Load, J);
367 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
368 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
369 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
370 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
371 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
372 section_type == MachO::S_SYMBOL_STUBS) {
374 if (section_type == MachO::S_SYMBOL_STUBS)
375 stride = Sec.reserved2;
379 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
380 << Sec.sectname << ") "
381 << "(size of stubs in reserved2 field is zero)\n";
384 uint32_t count = Sec.size / stride;
385 outs() << "Indirect symbols for (" << Sec.segname << ","
386 << Sec.sectname << ") " << count << " entries";
387 uint32_t n = Sec.reserved1;
388 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
391 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
392 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
393 for (unsigned J = 0; J < Seg.nsects; ++J) {
394 MachO::section Sec = O->getSection(Load, J);
395 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
396 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
397 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
398 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
399 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
400 section_type == MachO::S_SYMBOL_STUBS) {
402 if (section_type == MachO::S_SYMBOL_STUBS)
403 stride = Sec.reserved2;
407 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
408 << Sec.sectname << ") "
409 << "(size of stubs in reserved2 field is zero)\n";
412 uint32_t count = Sec.size / stride;
413 outs() << "Indirect symbols for (" << Sec.segname << ","
414 << Sec.sectname << ") " << count << " entries";
415 uint32_t n = Sec.reserved1;
416 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
423 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
424 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
425 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
426 outs() << "Data in code table (" << nentries << " entries)\n";
427 outs() << "offset length kind\n";
428 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
431 DI->getOffset(Offset);
432 outs() << format("0x%08" PRIx32, Offset) << " ";
434 DI->getLength(Length);
435 outs() << format("%6u", Length) << " ";
440 case MachO::DICE_KIND_DATA:
443 case MachO::DICE_KIND_JUMP_TABLE8:
444 outs() << "JUMP_TABLE8";
446 case MachO::DICE_KIND_JUMP_TABLE16:
447 outs() << "JUMP_TABLE16";
449 case MachO::DICE_KIND_JUMP_TABLE32:
450 outs() << "JUMP_TABLE32";
452 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
453 outs() << "ABS_JUMP_TABLE32";
456 outs() << format("0x%04" PRIx32, Kind);
460 outs() << format("0x%04" PRIx32, Kind);
465 static void PrintLinkOptHints(MachOObjectFile *O) {
466 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
467 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
468 uint32_t nloh = LohLC.datasize;
469 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
470 for (uint32_t i = 0; i < nloh;) {
472 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
474 outs() << " identifier " << identifier << " ";
477 switch (identifier) {
479 outs() << "AdrpAdrp\n";
482 outs() << "AdrpLdr\n";
485 outs() << "AdrpAddLdr\n";
488 outs() << "AdrpLdrGotLdr\n";
491 outs() << "AdrpAddStr\n";
494 outs() << "AdrpLdrGotStr\n";
497 outs() << "AdrpAdd\n";
500 outs() << "AdrpLdrGot\n";
503 outs() << "Unknown identifier value\n";
506 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
508 outs() << " narguments " << narguments << "\n";
512 for (uint32_t j = 0; j < narguments; j++) {
513 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
515 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
522 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
524 for (const auto &Load : O->load_commands()) {
525 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
526 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
527 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
528 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
529 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
530 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
531 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
532 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
533 if (dl.dylib.name < dl.cmdsize) {
534 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
539 outs() << " (compatibility version "
540 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
541 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
542 << (dl.dylib.compatibility_version & 0xff) << ",";
543 outs() << " current version "
544 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
545 << ((dl.dylib.current_version >> 8) & 0xff) << "."
546 << (dl.dylib.current_version & 0xff) << ")\n";
549 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
550 if (Load.C.cmd == MachO::LC_ID_DYLIB)
551 outs() << "LC_ID_DYLIB ";
552 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
553 outs() << "LC_LOAD_DYLIB ";
554 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
555 outs() << "LC_LOAD_WEAK_DYLIB ";
556 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
557 outs() << "LC_LAZY_LOAD_DYLIB ";
558 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
559 outs() << "LC_REEXPORT_DYLIB ";
560 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
561 outs() << "LC_LOAD_UPWARD_DYLIB ";
564 outs() << "command " << Index++ << "\n";
570 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
572 static void CreateSymbolAddressMap(MachOObjectFile *O,
573 SymbolAddressMap *AddrMap) {
574 // Create a map of symbol addresses to symbol names.
575 for (const SymbolRef &Symbol : O->symbols()) {
576 SymbolRef::Type ST = Symbol.getType();
577 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
578 ST == SymbolRef::ST_Other) {
579 uint64_t Address = Symbol.getValue();
580 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
581 if (std::error_code EC = SymNameOrErr.getError())
582 report_fatal_error(EC.message());
583 StringRef SymName = *SymNameOrErr;
584 if (!SymName.startswith(".objc"))
585 (*AddrMap)[Address] = SymName;
590 // GuessSymbolName is passed the address of what might be a symbol and a
591 // pointer to the SymbolAddressMap. It returns the name of a symbol
592 // with that address or nullptr if no symbol is found with that address.
593 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
594 const char *SymbolName = nullptr;
595 // A DenseMap can't lookup up some values.
596 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
597 StringRef name = AddrMap->lookup(value);
599 SymbolName = name.data();
604 static void DumpCstringChar(const char c) {
608 outs().write_escaped(p);
611 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
612 uint32_t sect_size, uint64_t sect_addr,
613 bool print_addresses) {
614 for (uint32_t i = 0; i < sect_size; i++) {
615 if (print_addresses) {
617 outs() << format("%016" PRIx64, sect_addr + i) << " ";
619 outs() << format("%08" PRIx64, sect_addr + i) << " ";
621 for (; i < sect_size && sect[i] != '\0'; i++)
622 DumpCstringChar(sect[i]);
623 if (i < sect_size && sect[i] == '\0')
628 static void DumpLiteral4(uint32_t l, float f) {
629 outs() << format("0x%08" PRIx32, l);
630 if ((l & 0x7f800000) != 0x7f800000)
631 outs() << format(" (%.16e)\n", f);
634 outs() << " (+Infinity)\n";
635 else if (l == 0xff800000)
636 outs() << " (-Infinity)\n";
637 else if ((l & 0x00400000) == 0x00400000)
638 outs() << " (non-signaling Not-a-Number)\n";
640 outs() << " (signaling Not-a-Number)\n";
644 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
645 uint32_t sect_size, uint64_t sect_addr,
646 bool print_addresses) {
647 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
648 if (print_addresses) {
650 outs() << format("%016" PRIx64, sect_addr + i) << " ";
652 outs() << format("%08" PRIx64, sect_addr + i) << " ";
655 memcpy(&f, sect + i, sizeof(float));
656 if (O->isLittleEndian() != sys::IsLittleEndianHost)
657 sys::swapByteOrder(f);
659 memcpy(&l, sect + i, sizeof(uint32_t));
660 if (O->isLittleEndian() != sys::IsLittleEndianHost)
661 sys::swapByteOrder(l);
666 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
668 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
670 Hi = (O->isLittleEndian()) ? l1 : l0;
671 Lo = (O->isLittleEndian()) ? l0 : l1;
673 // Hi is the high word, so this is equivalent to if(isfinite(d))
674 if ((Hi & 0x7ff00000) != 0x7ff00000)
675 outs() << format(" (%.16e)\n", d);
677 if (Hi == 0x7ff00000 && Lo == 0)
678 outs() << " (+Infinity)\n";
679 else if (Hi == 0xfff00000 && Lo == 0)
680 outs() << " (-Infinity)\n";
681 else if ((Hi & 0x00080000) == 0x00080000)
682 outs() << " (non-signaling Not-a-Number)\n";
684 outs() << " (signaling Not-a-Number)\n";
688 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
689 uint32_t sect_size, uint64_t sect_addr,
690 bool print_addresses) {
691 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
692 if (print_addresses) {
694 outs() << format("%016" PRIx64, sect_addr + i) << " ";
696 outs() << format("%08" PRIx64, sect_addr + i) << " ";
699 memcpy(&d, sect + i, sizeof(double));
700 if (O->isLittleEndian() != sys::IsLittleEndianHost)
701 sys::swapByteOrder(d);
703 memcpy(&l0, sect + i, sizeof(uint32_t));
704 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
705 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
706 sys::swapByteOrder(l0);
707 sys::swapByteOrder(l1);
709 DumpLiteral8(O, l0, l1, d);
713 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
714 outs() << format("0x%08" PRIx32, l0) << " ";
715 outs() << format("0x%08" PRIx32, l1) << " ";
716 outs() << format("0x%08" PRIx32, l2) << " ";
717 outs() << format("0x%08" PRIx32, l3) << "\n";
720 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
721 uint32_t sect_size, uint64_t sect_addr,
722 bool print_addresses) {
723 for (uint32_t i = 0; i < sect_size; i += 16) {
724 if (print_addresses) {
726 outs() << format("%016" PRIx64, sect_addr + i) << " ";
728 outs() << format("%08" PRIx64, sect_addr + i) << " ";
730 uint32_t l0, l1, l2, l3;
731 memcpy(&l0, sect + i, sizeof(uint32_t));
732 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
733 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
734 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
735 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
736 sys::swapByteOrder(l0);
737 sys::swapByteOrder(l1);
738 sys::swapByteOrder(l2);
739 sys::swapByteOrder(l3);
741 DumpLiteral16(l0, l1, l2, l3);
745 static void DumpLiteralPointerSection(MachOObjectFile *O,
746 const SectionRef &Section,
747 const char *sect, uint32_t sect_size,
749 bool print_addresses) {
750 // Collect the literal sections in this Mach-O file.
751 std::vector<SectionRef> LiteralSections;
752 for (const SectionRef &Section : O->sections()) {
753 DataRefImpl Ref = Section.getRawDataRefImpl();
754 uint32_t section_type;
756 const MachO::section_64 Sec = O->getSection64(Ref);
757 section_type = Sec.flags & MachO::SECTION_TYPE;
759 const MachO::section Sec = O->getSection(Ref);
760 section_type = Sec.flags & MachO::SECTION_TYPE;
762 if (section_type == MachO::S_CSTRING_LITERALS ||
763 section_type == MachO::S_4BYTE_LITERALS ||
764 section_type == MachO::S_8BYTE_LITERALS ||
765 section_type == MachO::S_16BYTE_LITERALS)
766 LiteralSections.push_back(Section);
769 // Set the size of the literal pointer.
770 uint32_t lp_size = O->is64Bit() ? 8 : 4;
772 // Collect the external relocation symbols for the literal pointers.
773 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
774 for (const RelocationRef &Reloc : Section.relocations()) {
776 MachO::any_relocation_info RE;
777 bool isExtern = false;
778 Rel = Reloc.getRawDataRefImpl();
779 RE = O->getRelocation(Rel);
780 isExtern = O->getPlainRelocationExternal(RE);
782 uint64_t RelocOffset = Reloc.getOffset();
783 symbol_iterator RelocSym = Reloc.getSymbol();
784 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
787 array_pod_sort(Relocs.begin(), Relocs.end());
789 // Dump each literal pointer.
790 for (uint32_t i = 0; i < sect_size; i += lp_size) {
791 if (print_addresses) {
793 outs() << format("%016" PRIx64, sect_addr + i) << " ";
795 outs() << format("%08" PRIx64, sect_addr + i) << " ";
799 memcpy(&lp, sect + i, sizeof(uint64_t));
800 if (O->isLittleEndian() != sys::IsLittleEndianHost)
801 sys::swapByteOrder(lp);
804 memcpy(&li, sect + i, sizeof(uint32_t));
805 if (O->isLittleEndian() != sys::IsLittleEndianHost)
806 sys::swapByteOrder(li);
810 // First look for an external relocation entry for this literal pointer.
811 auto Reloc = std::find_if(
812 Relocs.begin(), Relocs.end(),
813 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
814 if (Reloc != Relocs.end()) {
815 symbol_iterator RelocSym = Reloc->second;
816 ErrorOr<StringRef> SymName = RelocSym->getName();
817 if (std::error_code EC = SymName.getError())
818 report_fatal_error(EC.message());
819 outs() << "external relocation entry for symbol:" << *SymName << "\n";
823 // For local references see what the section the literal pointer points to.
824 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
825 [&](const SectionRef &R) {
826 return lp >= R.getAddress() &&
827 lp < R.getAddress() + R.getSize();
829 if (Sect == LiteralSections.end()) {
830 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
834 uint64_t SectAddress = Sect->getAddress();
835 uint64_t SectSize = Sect->getSize();
838 Sect->getName(SectName);
839 DataRefImpl Ref = Sect->getRawDataRefImpl();
840 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
841 outs() << SegmentName << ":" << SectName << ":";
843 uint32_t section_type;
845 const MachO::section_64 Sec = O->getSection64(Ref);
846 section_type = Sec.flags & MachO::SECTION_TYPE;
848 const MachO::section Sec = O->getSection(Ref);
849 section_type = Sec.flags & MachO::SECTION_TYPE;
853 Sect->getContents(BytesStr);
854 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
856 switch (section_type) {
857 case MachO::S_CSTRING_LITERALS:
858 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
860 DumpCstringChar(Contents[i]);
864 case MachO::S_4BYTE_LITERALS:
866 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
868 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
869 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
870 sys::swapByteOrder(f);
871 sys::swapByteOrder(l);
875 case MachO::S_8BYTE_LITERALS: {
877 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
879 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
880 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
882 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
883 sys::swapByteOrder(f);
884 sys::swapByteOrder(l0);
885 sys::swapByteOrder(l1);
887 DumpLiteral8(O, l0, l1, d);
890 case MachO::S_16BYTE_LITERALS: {
891 uint32_t l0, l1, l2, l3;
892 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
893 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
895 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
897 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
899 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
900 sys::swapByteOrder(l0);
901 sys::swapByteOrder(l1);
902 sys::swapByteOrder(l2);
903 sys::swapByteOrder(l3);
905 DumpLiteral16(l0, l1, l2, l3);
912 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
913 uint32_t sect_size, uint64_t sect_addr,
914 SymbolAddressMap *AddrMap,
917 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
918 for (uint32_t i = 0; i < sect_size; i += stride) {
919 const char *SymbolName = nullptr;
921 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
922 uint64_t pointer_value;
923 memcpy(&pointer_value, sect + i, stride);
924 if (O->isLittleEndian() != sys::IsLittleEndianHost)
925 sys::swapByteOrder(pointer_value);
926 outs() << format("0x%016" PRIx64, pointer_value);
928 SymbolName = GuessSymbolName(pointer_value, AddrMap);
930 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
931 uint32_t pointer_value;
932 memcpy(&pointer_value, sect + i, stride);
933 if (O->isLittleEndian() != sys::IsLittleEndianHost)
934 sys::swapByteOrder(pointer_value);
935 outs() << format("0x%08" PRIx32, pointer_value);
937 SymbolName = GuessSymbolName(pointer_value, AddrMap);
940 outs() << " " << SymbolName;
945 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
946 uint32_t size, uint64_t addr) {
947 uint32_t cputype = O->getHeader().cputype;
948 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
950 for (uint32_t i = 0; i < size; i += j, addr += j) {
952 outs() << format("%016" PRIx64, addr) << "\t";
954 outs() << format("%08" PRIx64, addr) << "\t";
955 for (j = 0; j < 16 && i + j < size; j++) {
956 uint8_t byte_word = *(sect + i + j);
957 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
963 for (uint32_t i = 0; i < size; i += j, addr += j) {
965 outs() << format("%016" PRIx64, addr) << "\t";
967 outs() << format("%08" PRIx64, sect) << "\t";
968 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
969 j += sizeof(int32_t)) {
970 if (i + j + sizeof(int32_t) < size) {
972 memcpy(&long_word, sect + i + j, sizeof(int32_t));
973 if (O->isLittleEndian() != sys::IsLittleEndianHost)
974 sys::swapByteOrder(long_word);
975 outs() << format("%08" PRIx32, long_word) << " ";
977 for (uint32_t k = 0; i + j + k < size; k++) {
978 uint8_t byte_word = *(sect + i + j);
979 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
988 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
989 StringRef DisSegName, StringRef DisSectName);
990 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
991 uint32_t size, uint32_t addr);
993 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
995 SymbolAddressMap AddrMap;
997 CreateSymbolAddressMap(O, &AddrMap);
999 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1000 StringRef DumpSection = FilterSections[i];
1001 std::pair<StringRef, StringRef> DumpSegSectName;
1002 DumpSegSectName = DumpSection.split(',');
1003 StringRef DumpSegName, DumpSectName;
1004 if (DumpSegSectName.second.size()) {
1005 DumpSegName = DumpSegSectName.first;
1006 DumpSectName = DumpSegSectName.second;
1009 DumpSectName = DumpSegSectName.first;
1011 for (const SectionRef &Section : O->sections()) {
1013 Section.getName(SectName);
1014 DataRefImpl Ref = Section.getRawDataRefImpl();
1015 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1016 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1017 (SectName == DumpSectName)) {
1019 uint32_t section_flags;
1021 const MachO::section_64 Sec = O->getSection64(Ref);
1022 section_flags = Sec.flags;
1025 const MachO::section Sec = O->getSection(Ref);
1026 section_flags = Sec.flags;
1028 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1031 Section.getContents(BytesStr);
1032 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1033 uint32_t sect_size = BytesStr.size();
1034 uint64_t sect_addr = Section.getAddress();
1036 outs() << "Contents of (" << SegName << "," << SectName
1040 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1041 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1042 DisassembleMachO(Filename, O, SegName, SectName);
1045 if (SegName == "__TEXT" && SectName == "__info_plist") {
1049 if (SegName == "__OBJC" && SectName == "__protocol") {
1050 DumpProtocolSection(O, sect, sect_size, sect_addr);
1053 switch (section_type) {
1054 case MachO::S_REGULAR:
1055 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1057 case MachO::S_ZEROFILL:
1058 outs() << "zerofill section and has no contents in the file\n";
1060 case MachO::S_CSTRING_LITERALS:
1061 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1063 case MachO::S_4BYTE_LITERALS:
1064 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1066 case MachO::S_8BYTE_LITERALS:
1067 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1069 case MachO::S_16BYTE_LITERALS:
1070 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1072 case MachO::S_LITERAL_POINTERS:
1073 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1076 case MachO::S_MOD_INIT_FUNC_POINTERS:
1077 case MachO::S_MOD_TERM_FUNC_POINTERS:
1078 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1082 outs() << "Unknown section type ("
1083 << format("0x%08" PRIx32, section_type) << ")\n";
1084 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1088 if (section_type == MachO::S_ZEROFILL)
1089 outs() << "zerofill section and has no contents in the file\n";
1091 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1098 static void DumpInfoPlistSectionContents(StringRef Filename,
1099 MachOObjectFile *O) {
1100 for (const SectionRef &Section : O->sections()) {
1102 Section.getName(SectName);
1103 DataRefImpl Ref = Section.getRawDataRefImpl();
1104 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1105 if (SegName == "__TEXT" && SectName == "__info_plist") {
1106 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1108 Section.getContents(BytesStr);
1109 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1116 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1117 // and if it is and there is a list of architecture flags is specified then
1118 // check to make sure this Mach-O file is one of those architectures or all
1119 // architectures were specified. If not then an error is generated and this
1120 // routine returns false. Else it returns true.
1121 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1122 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1123 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1124 bool ArchFound = false;
1125 MachO::mach_header H;
1126 MachO::mach_header_64 H_64;
1128 if (MachO->is64Bit()) {
1129 H_64 = MachO->MachOObjectFile::getHeader64();
1130 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1132 H = MachO->MachOObjectFile::getHeader();
1133 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1136 for (i = 0; i < ArchFlags.size(); ++i) {
1137 if (ArchFlags[i] == T.getArchName())
1142 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1143 << "architecture: " + ArchFlags[i] + "\n";
1150 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1152 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1153 // archive member and or in a slice of a universal file. It prints the
1154 // the file name and header info and then processes it according to the
1155 // command line options.
1156 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1157 StringRef ArchiveMemberName = StringRef(),
1158 StringRef ArchitectureName = StringRef()) {
1159 // If we are doing some processing here on the Mach-O file print the header
1160 // info. And don't print it otherwise like in the case of printing the
1161 // UniversalHeaders or ArchiveHeaders.
1162 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
1163 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1164 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
1166 if (!ArchiveMemberName.empty())
1167 outs() << '(' << ArchiveMemberName << ')';
1168 if (!ArchitectureName.empty())
1169 outs() << " (architecture " << ArchitectureName << ")";
1174 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1175 if (IndirectSymbols)
1176 PrintIndirectSymbols(MachOOF, !NonVerbose);
1178 PrintDataInCodeTable(MachOOF, !NonVerbose);
1180 PrintLinkOptHints(MachOOF);
1182 PrintRelocations(MachOOF);
1184 PrintSectionHeaders(MachOOF);
1185 if (SectionContents)
1186 PrintSectionContents(MachOOF);
1187 if (FilterSections.size() != 0)
1188 DumpSectionContents(Filename, MachOOF, !NonVerbose);
1190 DumpInfoPlistSectionContents(Filename, MachOOF);
1192 PrintDylibs(MachOOF, false);
1194 PrintDylibs(MachOOF, true);
1196 PrintSymbolTable(MachOOF);
1198 printMachOUnwindInfo(MachOOF);
1200 printMachOFileHeader(MachOOF);
1202 printObjcMetaData(MachOOF, !NonVerbose);
1204 printExportsTrie(MachOOF);
1206 printRebaseTable(MachOOF);
1208 printBindTable(MachOOF);
1210 printLazyBindTable(MachOOF);
1212 printWeakBindTable(MachOOF);
1215 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1216 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1217 outs() << " cputype (" << cputype << ")\n";
1218 outs() << " cpusubtype (" << cpusubtype << ")\n";
1221 // printCPUType() helps print_fat_headers by printing the cputype and
1222 // pusubtype (symbolically for the one's it knows about).
1223 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1225 case MachO::CPU_TYPE_I386:
1226 switch (cpusubtype) {
1227 case MachO::CPU_SUBTYPE_I386_ALL:
1228 outs() << " cputype CPU_TYPE_I386\n";
1229 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1232 printUnknownCPUType(cputype, cpusubtype);
1236 case MachO::CPU_TYPE_X86_64:
1237 switch (cpusubtype) {
1238 case MachO::CPU_SUBTYPE_X86_64_ALL:
1239 outs() << " cputype CPU_TYPE_X86_64\n";
1240 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1242 case MachO::CPU_SUBTYPE_X86_64_H:
1243 outs() << " cputype CPU_TYPE_X86_64\n";
1244 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1247 printUnknownCPUType(cputype, cpusubtype);
1251 case MachO::CPU_TYPE_ARM:
1252 switch (cpusubtype) {
1253 case MachO::CPU_SUBTYPE_ARM_ALL:
1254 outs() << " cputype CPU_TYPE_ARM\n";
1255 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1257 case MachO::CPU_SUBTYPE_ARM_V4T:
1258 outs() << " cputype CPU_TYPE_ARM\n";
1259 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1261 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1262 outs() << " cputype CPU_TYPE_ARM\n";
1263 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1265 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1266 outs() << " cputype CPU_TYPE_ARM\n";
1267 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1269 case MachO::CPU_SUBTYPE_ARM_V6:
1270 outs() << " cputype CPU_TYPE_ARM\n";
1271 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1273 case MachO::CPU_SUBTYPE_ARM_V6M:
1274 outs() << " cputype CPU_TYPE_ARM\n";
1275 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1277 case MachO::CPU_SUBTYPE_ARM_V7:
1278 outs() << " cputype CPU_TYPE_ARM\n";
1279 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1281 case MachO::CPU_SUBTYPE_ARM_V7EM:
1282 outs() << " cputype CPU_TYPE_ARM\n";
1283 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1285 case MachO::CPU_SUBTYPE_ARM_V7K:
1286 outs() << " cputype CPU_TYPE_ARM\n";
1287 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1289 case MachO::CPU_SUBTYPE_ARM_V7M:
1290 outs() << " cputype CPU_TYPE_ARM\n";
1291 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1293 case MachO::CPU_SUBTYPE_ARM_V7S:
1294 outs() << " cputype CPU_TYPE_ARM\n";
1295 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1298 printUnknownCPUType(cputype, cpusubtype);
1302 case MachO::CPU_TYPE_ARM64:
1303 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1304 case MachO::CPU_SUBTYPE_ARM64_ALL:
1305 outs() << " cputype CPU_TYPE_ARM64\n";
1306 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1309 printUnknownCPUType(cputype, cpusubtype);
1314 printUnknownCPUType(cputype, cpusubtype);
1319 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1321 outs() << "Fat headers\n";
1323 outs() << "fat_magic FAT_MAGIC\n";
1325 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1327 uint32_t nfat_arch = UB->getNumberOfObjects();
1328 StringRef Buf = UB->getData();
1329 uint64_t size = Buf.size();
1330 uint64_t big_size = sizeof(struct MachO::fat_header) +
1331 nfat_arch * sizeof(struct MachO::fat_arch);
1332 outs() << "nfat_arch " << UB->getNumberOfObjects();
1334 outs() << " (malformed, contains zero architecture types)\n";
1335 else if (big_size > size)
1336 outs() << " (malformed, architectures past end of file)\n";
1340 for (uint32_t i = 0; i < nfat_arch; ++i) {
1341 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1342 uint32_t cputype = OFA.getCPUType();
1343 uint32_t cpusubtype = OFA.getCPUSubType();
1344 outs() << "architecture ";
1345 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1346 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1347 uint32_t other_cputype = other_OFA.getCPUType();
1348 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1349 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1350 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1351 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1352 outs() << "(illegal duplicate architecture) ";
1357 outs() << OFA.getArchTypeName() << "\n";
1358 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1360 outs() << i << "\n";
1361 outs() << " cputype " << cputype << "\n";
1362 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1366 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1367 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1369 outs() << " capabilities "
1370 << format("0x%" PRIx32,
1371 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1372 outs() << " offset " << OFA.getOffset();
1373 if (OFA.getOffset() > size)
1374 outs() << " (past end of file)";
1375 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1376 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1378 outs() << " size " << OFA.getSize();
1379 big_size = OFA.getOffset() + OFA.getSize();
1380 if (big_size > size)
1381 outs() << " (past end of file)";
1383 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1388 static void printArchiveChild(const Archive::Child &C, bool verbose,
1389 bool print_offset) {
1391 outs() << C.getChildOffset() << "\t";
1392 sys::fs::perms Mode = C.getAccessMode();
1394 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1395 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1397 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1398 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1399 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1400 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1401 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1402 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1403 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1404 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1405 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1407 outs() << format("0%o ", Mode);
1410 unsigned UID = C.getUID();
1411 outs() << format("%3d/", UID);
1412 unsigned GID = C.getGID();
1413 outs() << format("%-3d ", GID);
1414 ErrorOr<uint64_t> Size = C.getRawSize();
1415 if (std::error_code EC = Size.getError())
1416 report_fatal_error(EC.message());
1417 outs() << format("%5" PRId64, Size.get()) << " ";
1419 StringRef RawLastModified = C.getRawLastModified();
1422 if (RawLastModified.getAsInteger(10, Seconds))
1423 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1425 // Since cime(3) returns a 26 character string of the form:
1426 // "Sun Sep 16 01:03:52 1973\n\0"
1427 // just print 24 characters.
1429 outs() << format("%.24s ", ctime(&t));
1432 outs() << RawLastModified << " ";
1436 ErrorOr<StringRef> NameOrErr = C.getName();
1437 if (NameOrErr.getError()) {
1438 StringRef RawName = C.getRawName();
1439 outs() << RawName << "\n";
1441 StringRef Name = NameOrErr.get();
1442 outs() << Name << "\n";
1445 StringRef RawName = C.getRawName();
1446 outs() << RawName << "\n";
1450 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1451 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1453 if (std::error_code EC = I->getError())
1454 report_fatal_error(EC.message());
1455 const Archive::Child &C = **I;
1456 printArchiveChild(C, verbose, print_offset);
1460 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1461 // -arch flags selecting just those slices as specified by them and also parses
1462 // archive files. Then for each individual Mach-O file ProcessMachO() is
1463 // called to process the file based on the command line options.
1464 void llvm::ParseInputMachO(StringRef Filename) {
1465 // Check for -arch all and verifiy the -arch flags are valid.
1466 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1467 if (ArchFlags[i] == "all") {
1470 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1471 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1472 "'for the -arch option\n";
1478 // Attempt to open the binary.
1479 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1480 if (std::error_code EC = BinaryOrErr.getError()) {
1481 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
1484 Binary &Bin = *BinaryOrErr.get().getBinary();
1486 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1487 outs() << "Archive : " << Filename << "\n";
1489 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
1490 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1492 if (std::error_code EC = I->getError())
1493 report_error(Filename, EC);
1495 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1496 if (ChildOrErr.getError())
1498 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1499 if (!checkMachOAndArchFlags(O, Filename))
1501 ProcessMachO(Filename, O, O->getFileName());
1506 if (UniversalHeaders) {
1507 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1508 printMachOUniversalHeaders(UB, !NonVerbose);
1510 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1511 // If we have a list of architecture flags specified dump only those.
1512 if (!ArchAll && ArchFlags.size() != 0) {
1513 // Look for a slice in the universal binary that matches each ArchFlag.
1515 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1517 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1518 E = UB->end_objects();
1520 if (ArchFlags[i] == I->getArchTypeName()) {
1522 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1523 I->getAsObjectFile();
1524 std::string ArchitectureName = "";
1525 if (ArchFlags.size() > 1)
1526 ArchitectureName = I->getArchTypeName();
1528 ObjectFile &O = *ObjOrErr.get();
1529 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1530 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1531 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1532 I->getAsArchive()) {
1533 std::unique_ptr<Archive> &A = *AOrErr;
1534 outs() << "Archive : " << Filename;
1535 if (!ArchitectureName.empty())
1536 outs() << " (architecture " << ArchitectureName << ")";
1539 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1540 for (Archive::child_iterator AI = A->child_begin(),
1541 AE = A->child_end();
1543 if (std::error_code EC = AI->getError())
1544 report_error(Filename, EC);
1545 auto &C = AI->get();
1546 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1547 if (ChildOrErr.getError())
1549 if (MachOObjectFile *O =
1550 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1551 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1557 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1558 << "architecture: " + ArchFlags[i] + "\n";
1564 // No architecture flags were specified so if this contains a slice that
1565 // matches the host architecture dump only that.
1567 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1568 E = UB->end_objects();
1570 if (MachOObjectFile::getHostArch().getArchName() ==
1571 I->getArchTypeName()) {
1572 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1573 std::string ArchiveName;
1574 ArchiveName.clear();
1576 ObjectFile &O = *ObjOrErr.get();
1577 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1578 ProcessMachO(Filename, MachOOF);
1579 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1580 I->getAsArchive()) {
1581 std::unique_ptr<Archive> &A = *AOrErr;
1582 outs() << "Archive : " << Filename << "\n";
1584 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1585 for (Archive::child_iterator AI = A->child_begin(),
1586 AE = A->child_end();
1588 if (std::error_code EC = AI->getError())
1589 report_error(Filename, EC);
1590 auto &C = AI->get();
1591 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1592 if (ChildOrErr.getError())
1594 if (MachOObjectFile *O =
1595 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1596 ProcessMachO(Filename, O, O->getFileName());
1603 // Either all architectures have been specified or none have been specified
1604 // and this does not contain the host architecture so dump all the slices.
1605 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1606 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1607 E = UB->end_objects();
1609 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1610 std::string ArchitectureName = "";
1611 if (moreThanOneArch)
1612 ArchitectureName = I->getArchTypeName();
1614 ObjectFile &Obj = *ObjOrErr.get();
1615 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1616 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1617 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1618 std::unique_ptr<Archive> &A = *AOrErr;
1619 outs() << "Archive : " << Filename;
1620 if (!ArchitectureName.empty())
1621 outs() << " (architecture " << ArchitectureName << ")";
1624 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1625 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1627 if (std::error_code EC = AI->getError())
1628 report_error(Filename, EC);
1629 auto &C = AI->get();
1630 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1631 if (ChildOrErr.getError())
1633 if (MachOObjectFile *O =
1634 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1635 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1636 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1644 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1645 if (!checkMachOAndArchFlags(O, Filename))
1647 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1648 ProcessMachO(Filename, MachOOF);
1650 errs() << "llvm-objdump: '" << Filename << "': "
1651 << "Object is not a Mach-O file type.\n";
1653 errs() << "llvm-objdump: '" << Filename << "': "
1654 << "Unrecognized file type.\n";
1657 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1658 typedef std::vector<BindInfoEntry> BindTable;
1659 typedef BindTable::iterator bind_table_iterator;
1661 // The block of info used by the Symbolizer call backs.
1662 struct DisassembleInfo {
1666 SymbolAddressMap *AddrMap;
1667 std::vector<SectionRef> *Sections;
1668 const char *class_name;
1669 const char *selector_name;
1671 char *demangled_name;
1674 BindTable *bindtable;
1678 // SymbolizerGetOpInfo() is the operand information call back function.
1679 // This is called to get the symbolic information for operand(s) of an
1680 // instruction when it is being done. This routine does this from
1681 // the relocation information, symbol table, etc. That block of information
1682 // is a pointer to the struct DisassembleInfo that was passed when the
1683 // disassembler context was created and passed to back to here when
1684 // called back by the disassembler for instruction operands that could have
1685 // relocation information. The address of the instruction containing operand is
1686 // at the Pc parameter. The immediate value the operand has is passed in
1687 // op_info->Value and is at Offset past the start of the instruction and has a
1688 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1689 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1690 // names and addends of the symbolic expression to add for the operand. The
1691 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1692 // information is returned then this function returns 1 else it returns 0.
1693 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1694 uint64_t Size, int TagType, void *TagBuf) {
1695 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1696 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1697 uint64_t value = op_info->Value;
1699 // Make sure all fields returned are zero if we don't set them.
1700 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1701 op_info->Value = value;
1703 // If the TagType is not the value 1 which it code knows about or if no
1704 // verbose symbolic information is wanted then just return 0, indicating no
1705 // information is being returned.
1706 if (TagType != 1 || !info->verbose)
1709 unsigned int Arch = info->O->getArch();
1710 if (Arch == Triple::x86) {
1711 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1713 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1715 // Search the external relocation entries of a fully linked image
1716 // (if any) for an entry that matches this segment offset.
1717 // uint32_t seg_offset = (Pc + Offset);
1720 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1721 // for an entry for this section offset.
1722 uint32_t sect_addr = info->S.getAddress();
1723 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1724 bool reloc_found = false;
1726 MachO::any_relocation_info RE;
1727 bool isExtern = false;
1729 bool r_scattered = false;
1730 uint32_t r_value, pair_r_value, r_type;
1731 for (const RelocationRef &Reloc : info->S.relocations()) {
1732 uint64_t RelocOffset = Reloc.getOffset();
1733 if (RelocOffset == sect_offset) {
1734 Rel = Reloc.getRawDataRefImpl();
1735 RE = info->O->getRelocation(Rel);
1736 r_type = info->O->getAnyRelocationType(RE);
1737 r_scattered = info->O->isRelocationScattered(RE);
1739 r_value = info->O->getScatteredRelocationValue(RE);
1740 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1741 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1742 DataRefImpl RelNext = Rel;
1743 info->O->moveRelocationNext(RelNext);
1744 MachO::any_relocation_info RENext;
1745 RENext = info->O->getRelocation(RelNext);
1746 if (info->O->isRelocationScattered(RENext))
1747 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1752 isExtern = info->O->getPlainRelocationExternal(RE);
1754 symbol_iterator RelocSym = Reloc.getSymbol();
1762 if (reloc_found && isExtern) {
1763 ErrorOr<StringRef> SymName = Symbol.getName();
1764 if (std::error_code EC = SymName.getError())
1765 report_fatal_error(EC.message());
1766 const char *name = SymName->data();
1767 op_info->AddSymbol.Present = 1;
1768 op_info->AddSymbol.Name = name;
1769 // For i386 extern relocation entries the value in the instruction is
1770 // the offset from the symbol, and value is already set in op_info->Value.
1773 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1774 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1775 const char *add = GuessSymbolName(r_value, info->AddrMap);
1776 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1777 uint32_t offset = value - (r_value - pair_r_value);
1778 op_info->AddSymbol.Present = 1;
1780 op_info->AddSymbol.Name = add;
1782 op_info->AddSymbol.Value = r_value;
1783 op_info->SubtractSymbol.Present = 1;
1785 op_info->SubtractSymbol.Name = sub;
1787 op_info->SubtractSymbol.Value = pair_r_value;
1788 op_info->Value = offset;
1793 if (Arch == Triple::x86_64) {
1794 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1796 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1798 // Search the external relocation entries of a fully linked image
1799 // (if any) for an entry that matches this segment offset.
1800 // uint64_t seg_offset = (Pc + Offset);
1803 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1804 // for an entry for this section offset.
1805 uint64_t sect_addr = info->S.getAddress();
1806 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1807 bool reloc_found = false;
1809 MachO::any_relocation_info RE;
1810 bool isExtern = false;
1812 for (const RelocationRef &Reloc : info->S.relocations()) {
1813 uint64_t RelocOffset = Reloc.getOffset();
1814 if (RelocOffset == sect_offset) {
1815 Rel = Reloc.getRawDataRefImpl();
1816 RE = info->O->getRelocation(Rel);
1817 // NOTE: Scattered relocations don't exist on x86_64.
1818 isExtern = info->O->getPlainRelocationExternal(RE);
1820 symbol_iterator RelocSym = Reloc.getSymbol();
1827 if (reloc_found && isExtern) {
1828 // The Value passed in will be adjusted by the Pc if the instruction
1829 // adds the Pc. But for x86_64 external relocation entries the Value
1830 // is the offset from the external symbol.
1831 if (info->O->getAnyRelocationPCRel(RE))
1832 op_info->Value -= Pc + Offset + Size;
1833 ErrorOr<StringRef> SymName = Symbol.getName();
1834 if (std::error_code EC = SymName.getError())
1835 report_fatal_error(EC.message());
1836 const char *name = SymName->data();
1837 unsigned Type = info->O->getAnyRelocationType(RE);
1838 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1839 DataRefImpl RelNext = Rel;
1840 info->O->moveRelocationNext(RelNext);
1841 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1842 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1843 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1844 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1845 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1846 op_info->SubtractSymbol.Present = 1;
1847 op_info->SubtractSymbol.Name = name;
1848 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1849 Symbol = *RelocSymNext;
1850 ErrorOr<StringRef> SymNameNext = Symbol.getName();
1851 if (std::error_code EC = SymNameNext.getError())
1852 report_fatal_error(EC.message());
1853 name = SymNameNext->data();
1856 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1857 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1858 op_info->AddSymbol.Present = 1;
1859 op_info->AddSymbol.Name = name;
1864 if (Arch == Triple::arm) {
1865 if (Offset != 0 || (Size != 4 && Size != 2))
1867 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1869 // Search the external relocation entries of a fully linked image
1870 // (if any) for an entry that matches this segment offset.
1871 // uint32_t seg_offset = (Pc + Offset);
1874 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1875 // for an entry for this section offset.
1876 uint32_t sect_addr = info->S.getAddress();
1877 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1879 MachO::any_relocation_info RE;
1880 bool isExtern = false;
1882 bool r_scattered = false;
1883 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1885 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1886 [&](const RelocationRef &Reloc) {
1887 uint64_t RelocOffset = Reloc.getOffset();
1888 return RelocOffset == sect_offset;
1891 if (Reloc == info->S.relocations().end())
1894 Rel = Reloc->getRawDataRefImpl();
1895 RE = info->O->getRelocation(Rel);
1896 r_length = info->O->getAnyRelocationLength(RE);
1897 r_scattered = info->O->isRelocationScattered(RE);
1899 r_value = info->O->getScatteredRelocationValue(RE);
1900 r_type = info->O->getScatteredRelocationType(RE);
1902 r_type = info->O->getAnyRelocationType(RE);
1903 isExtern = info->O->getPlainRelocationExternal(RE);
1905 symbol_iterator RelocSym = Reloc->getSymbol();
1909 if (r_type == MachO::ARM_RELOC_HALF ||
1910 r_type == MachO::ARM_RELOC_SECTDIFF ||
1911 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1912 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1913 DataRefImpl RelNext = Rel;
1914 info->O->moveRelocationNext(RelNext);
1915 MachO::any_relocation_info RENext;
1916 RENext = info->O->getRelocation(RelNext);
1917 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1918 if (info->O->isRelocationScattered(RENext))
1919 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1923 ErrorOr<StringRef> SymName = Symbol.getName();
1924 if (std::error_code EC = SymName.getError())
1925 report_fatal_error(EC.message());
1926 const char *name = SymName->data();
1927 op_info->AddSymbol.Present = 1;
1928 op_info->AddSymbol.Name = name;
1930 case MachO::ARM_RELOC_HALF:
1931 if ((r_length & 0x1) == 1) {
1932 op_info->Value = value << 16 | other_half;
1933 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1935 op_info->Value = other_half << 16 | value;
1936 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1944 // If we have a branch that is not an external relocation entry then
1945 // return 0 so the code in tryAddingSymbolicOperand() can use the
1946 // SymbolLookUp call back with the branch target address to look up the
1947 // symbol and possiblity add an annotation for a symbol stub.
1948 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1949 r_type == MachO::ARM_THUMB_RELOC_BR22))
1952 uint32_t offset = 0;
1953 if (r_type == MachO::ARM_RELOC_HALF ||
1954 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1955 if ((r_length & 0x1) == 1)
1956 value = value << 16 | other_half;
1958 value = other_half << 16 | value;
1960 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1961 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1962 offset = value - r_value;
1966 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1967 if ((r_length & 0x1) == 1)
1968 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1970 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1971 const char *add = GuessSymbolName(r_value, info->AddrMap);
1972 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1973 int32_t offset = value - (r_value - pair_r_value);
1974 op_info->AddSymbol.Present = 1;
1976 op_info->AddSymbol.Name = add;
1978 op_info->AddSymbol.Value = r_value;
1979 op_info->SubtractSymbol.Present = 1;
1981 op_info->SubtractSymbol.Name = sub;
1983 op_info->SubtractSymbol.Value = pair_r_value;
1984 op_info->Value = offset;
1988 op_info->AddSymbol.Present = 1;
1989 op_info->Value = offset;
1990 if (r_type == MachO::ARM_RELOC_HALF) {
1991 if ((r_length & 0x1) == 1)
1992 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1994 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1996 const char *add = GuessSymbolName(value, info->AddrMap);
1997 if (add != nullptr) {
1998 op_info->AddSymbol.Name = add;
2001 op_info->AddSymbol.Value = value;
2004 if (Arch == Triple::aarch64) {
2005 if (Offset != 0 || Size != 4)
2007 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2009 // Search the external relocation entries of a fully linked image
2010 // (if any) for an entry that matches this segment offset.
2011 // uint64_t seg_offset = (Pc + Offset);
2014 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2015 // for an entry for this section offset.
2016 uint64_t sect_addr = info->S.getAddress();
2017 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2019 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2020 [&](const RelocationRef &Reloc) {
2021 uint64_t RelocOffset = Reloc.getOffset();
2022 return RelocOffset == sect_offset;
2025 if (Reloc == info->S.relocations().end())
2028 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2029 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2030 uint32_t r_type = info->O->getAnyRelocationType(RE);
2031 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2032 DataRefImpl RelNext = Rel;
2033 info->O->moveRelocationNext(RelNext);
2034 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2036 value = info->O->getPlainRelocationSymbolNum(RENext);
2037 op_info->Value = value;
2040 // NOTE: Scattered relocations don't exist on arm64.
2041 if (!info->O->getPlainRelocationExternal(RE))
2043 ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
2044 if (std::error_code EC = SymName.getError())
2045 report_fatal_error(EC.message());
2046 const char *name = SymName->data();
2047 op_info->AddSymbol.Present = 1;
2048 op_info->AddSymbol.Name = name;
2051 case MachO::ARM64_RELOC_PAGE21:
2053 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2055 case MachO::ARM64_RELOC_PAGEOFF12:
2057 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2059 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2061 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2063 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2065 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2067 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2068 /* @tvlppage is not implemented in llvm-mc */
2069 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2071 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2072 /* @tvlppageoff is not implemented in llvm-mc */
2073 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2076 case MachO::ARM64_RELOC_BRANCH26:
2077 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2085 // GuessCstringPointer is passed the address of what might be a pointer to a
2086 // literal string in a cstring section. If that address is in a cstring section
2087 // it returns a pointer to that string. Else it returns nullptr.
2088 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2089 struct DisassembleInfo *info) {
2090 for (const auto &Load : info->O->load_commands()) {
2091 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2092 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2093 for (unsigned J = 0; J < Seg.nsects; ++J) {
2094 MachO::section_64 Sec = info->O->getSection64(Load, J);
2095 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2096 if (section_type == MachO::S_CSTRING_LITERALS &&
2097 ReferenceValue >= Sec.addr &&
2098 ReferenceValue < Sec.addr + Sec.size) {
2099 uint64_t sect_offset = ReferenceValue - Sec.addr;
2100 uint64_t object_offset = Sec.offset + sect_offset;
2101 StringRef MachOContents = info->O->getData();
2102 uint64_t object_size = MachOContents.size();
2103 const char *object_addr = (const char *)MachOContents.data();
2104 if (object_offset < object_size) {
2105 const char *name = object_addr + object_offset;
2112 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2113 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2114 for (unsigned J = 0; J < Seg.nsects; ++J) {
2115 MachO::section Sec = info->O->getSection(Load, J);
2116 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2117 if (section_type == MachO::S_CSTRING_LITERALS &&
2118 ReferenceValue >= Sec.addr &&
2119 ReferenceValue < Sec.addr + Sec.size) {
2120 uint64_t sect_offset = ReferenceValue - Sec.addr;
2121 uint64_t object_offset = Sec.offset + sect_offset;
2122 StringRef MachOContents = info->O->getData();
2123 uint64_t object_size = MachOContents.size();
2124 const char *object_addr = (const char *)MachOContents.data();
2125 if (object_offset < object_size) {
2126 const char *name = object_addr + object_offset;
2138 // GuessIndirectSymbol returns the name of the indirect symbol for the
2139 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2140 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2141 // symbol name being referenced by the stub or pointer.
2142 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2143 struct DisassembleInfo *info) {
2144 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2145 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2146 for (const auto &Load : info->O->load_commands()) {
2147 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2148 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2149 for (unsigned J = 0; J < Seg.nsects; ++J) {
2150 MachO::section_64 Sec = info->O->getSection64(Load, J);
2151 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2152 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2153 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2154 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2155 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2156 section_type == MachO::S_SYMBOL_STUBS) &&
2157 ReferenceValue >= Sec.addr &&
2158 ReferenceValue < Sec.addr + Sec.size) {
2160 if (section_type == MachO::S_SYMBOL_STUBS)
2161 stride = Sec.reserved2;
2166 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2167 if (index < Dysymtab.nindirectsyms) {
2168 uint32_t indirect_symbol =
2169 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2170 if (indirect_symbol < Symtab.nsyms) {
2171 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2172 SymbolRef Symbol = *Sym;
2173 ErrorOr<StringRef> SymName = Symbol.getName();
2174 if (std::error_code EC = SymName.getError())
2175 report_fatal_error(EC.message());
2176 const char *name = SymName->data();
2182 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2183 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2184 for (unsigned J = 0; J < Seg.nsects; ++J) {
2185 MachO::section Sec = info->O->getSection(Load, J);
2186 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2187 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2188 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2189 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2190 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2191 section_type == MachO::S_SYMBOL_STUBS) &&
2192 ReferenceValue >= Sec.addr &&
2193 ReferenceValue < Sec.addr + Sec.size) {
2195 if (section_type == MachO::S_SYMBOL_STUBS)
2196 stride = Sec.reserved2;
2201 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2202 if (index < Dysymtab.nindirectsyms) {
2203 uint32_t indirect_symbol =
2204 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2205 if (indirect_symbol < Symtab.nsyms) {
2206 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2207 SymbolRef Symbol = *Sym;
2208 ErrorOr<StringRef> SymName = Symbol.getName();
2209 if (std::error_code EC = SymName.getError())
2210 report_fatal_error(EC.message());
2211 const char *name = SymName->data();
2222 // method_reference() is called passing it the ReferenceName that might be
2223 // a reference it to an Objective-C method call. If so then it allocates and
2224 // assembles a method call string with the values last seen and saved in
2225 // the DisassembleInfo's class_name and selector_name fields. This is saved
2226 // into the method field of the info and any previous string is free'ed.
2227 // Then the class_name field in the info is set to nullptr. The method call
2228 // string is set into ReferenceName and ReferenceType is set to
2229 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2230 // then both ReferenceType and ReferenceName are left unchanged.
2231 static void method_reference(struct DisassembleInfo *info,
2232 uint64_t *ReferenceType,
2233 const char **ReferenceName) {
2234 unsigned int Arch = info->O->getArch();
2235 if (*ReferenceName != nullptr) {
2236 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2237 if (info->selector_name != nullptr) {
2238 if (info->method != nullptr)
2240 if (info->class_name != nullptr) {
2241 info->method = (char *)malloc(5 + strlen(info->class_name) +
2242 strlen(info->selector_name));
2243 if (info->method != nullptr) {
2244 strcpy(info->method, "+[");
2245 strcat(info->method, info->class_name);
2246 strcat(info->method, " ");
2247 strcat(info->method, info->selector_name);
2248 strcat(info->method, "]");
2249 *ReferenceName = info->method;
2250 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2253 info->method = (char *)malloc(9 + strlen(info->selector_name));
2254 if (info->method != nullptr) {
2255 if (Arch == Triple::x86_64)
2256 strcpy(info->method, "-[%rdi ");
2257 else if (Arch == Triple::aarch64)
2258 strcpy(info->method, "-[x0 ");
2260 strcpy(info->method, "-[r? ");
2261 strcat(info->method, info->selector_name);
2262 strcat(info->method, "]");
2263 *ReferenceName = info->method;
2264 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2267 info->class_name = nullptr;
2269 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2270 if (info->selector_name != nullptr) {
2271 if (info->method != nullptr)
2273 info->method = (char *)malloc(17 + strlen(info->selector_name));
2274 if (info->method != nullptr) {
2275 if (Arch == Triple::x86_64)
2276 strcpy(info->method, "-[[%rdi super] ");
2277 else if (Arch == Triple::aarch64)
2278 strcpy(info->method, "-[[x0 super] ");
2280 strcpy(info->method, "-[[r? super] ");
2281 strcat(info->method, info->selector_name);
2282 strcat(info->method, "]");
2283 *ReferenceName = info->method;
2284 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2286 info->class_name = nullptr;
2292 // GuessPointerPointer() is passed the address of what might be a pointer to
2293 // a reference to an Objective-C class, selector, message ref or cfstring.
2294 // If so the value of the pointer is returned and one of the booleans are set
2295 // to true. If not zero is returned and all the booleans are set to false.
2296 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2297 struct DisassembleInfo *info,
2298 bool &classref, bool &selref, bool &msgref,
2304 for (const auto &Load : info->O->load_commands()) {
2305 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2306 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2307 for (unsigned J = 0; J < Seg.nsects; ++J) {
2308 MachO::section_64 Sec = info->O->getSection64(Load, J);
2309 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2310 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2311 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2312 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2313 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2314 ReferenceValue >= Sec.addr &&
2315 ReferenceValue < Sec.addr + Sec.size) {
2316 uint64_t sect_offset = ReferenceValue - Sec.addr;
2317 uint64_t object_offset = Sec.offset + sect_offset;
2318 StringRef MachOContents = info->O->getData();
2319 uint64_t object_size = MachOContents.size();
2320 const char *object_addr = (const char *)MachOContents.data();
2321 if (object_offset < object_size) {
2322 uint64_t pointer_value;
2323 memcpy(&pointer_value, object_addr + object_offset,
2325 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2326 sys::swapByteOrder(pointer_value);
2327 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2329 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2330 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2332 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2333 ReferenceValue + 8 < Sec.addr + Sec.size) {
2335 memcpy(&pointer_value, object_addr + object_offset + 8,
2337 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2338 sys::swapByteOrder(pointer_value);
2339 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2341 return pointer_value;
2348 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2353 // get_pointer_64 returns a pointer to the bytes in the object file at the
2354 // Address from a section in the Mach-O file. And indirectly returns the
2355 // offset into the section, number of bytes left in the section past the offset
2356 // and which section is was being referenced. If the Address is not in a
2357 // section nullptr is returned.
2358 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2359 uint32_t &left, SectionRef &S,
2360 DisassembleInfo *info,
2361 bool objc_only = false) {
2365 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2366 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2367 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2372 ((*(info->Sections))[SectIdx]).getName(SectName);
2373 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2374 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2375 if (SegName != "__OBJC" && SectName != "__cstring")
2378 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2379 S = (*(info->Sections))[SectIdx];
2380 offset = Address - SectAddress;
2381 left = SectSize - offset;
2382 StringRef SectContents;
2383 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2384 return SectContents.data() + offset;
2390 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2391 uint32_t &left, SectionRef &S,
2392 DisassembleInfo *info,
2393 bool objc_only = false) {
2394 return get_pointer_64(Address, offset, left, S, info, objc_only);
2397 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2398 // the symbol indirectly through n_value. Based on the relocation information
2399 // for the specified section offset in the specified section reference.
2400 // If no relocation information is found and a non-zero ReferenceValue for the
2401 // symbol is passed, look up that address in the info's AddrMap.
2402 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2403 DisassembleInfo *info, uint64_t &n_value,
2404 uint64_t ReferenceValue = 0) {
2409 // See if there is an external relocation entry at the sect_offset.
2410 bool reloc_found = false;
2412 MachO::any_relocation_info RE;
2413 bool isExtern = false;
2415 for (const RelocationRef &Reloc : S.relocations()) {
2416 uint64_t RelocOffset = Reloc.getOffset();
2417 if (RelocOffset == sect_offset) {
2418 Rel = Reloc.getRawDataRefImpl();
2419 RE = info->O->getRelocation(Rel);
2420 if (info->O->isRelocationScattered(RE))
2422 isExtern = info->O->getPlainRelocationExternal(RE);
2424 symbol_iterator RelocSym = Reloc.getSymbol();
2431 // If there is an external relocation entry for a symbol in this section
2432 // at this section_offset then use that symbol's value for the n_value
2433 // and return its name.
2434 const char *SymbolName = nullptr;
2435 if (reloc_found && isExtern) {
2436 n_value = Symbol.getValue();
2437 ErrorOr<StringRef> NameOrError = Symbol.getName();
2438 if (std::error_code EC = NameOrError.getError())
2439 report_fatal_error(EC.message());
2440 StringRef Name = *NameOrError;
2441 if (!Name.empty()) {
2442 SymbolName = Name.data();
2447 // TODO: For fully linked images, look through the external relocation
2448 // entries off the dynamic symtab command. For these the r_offset is from the
2449 // start of the first writeable segment in the Mach-O file. So the offset
2450 // to this section from that segment is passed to this routine by the caller,
2451 // as the database_offset. Which is the difference of the section's starting
2452 // address and the first writable segment.
2454 // NOTE: need add passing the database_offset to this routine.
2456 // We did not find an external relocation entry so look up the ReferenceValue
2457 // as an address of a symbol and if found return that symbol's name.
2458 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2463 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2464 DisassembleInfo *info,
2465 uint32_t ReferenceValue) {
2467 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2470 // These are structs in the Objective-C meta data and read to produce the
2471 // comments for disassembly. While these are part of the ABI they are no
2472 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2474 // The cfstring object in a 64-bit Mach-O file.
2475 struct cfstring64_t {
2476 uint64_t isa; // class64_t * (64-bit pointer)
2477 uint64_t flags; // flag bits
2478 uint64_t characters; // char * (64-bit pointer)
2479 uint64_t length; // number of non-NULL characters in above
2482 // The class object in a 64-bit Mach-O file.
2484 uint64_t isa; // class64_t * (64-bit pointer)
2485 uint64_t superclass; // class64_t * (64-bit pointer)
2486 uint64_t cache; // Cache (64-bit pointer)
2487 uint64_t vtable; // IMP * (64-bit pointer)
2488 uint64_t data; // class_ro64_t * (64-bit pointer)
2492 uint32_t isa; /* class32_t * (32-bit pointer) */
2493 uint32_t superclass; /* class32_t * (32-bit pointer) */
2494 uint32_t cache; /* Cache (32-bit pointer) */
2495 uint32_t vtable; /* IMP * (32-bit pointer) */
2496 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2499 struct class_ro64_t {
2501 uint32_t instanceStart;
2502 uint32_t instanceSize;
2504 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2505 uint64_t name; // const char * (64-bit pointer)
2506 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2507 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2508 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2509 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2510 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2513 struct class_ro32_t {
2515 uint32_t instanceStart;
2516 uint32_t instanceSize;
2517 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2518 uint32_t name; /* const char * (32-bit pointer) */
2519 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2520 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2521 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2522 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2523 uint32_t baseProperties; /* const struct objc_property_list *
2527 /* Values for class_ro{64,32}_t->flags */
2528 #define RO_META (1 << 0)
2529 #define RO_ROOT (1 << 1)
2530 #define RO_HAS_CXX_STRUCTORS (1 << 2)
2532 struct method_list64_t {
2535 /* struct method64_t first; These structures follow inline */
2538 struct method_list32_t {
2541 /* struct method32_t first; These structures follow inline */
2545 uint64_t name; /* SEL (64-bit pointer) */
2546 uint64_t types; /* const char * (64-bit pointer) */
2547 uint64_t imp; /* IMP (64-bit pointer) */
2551 uint32_t name; /* SEL (32-bit pointer) */
2552 uint32_t types; /* const char * (32-bit pointer) */
2553 uint32_t imp; /* IMP (32-bit pointer) */
2556 struct protocol_list64_t {
2557 uint64_t count; /* uintptr_t (a 64-bit value) */
2558 /* struct protocol64_t * list[0]; These pointers follow inline */
2561 struct protocol_list32_t {
2562 uint32_t count; /* uintptr_t (a 32-bit value) */
2563 /* struct protocol32_t * list[0]; These pointers follow inline */
2566 struct protocol64_t {
2567 uint64_t isa; /* id * (64-bit pointer) */
2568 uint64_t name; /* const char * (64-bit pointer) */
2569 uint64_t protocols; /* struct protocol_list64_t *
2571 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2572 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2573 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2574 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2575 uint64_t instanceProperties; /* struct objc_property_list *
2579 struct protocol32_t {
2580 uint32_t isa; /* id * (32-bit pointer) */
2581 uint32_t name; /* const char * (32-bit pointer) */
2582 uint32_t protocols; /* struct protocol_list_t *
2584 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2585 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2586 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2587 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2588 uint32_t instanceProperties; /* struct objc_property_list *
2592 struct ivar_list64_t {
2595 /* struct ivar64_t first; These structures follow inline */
2598 struct ivar_list32_t {
2601 /* struct ivar32_t first; These structures follow inline */
2605 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2606 uint64_t name; /* const char * (64-bit pointer) */
2607 uint64_t type; /* const char * (64-bit pointer) */
2613 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2614 uint32_t name; /* const char * (32-bit pointer) */
2615 uint32_t type; /* const char * (32-bit pointer) */
2620 struct objc_property_list64 {
2623 /* struct objc_property64 first; These structures follow inline */
2626 struct objc_property_list32 {
2629 /* struct objc_property32 first; These structures follow inline */
2632 struct objc_property64 {
2633 uint64_t name; /* const char * (64-bit pointer) */
2634 uint64_t attributes; /* const char * (64-bit pointer) */
2637 struct objc_property32 {
2638 uint32_t name; /* const char * (32-bit pointer) */
2639 uint32_t attributes; /* const char * (32-bit pointer) */
2642 struct category64_t {
2643 uint64_t name; /* const char * (64-bit pointer) */
2644 uint64_t cls; /* struct class_t * (64-bit pointer) */
2645 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2646 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2647 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2648 uint64_t instanceProperties; /* struct objc_property_list *
2652 struct category32_t {
2653 uint32_t name; /* const char * (32-bit pointer) */
2654 uint32_t cls; /* struct class_t * (32-bit pointer) */
2655 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2656 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2657 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2658 uint32_t instanceProperties; /* struct objc_property_list *
2662 struct objc_image_info64 {
2666 struct objc_image_info32 {
2670 struct imageInfo_t {
2674 /* masks for objc_image_info.flags */
2675 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2676 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2678 struct message_ref64 {
2679 uint64_t imp; /* IMP (64-bit pointer) */
2680 uint64_t sel; /* SEL (64-bit pointer) */
2683 struct message_ref32 {
2684 uint32_t imp; /* IMP (32-bit pointer) */
2685 uint32_t sel; /* SEL (32-bit pointer) */
2688 // Objective-C 1 (32-bit only) meta data structs.
2690 struct objc_module_t {
2693 uint32_t name; /* char * (32-bit pointer) */
2694 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2697 struct objc_symtab_t {
2698 uint32_t sel_ref_cnt;
2699 uint32_t refs; /* SEL * (32-bit pointer) */
2700 uint16_t cls_def_cnt;
2701 uint16_t cat_def_cnt;
2702 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2705 struct objc_class_t {
2706 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2707 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2708 uint32_t name; /* const char * (32-bit pointer) */
2711 int32_t instance_size;
2712 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2713 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2714 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2715 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2718 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2719 // class is not a metaclass
2720 #define CLS_CLASS 0x1
2721 // class is a metaclass
2722 #define CLS_META 0x2
2724 struct objc_category_t {
2725 uint32_t category_name; /* char * (32-bit pointer) */
2726 uint32_t class_name; /* char * (32-bit pointer) */
2727 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2728 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2729 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2732 struct objc_ivar_t {
2733 uint32_t ivar_name; /* char * (32-bit pointer) */
2734 uint32_t ivar_type; /* char * (32-bit pointer) */
2735 int32_t ivar_offset;
2738 struct objc_ivar_list_t {
2740 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2743 struct objc_method_list_t {
2744 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2745 int32_t method_count;
2746 // struct objc_method_t method_list[1]; /* variable length structure */
2749 struct objc_method_t {
2750 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2751 uint32_t method_types; /* char * (32-bit pointer) */
2752 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2756 struct objc_protocol_list_t {
2757 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2759 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2760 // (32-bit pointer) */
2763 struct objc_protocol_t {
2764 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2765 uint32_t protocol_name; /* char * (32-bit pointer) */
2766 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2767 uint32_t instance_methods; /* struct objc_method_description_list *
2769 uint32_t class_methods; /* struct objc_method_description_list *
2773 struct objc_method_description_list_t {
2775 // struct objc_method_description_t list[1];
2778 struct objc_method_description_t {
2779 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2780 uint32_t types; /* char * (32-bit pointer) */
2783 inline void swapStruct(struct cfstring64_t &cfs) {
2784 sys::swapByteOrder(cfs.isa);
2785 sys::swapByteOrder(cfs.flags);
2786 sys::swapByteOrder(cfs.characters);
2787 sys::swapByteOrder(cfs.length);
2790 inline void swapStruct(struct class64_t &c) {
2791 sys::swapByteOrder(c.isa);
2792 sys::swapByteOrder(c.superclass);
2793 sys::swapByteOrder(c.cache);
2794 sys::swapByteOrder(c.vtable);
2795 sys::swapByteOrder(c.data);
2798 inline void swapStruct(struct class32_t &c) {
2799 sys::swapByteOrder(c.isa);
2800 sys::swapByteOrder(c.superclass);
2801 sys::swapByteOrder(c.cache);
2802 sys::swapByteOrder(c.vtable);
2803 sys::swapByteOrder(c.data);
2806 inline void swapStruct(struct class_ro64_t &cro) {
2807 sys::swapByteOrder(cro.flags);
2808 sys::swapByteOrder(cro.instanceStart);
2809 sys::swapByteOrder(cro.instanceSize);
2810 sys::swapByteOrder(cro.reserved);
2811 sys::swapByteOrder(cro.ivarLayout);
2812 sys::swapByteOrder(cro.name);
2813 sys::swapByteOrder(cro.baseMethods);
2814 sys::swapByteOrder(cro.baseProtocols);
2815 sys::swapByteOrder(cro.ivars);
2816 sys::swapByteOrder(cro.weakIvarLayout);
2817 sys::swapByteOrder(cro.baseProperties);
2820 inline void swapStruct(struct class_ro32_t &cro) {
2821 sys::swapByteOrder(cro.flags);
2822 sys::swapByteOrder(cro.instanceStart);
2823 sys::swapByteOrder(cro.instanceSize);
2824 sys::swapByteOrder(cro.ivarLayout);
2825 sys::swapByteOrder(cro.name);
2826 sys::swapByteOrder(cro.baseMethods);
2827 sys::swapByteOrder(cro.baseProtocols);
2828 sys::swapByteOrder(cro.ivars);
2829 sys::swapByteOrder(cro.weakIvarLayout);
2830 sys::swapByteOrder(cro.baseProperties);
2833 inline void swapStruct(struct method_list64_t &ml) {
2834 sys::swapByteOrder(ml.entsize);
2835 sys::swapByteOrder(ml.count);
2838 inline void swapStruct(struct method_list32_t &ml) {
2839 sys::swapByteOrder(ml.entsize);
2840 sys::swapByteOrder(ml.count);
2843 inline void swapStruct(struct method64_t &m) {
2844 sys::swapByteOrder(m.name);
2845 sys::swapByteOrder(m.types);
2846 sys::swapByteOrder(m.imp);
2849 inline void swapStruct(struct method32_t &m) {
2850 sys::swapByteOrder(m.name);
2851 sys::swapByteOrder(m.types);
2852 sys::swapByteOrder(m.imp);
2855 inline void swapStruct(struct protocol_list64_t &pl) {
2856 sys::swapByteOrder(pl.count);
2859 inline void swapStruct(struct protocol_list32_t &pl) {
2860 sys::swapByteOrder(pl.count);
2863 inline void swapStruct(struct protocol64_t &p) {
2864 sys::swapByteOrder(p.isa);
2865 sys::swapByteOrder(p.name);
2866 sys::swapByteOrder(p.protocols);
2867 sys::swapByteOrder(p.instanceMethods);
2868 sys::swapByteOrder(p.classMethods);
2869 sys::swapByteOrder(p.optionalInstanceMethods);
2870 sys::swapByteOrder(p.optionalClassMethods);
2871 sys::swapByteOrder(p.instanceProperties);
2874 inline void swapStruct(struct protocol32_t &p) {
2875 sys::swapByteOrder(p.isa);
2876 sys::swapByteOrder(p.name);
2877 sys::swapByteOrder(p.protocols);
2878 sys::swapByteOrder(p.instanceMethods);
2879 sys::swapByteOrder(p.classMethods);
2880 sys::swapByteOrder(p.optionalInstanceMethods);
2881 sys::swapByteOrder(p.optionalClassMethods);
2882 sys::swapByteOrder(p.instanceProperties);
2885 inline void swapStruct(struct ivar_list64_t &il) {
2886 sys::swapByteOrder(il.entsize);
2887 sys::swapByteOrder(il.count);
2890 inline void swapStruct(struct ivar_list32_t &il) {
2891 sys::swapByteOrder(il.entsize);
2892 sys::swapByteOrder(il.count);
2895 inline void swapStruct(struct ivar64_t &i) {
2896 sys::swapByteOrder(i.offset);
2897 sys::swapByteOrder(i.name);
2898 sys::swapByteOrder(i.type);
2899 sys::swapByteOrder(i.alignment);
2900 sys::swapByteOrder(i.size);
2903 inline void swapStruct(struct ivar32_t &i) {
2904 sys::swapByteOrder(i.offset);
2905 sys::swapByteOrder(i.name);
2906 sys::swapByteOrder(i.type);
2907 sys::swapByteOrder(i.alignment);
2908 sys::swapByteOrder(i.size);
2911 inline void swapStruct(struct objc_property_list64 &pl) {
2912 sys::swapByteOrder(pl.entsize);
2913 sys::swapByteOrder(pl.count);
2916 inline void swapStruct(struct objc_property_list32 &pl) {
2917 sys::swapByteOrder(pl.entsize);
2918 sys::swapByteOrder(pl.count);
2921 inline void swapStruct(struct objc_property64 &op) {
2922 sys::swapByteOrder(op.name);
2923 sys::swapByteOrder(op.attributes);
2926 inline void swapStruct(struct objc_property32 &op) {
2927 sys::swapByteOrder(op.name);
2928 sys::swapByteOrder(op.attributes);
2931 inline void swapStruct(struct category64_t &c) {
2932 sys::swapByteOrder(c.name);
2933 sys::swapByteOrder(c.cls);
2934 sys::swapByteOrder(c.instanceMethods);
2935 sys::swapByteOrder(c.classMethods);
2936 sys::swapByteOrder(c.protocols);
2937 sys::swapByteOrder(c.instanceProperties);
2940 inline void swapStruct(struct category32_t &c) {
2941 sys::swapByteOrder(c.name);
2942 sys::swapByteOrder(c.cls);
2943 sys::swapByteOrder(c.instanceMethods);
2944 sys::swapByteOrder(c.classMethods);
2945 sys::swapByteOrder(c.protocols);
2946 sys::swapByteOrder(c.instanceProperties);
2949 inline void swapStruct(struct objc_image_info64 &o) {
2950 sys::swapByteOrder(o.version);
2951 sys::swapByteOrder(o.flags);
2954 inline void swapStruct(struct objc_image_info32 &o) {
2955 sys::swapByteOrder(o.version);
2956 sys::swapByteOrder(o.flags);
2959 inline void swapStruct(struct imageInfo_t &o) {
2960 sys::swapByteOrder(o.version);
2961 sys::swapByteOrder(o.flags);
2964 inline void swapStruct(struct message_ref64 &mr) {
2965 sys::swapByteOrder(mr.imp);
2966 sys::swapByteOrder(mr.sel);
2969 inline void swapStruct(struct message_ref32 &mr) {
2970 sys::swapByteOrder(mr.imp);
2971 sys::swapByteOrder(mr.sel);
2974 inline void swapStruct(struct objc_module_t &module) {
2975 sys::swapByteOrder(module.version);
2976 sys::swapByteOrder(module.size);
2977 sys::swapByteOrder(module.name);
2978 sys::swapByteOrder(module.symtab);
2981 inline void swapStruct(struct objc_symtab_t &symtab) {
2982 sys::swapByteOrder(symtab.sel_ref_cnt);
2983 sys::swapByteOrder(symtab.refs);
2984 sys::swapByteOrder(symtab.cls_def_cnt);
2985 sys::swapByteOrder(symtab.cat_def_cnt);
2988 inline void swapStruct(struct objc_class_t &objc_class) {
2989 sys::swapByteOrder(objc_class.isa);
2990 sys::swapByteOrder(objc_class.super_class);
2991 sys::swapByteOrder(objc_class.name);
2992 sys::swapByteOrder(objc_class.version);
2993 sys::swapByteOrder(objc_class.info);
2994 sys::swapByteOrder(objc_class.instance_size);
2995 sys::swapByteOrder(objc_class.ivars);
2996 sys::swapByteOrder(objc_class.methodLists);
2997 sys::swapByteOrder(objc_class.cache);
2998 sys::swapByteOrder(objc_class.protocols);
3001 inline void swapStruct(struct objc_category_t &objc_category) {
3002 sys::swapByteOrder(objc_category.category_name);
3003 sys::swapByteOrder(objc_category.class_name);
3004 sys::swapByteOrder(objc_category.instance_methods);
3005 sys::swapByteOrder(objc_category.class_methods);
3006 sys::swapByteOrder(objc_category.protocols);
3009 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3010 sys::swapByteOrder(objc_ivar_list.ivar_count);
3013 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3014 sys::swapByteOrder(objc_ivar.ivar_name);
3015 sys::swapByteOrder(objc_ivar.ivar_type);
3016 sys::swapByteOrder(objc_ivar.ivar_offset);
3019 inline void swapStruct(struct objc_method_list_t &method_list) {
3020 sys::swapByteOrder(method_list.obsolete);
3021 sys::swapByteOrder(method_list.method_count);
3024 inline void swapStruct(struct objc_method_t &method) {
3025 sys::swapByteOrder(method.method_name);
3026 sys::swapByteOrder(method.method_types);
3027 sys::swapByteOrder(method.method_imp);
3030 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3031 sys::swapByteOrder(protocol_list.next);
3032 sys::swapByteOrder(protocol_list.count);
3035 inline void swapStruct(struct objc_protocol_t &protocol) {
3036 sys::swapByteOrder(protocol.isa);
3037 sys::swapByteOrder(protocol.protocol_name);
3038 sys::swapByteOrder(protocol.protocol_list);
3039 sys::swapByteOrder(protocol.instance_methods);
3040 sys::swapByteOrder(protocol.class_methods);
3043 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3044 sys::swapByteOrder(mdl.count);
3047 inline void swapStruct(struct objc_method_description_t &md) {
3048 sys::swapByteOrder(md.name);
3049 sys::swapByteOrder(md.types);
3052 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3053 struct DisassembleInfo *info);
3055 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3056 // to an Objective-C class and returns the class name. It is also passed the
3057 // address of the pointer, so when the pointer is zero as it can be in an .o
3058 // file, that is used to look for an external relocation entry with a symbol
3060 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3061 uint64_t ReferenceValue,
3062 struct DisassembleInfo *info) {
3064 uint32_t offset, left;
3067 // The pointer_value can be 0 in an object file and have a relocation
3068 // entry for the class symbol at the ReferenceValue (the address of the
3070 if (pointer_value == 0) {
3071 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3072 if (r == nullptr || left < sizeof(uint64_t))
3075 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3076 if (symbol_name == nullptr)
3078 const char *class_name = strrchr(symbol_name, '$');
3079 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3080 return class_name + 2;
3085 // The case were the pointer_value is non-zero and points to a class defined
3086 // in this Mach-O file.
3087 r = get_pointer_64(pointer_value, offset, left, S, info);
3088 if (r == nullptr || left < sizeof(struct class64_t))
3091 memcpy(&c, r, sizeof(struct class64_t));
3092 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3096 r = get_pointer_64(c.data, offset, left, S, info);
3097 if (r == nullptr || left < sizeof(struct class_ro64_t))
3099 struct class_ro64_t cro;
3100 memcpy(&cro, r, sizeof(struct class_ro64_t));
3101 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3105 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3109 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3110 // pointer to a cfstring and returns its name or nullptr.
3111 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3112 struct DisassembleInfo *info) {
3113 const char *r, *name;
3114 uint32_t offset, left;
3116 struct cfstring64_t cfs;
3117 uint64_t cfs_characters;
3119 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3120 if (r == nullptr || left < sizeof(struct cfstring64_t))
3122 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3123 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3125 if (cfs.characters == 0) {
3127 const char *symbol_name = get_symbol_64(
3128 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3129 if (symbol_name == nullptr)
3131 cfs_characters = n_value;
3133 cfs_characters = cfs.characters;
3134 name = get_pointer_64(cfs_characters, offset, left, S, info);
3139 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
3140 // of a pointer to an Objective-C selector reference when the pointer value is
3141 // zero as in a .o file and is likely to have a external relocation entry with
3142 // who's symbol's n_value is the real pointer to the selector name. If that is
3143 // the case the real pointer to the selector name is returned else 0 is
3145 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3146 struct DisassembleInfo *info) {
3147 uint32_t offset, left;
3150 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3151 if (r == nullptr || left < sizeof(uint64_t))
3154 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3155 if (symbol_name == nullptr)
3160 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3161 const char *sectname) {
3162 for (const SectionRef &Section : O->sections()) {
3164 Section.getName(SectName);
3165 DataRefImpl Ref = Section.getRawDataRefImpl();
3166 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3167 if (SegName == segname && SectName == sectname)
3170 return SectionRef();
3174 walk_pointer_list_64(const char *listname, const SectionRef S,
3175 MachOObjectFile *O, struct DisassembleInfo *info,
3176 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3177 if (S == SectionRef())
3181 S.getName(SectName);
3182 DataRefImpl Ref = S.getRawDataRefImpl();
3183 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3184 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3187 S.getContents(BytesStr);
3188 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3190 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3191 uint32_t left = S.getSize() - i;
3192 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3194 memcpy(&p, Contents + i, size);
3195 if (i + sizeof(uint64_t) > S.getSize())
3196 outs() << listname << " list pointer extends past end of (" << SegName
3197 << "," << SectName << ") section\n";
3198 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3200 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3201 sys::swapByteOrder(p);
3203 uint64_t n_value = 0;
3204 const char *name = get_symbol_64(i, S, info, n_value, p);
3205 if (name == nullptr)
3206 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3209 outs() << format("0x%" PRIx64, n_value);
3211 outs() << " + " << format("0x%" PRIx64, p);
3213 outs() << format("0x%" PRIx64, p);
3214 if (name != nullptr)
3215 outs() << " " << name;
3225 walk_pointer_list_32(const char *listname, const SectionRef S,
3226 MachOObjectFile *O, struct DisassembleInfo *info,
3227 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3228 if (S == SectionRef())
3232 S.getName(SectName);
3233 DataRefImpl Ref = S.getRawDataRefImpl();
3234 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3235 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3238 S.getContents(BytesStr);
3239 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3241 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3242 uint32_t left = S.getSize() - i;
3243 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3245 memcpy(&p, Contents + i, size);
3246 if (i + sizeof(uint32_t) > S.getSize())
3247 outs() << listname << " list pointer extends past end of (" << SegName
3248 << "," << SectName << ") section\n";
3249 uint32_t Address = S.getAddress() + i;
3250 outs() << format("%08" PRIx32, Address) << " ";
3252 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3253 sys::swapByteOrder(p);
3254 outs() << format("0x%" PRIx32, p);
3256 const char *name = get_symbol_32(i, S, info, p);
3257 if (name != nullptr)
3258 outs() << " " << name;
3266 static void print_layout_map(const char *layout_map, uint32_t left) {
3267 if (layout_map == nullptr)
3269 outs() << " layout map: ";
3271 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3274 } while (*layout_map != '\0' && left != 0);
3278 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3279 uint32_t offset, left;
3281 const char *layout_map;
3285 layout_map = get_pointer_64(p, offset, left, S, info);
3286 print_layout_map(layout_map, left);
3289 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3290 uint32_t offset, left;
3292 const char *layout_map;
3296 layout_map = get_pointer_32(p, offset, left, S, info);
3297 print_layout_map(layout_map, left);
3300 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3301 const char *indent) {
3302 struct method_list64_t ml;
3303 struct method64_t m;
3305 uint32_t offset, xoffset, left, i;
3307 const char *name, *sym_name;
3310 r = get_pointer_64(p, offset, left, S, info);
3313 memset(&ml, '\0', sizeof(struct method_list64_t));
3314 if (left < sizeof(struct method_list64_t)) {
3315 memcpy(&ml, r, left);
3316 outs() << " (method_list_t entends past the end of the section)\n";
3318 memcpy(&ml, r, sizeof(struct method_list64_t));
3319 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3321 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3322 outs() << indent << "\t\t count " << ml.count << "\n";
3324 p += sizeof(struct method_list64_t);
3325 offset += sizeof(struct method_list64_t);
3326 for (i = 0; i < ml.count; i++) {
3327 r = get_pointer_64(p, offset, left, S, info);
3330 memset(&m, '\0', sizeof(struct method64_t));
3331 if (left < sizeof(struct method64_t)) {
3332 memcpy(&m, r, left);
3333 outs() << indent << " (method_t extends past the end of the section)\n";
3335 memcpy(&m, r, sizeof(struct method64_t));
3336 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3339 outs() << indent << "\t\t name ";
3340 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3341 info, n_value, m.name);
3343 if (info->verbose && sym_name != nullptr)
3346 outs() << format("0x%" PRIx64, n_value);
3348 outs() << " + " << format("0x%" PRIx64, m.name);
3350 outs() << format("0x%" PRIx64, m.name);
3351 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3352 if (name != nullptr)
3353 outs() << format(" %.*s", left, name);
3356 outs() << indent << "\t\t types ";
3357 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3358 info, n_value, m.types);
3360 if (info->verbose && sym_name != nullptr)
3363 outs() << format("0x%" PRIx64, n_value);
3365 outs() << " + " << format("0x%" PRIx64, m.types);
3367 outs() << format("0x%" PRIx64, m.types);
3368 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3369 if (name != nullptr)
3370 outs() << format(" %.*s", left, name);
3373 outs() << indent << "\t\t imp ";
3374 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3376 if (info->verbose && name == nullptr) {
3378 outs() << format("0x%" PRIx64, n_value) << " ";
3380 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3382 outs() << format("0x%" PRIx64, m.imp) << " ";
3384 if (name != nullptr)
3388 p += sizeof(struct method64_t);
3389 offset += sizeof(struct method64_t);
3393 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3394 const char *indent) {
3395 struct method_list32_t ml;
3396 struct method32_t m;
3397 const char *r, *name;
3398 uint32_t offset, xoffset, left, i;
3401 r = get_pointer_32(p, offset, left, S, info);
3404 memset(&ml, '\0', sizeof(struct method_list32_t));
3405 if (left < sizeof(struct method_list32_t)) {
3406 memcpy(&ml, r, left);
3407 outs() << " (method_list_t entends past the end of the section)\n";
3409 memcpy(&ml, r, sizeof(struct method_list32_t));
3410 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3412 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3413 outs() << indent << "\t\t count " << ml.count << "\n";
3415 p += sizeof(struct method_list32_t);
3416 offset += sizeof(struct method_list32_t);
3417 for (i = 0; i < ml.count; i++) {
3418 r = get_pointer_32(p, offset, left, S, info);
3421 memset(&m, '\0', sizeof(struct method32_t));
3422 if (left < sizeof(struct method32_t)) {
3423 memcpy(&ml, r, left);
3424 outs() << indent << " (method_t entends past the end of the section)\n";
3426 memcpy(&m, r, sizeof(struct method32_t));
3427 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3430 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3431 name = get_pointer_32(m.name, xoffset, left, xS, info);
3432 if (name != nullptr)
3433 outs() << format(" %.*s", left, name);
3436 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3437 name = get_pointer_32(m.types, xoffset, left, xS, info);
3438 if (name != nullptr)
3439 outs() << format(" %.*s", left, name);
3442 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3443 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3445 if (name != nullptr)
3446 outs() << " " << name;
3449 p += sizeof(struct method32_t);
3450 offset += sizeof(struct method32_t);
3454 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3455 uint32_t offset, left, xleft;
3457 struct objc_method_list_t method_list;
3458 struct objc_method_t method;
3459 const char *r, *methods, *name, *SymbolName;
3462 r = get_pointer_32(p, offset, left, S, info, true);
3467 if (left > sizeof(struct objc_method_list_t)) {
3468 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3470 outs() << "\t\t objc_method_list extends past end of the section\n";
3471 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3472 memcpy(&method_list, r, left);
3474 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3475 swapStruct(method_list);
3477 outs() << "\t\t obsolete "
3478 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3479 outs() << "\t\t method_count " << method_list.method_count << "\n";
3481 methods = r + sizeof(struct objc_method_list_t);
3482 for (i = 0; i < method_list.method_count; i++) {
3483 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3484 outs() << "\t\t remaining method's extend past the of the section\n";
3487 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3488 sizeof(struct objc_method_t));
3489 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3492 outs() << "\t\t method_name "
3493 << format("0x%08" PRIx32, method.method_name);
3494 if (info->verbose) {
3495 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3496 if (name != nullptr)
3497 outs() << format(" %.*s", xleft, name);
3499 outs() << " (not in an __OBJC section)";
3503 outs() << "\t\t method_types "
3504 << format("0x%08" PRIx32, method.method_types);
3505 if (info->verbose) {
3506 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3507 if (name != nullptr)
3508 outs() << format(" %.*s", xleft, name);
3510 outs() << " (not in an __OBJC section)";
3514 outs() << "\t\t method_imp "
3515 << format("0x%08" PRIx32, method.method_imp) << " ";
3516 if (info->verbose) {
3517 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3518 if (SymbolName != nullptr)
3519 outs() << SymbolName;
3526 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3527 struct protocol_list64_t pl;
3528 uint64_t q, n_value;
3529 struct protocol64_t pc;
3531 uint32_t offset, xoffset, left, i;
3533 const char *name, *sym_name;
3535 r = get_pointer_64(p, offset, left, S, info);
3538 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3539 if (left < sizeof(struct protocol_list64_t)) {
3540 memcpy(&pl, r, left);
3541 outs() << " (protocol_list_t entends past the end of the section)\n";
3543 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3544 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3546 outs() << " count " << pl.count << "\n";
3548 p += sizeof(struct protocol_list64_t);
3549 offset += sizeof(struct protocol_list64_t);
3550 for (i = 0; i < pl.count; i++) {
3551 r = get_pointer_64(p, offset, left, S, info);
3555 if (left < sizeof(uint64_t)) {
3556 memcpy(&q, r, left);
3557 outs() << " (protocol_t * entends past the end of the section)\n";
3559 memcpy(&q, r, sizeof(uint64_t));
3560 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3561 sys::swapByteOrder(q);
3563 outs() << "\t\t list[" << i << "] ";
3564 sym_name = get_symbol_64(offset, S, info, n_value, q);
3566 if (info->verbose && sym_name != nullptr)
3569 outs() << format("0x%" PRIx64, n_value);
3571 outs() << " + " << format("0x%" PRIx64, q);
3573 outs() << format("0x%" PRIx64, q);
3574 outs() << " (struct protocol_t *)\n";
3576 r = get_pointer_64(q + n_value, offset, left, S, info);
3579 memset(&pc, '\0', sizeof(struct protocol64_t));
3580 if (left < sizeof(struct protocol64_t)) {
3581 memcpy(&pc, r, left);
3582 outs() << " (protocol_t entends past the end of the section)\n";
3584 memcpy(&pc, r, sizeof(struct protocol64_t));
3585 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3588 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3590 outs() << "\t\t\t name ";
3591 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3592 info, n_value, pc.name);
3594 if (info->verbose && sym_name != nullptr)
3597 outs() << format("0x%" PRIx64, n_value);
3599 outs() << " + " << format("0x%" PRIx64, pc.name);
3601 outs() << format("0x%" PRIx64, pc.name);
3602 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3603 if (name != nullptr)
3604 outs() << format(" %.*s", left, name);
3607 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3609 outs() << "\t\t instanceMethods ";
3611 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3612 S, info, n_value, pc.instanceMethods);
3614 if (info->verbose && sym_name != nullptr)
3617 outs() << format("0x%" PRIx64, n_value);
3618 if (pc.instanceMethods != 0)
3619 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3621 outs() << format("0x%" PRIx64, pc.instanceMethods);
3622 outs() << " (struct method_list_t *)\n";
3623 if (pc.instanceMethods + n_value != 0)
3624 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3626 outs() << "\t\t classMethods ";
3628 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3629 info, n_value, pc.classMethods);
3631 if (info->verbose && sym_name != nullptr)
3634 outs() << format("0x%" PRIx64, n_value);
3635 if (pc.classMethods != 0)
3636 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3638 outs() << format("0x%" PRIx64, pc.classMethods);
3639 outs() << " (struct method_list_t *)\n";
3640 if (pc.classMethods + n_value != 0)
3641 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3643 outs() << "\t optionalInstanceMethods "
3644 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3645 outs() << "\t optionalClassMethods "
3646 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3647 outs() << "\t instanceProperties "
3648 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3650 p += sizeof(uint64_t);
3651 offset += sizeof(uint64_t);
3655 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3656 struct protocol_list32_t pl;
3658 struct protocol32_t pc;
3660 uint32_t offset, xoffset, left, i;
3664 r = get_pointer_32(p, offset, left, S, info);
3667 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3668 if (left < sizeof(struct protocol_list32_t)) {
3669 memcpy(&pl, r, left);
3670 outs() << " (protocol_list_t entends past the end of the section)\n";
3672 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3673 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3675 outs() << " count " << pl.count << "\n";
3677 p += sizeof(struct protocol_list32_t);
3678 offset += sizeof(struct protocol_list32_t);
3679 for (i = 0; i < pl.count; i++) {
3680 r = get_pointer_32(p, offset, left, S, info);
3684 if (left < sizeof(uint32_t)) {
3685 memcpy(&q, r, left);
3686 outs() << " (protocol_t * entends past the end of the section)\n";
3688 memcpy(&q, r, sizeof(uint32_t));
3689 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3690 sys::swapByteOrder(q);
3691 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3692 << " (struct protocol_t *)\n";
3693 r = get_pointer_32(q, offset, left, S, info);
3696 memset(&pc, '\0', sizeof(struct protocol32_t));
3697 if (left < sizeof(struct protocol32_t)) {
3698 memcpy(&pc, r, left);
3699 outs() << " (protocol_t entends past the end of the section)\n";
3701 memcpy(&pc, r, sizeof(struct protocol32_t));
3702 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3704 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3705 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3706 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3707 if (name != nullptr)
3708 outs() << format(" %.*s", left, name);
3710 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3711 outs() << "\t\t instanceMethods "
3712 << format("0x%" PRIx32, pc.instanceMethods)
3713 << " (struct method_list_t *)\n";
3714 if (pc.instanceMethods != 0)
3715 print_method_list32_t(pc.instanceMethods, info, "\t");
3716 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3717 << " (struct method_list_t *)\n";
3718 if (pc.classMethods != 0)
3719 print_method_list32_t(pc.classMethods, info, "\t");
3720 outs() << "\t optionalInstanceMethods "
3721 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3722 outs() << "\t optionalClassMethods "
3723 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3724 outs() << "\t instanceProperties "
3725 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3726 p += sizeof(uint32_t);
3727 offset += sizeof(uint32_t);
3731 static void print_indent(uint32_t indent) {
3732 for (uint32_t i = 0; i < indent;) {
3733 if (indent - i >= 8) {
3737 for (uint32_t j = i; j < indent; j++)
3744 static bool print_method_description_list(uint32_t p, uint32_t indent,
3745 struct DisassembleInfo *info) {
3746 uint32_t offset, left, xleft;
3748 struct objc_method_description_list_t mdl;
3749 struct objc_method_description_t md;
3750 const char *r, *list, *name;
3753 r = get_pointer_32(p, offset, left, S, info, true);
3758 if (left > sizeof(struct objc_method_description_list_t)) {
3759 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3761 print_indent(indent);
3762 outs() << " objc_method_description_list extends past end of the section\n";
3763 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3764 memcpy(&mdl, r, left);
3766 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3769 print_indent(indent);
3770 outs() << " count " << mdl.count << "\n";
3772 list = r + sizeof(struct objc_method_description_list_t);
3773 for (i = 0; i < mdl.count; i++) {
3774 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3775 print_indent(indent);
3776 outs() << " remaining list entries extend past the of the section\n";
3779 print_indent(indent);
3780 outs() << " list[" << i << "]\n";
3781 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3782 sizeof(struct objc_method_description_t));
3783 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3786 print_indent(indent);
3787 outs() << " name " << format("0x%08" PRIx32, md.name);
3788 if (info->verbose) {
3789 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3790 if (name != nullptr)
3791 outs() << format(" %.*s", xleft, name);
3793 outs() << " (not in an __OBJC section)";
3797 print_indent(indent);
3798 outs() << " types " << format("0x%08" PRIx32, md.types);
3799 if (info->verbose) {
3800 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3801 if (name != nullptr)
3802 outs() << format(" %.*s", xleft, name);
3804 outs() << " (not in an __OBJC section)";
3811 static bool print_protocol_list(uint32_t p, uint32_t indent,
3812 struct DisassembleInfo *info);
3814 static bool print_protocol(uint32_t p, uint32_t indent,
3815 struct DisassembleInfo *info) {
3816 uint32_t offset, left;
3818 struct objc_protocol_t protocol;
3819 const char *r, *name;
3821 r = get_pointer_32(p, offset, left, S, info, true);
3826 if (left >= sizeof(struct objc_protocol_t)) {
3827 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3829 print_indent(indent);
3830 outs() << " Protocol extends past end of the section\n";
3831 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3832 memcpy(&protocol, r, left);
3834 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3835 swapStruct(protocol);
3837 print_indent(indent);
3838 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3841 print_indent(indent);
3842 outs() << " protocol_name "
3843 << format("0x%08" PRIx32, protocol.protocol_name);
3844 if (info->verbose) {
3845 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3846 if (name != nullptr)
3847 outs() << format(" %.*s", left, name);
3849 outs() << " (not in an __OBJC section)";
3853 print_indent(indent);
3854 outs() << " protocol_list "
3855 << format("0x%08" PRIx32, protocol.protocol_list);
3856 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3857 outs() << " (not in an __OBJC section)\n";
3859 print_indent(indent);
3860 outs() << " instance_methods "
3861 << format("0x%08" PRIx32, protocol.instance_methods);
3862 if (print_method_description_list(protocol.instance_methods, indent, info))
3863 outs() << " (not in an __OBJC section)\n";
3865 print_indent(indent);
3866 outs() << " class_methods "
3867 << format("0x%08" PRIx32, protocol.class_methods);
3868 if (print_method_description_list(protocol.class_methods, indent, info))
3869 outs() << " (not in an __OBJC section)\n";
3874 static bool print_protocol_list(uint32_t p, uint32_t indent,
3875 struct DisassembleInfo *info) {
3876 uint32_t offset, left, l;
3878 struct objc_protocol_list_t protocol_list;
3879 const char *r, *list;
3882 r = get_pointer_32(p, offset, left, S, info, true);
3887 if (left > sizeof(struct objc_protocol_list_t)) {
3888 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3890 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3891 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3892 memcpy(&protocol_list, r, left);
3894 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3895 swapStruct(protocol_list);
3897 print_indent(indent);
3898 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3900 print_indent(indent);
3901 outs() << " count " << protocol_list.count << "\n";
3903 list = r + sizeof(struct objc_protocol_list_t);
3904 for (i = 0; i < protocol_list.count; i++) {
3905 if ((i + 1) * sizeof(uint32_t) > left) {
3906 outs() << "\t\t remaining list entries extend past the of the section\n";
3909 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3910 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3911 sys::swapByteOrder(l);
3913 print_indent(indent);
3914 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3915 if (print_protocol(l, indent, info))
3916 outs() << "(not in an __OBJC section)\n";
3921 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3922 struct ivar_list64_t il;
3925 uint32_t offset, xoffset, left, j;
3927 const char *name, *sym_name, *ivar_offset_p;
3928 uint64_t ivar_offset, n_value;
3930 r = get_pointer_64(p, offset, left, S, info);
3933 memset(&il, '\0', sizeof(struct ivar_list64_t));
3934 if (left < sizeof(struct ivar_list64_t)) {
3935 memcpy(&il, r, left);
3936 outs() << " (ivar_list_t entends past the end of the section)\n";
3938 memcpy(&il, r, sizeof(struct ivar_list64_t));
3939 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3941 outs() << " entsize " << il.entsize << "\n";
3942 outs() << " count " << il.count << "\n";
3944 p += sizeof(struct ivar_list64_t);
3945 offset += sizeof(struct ivar_list64_t);
3946 for (j = 0; j < il.count; j++) {
3947 r = get_pointer_64(p, offset, left, S, info);
3950 memset(&i, '\0', sizeof(struct ivar64_t));
3951 if (left < sizeof(struct ivar64_t)) {
3952 memcpy(&i, r, left);
3953 outs() << " (ivar_t entends past the end of the section)\n";
3955 memcpy(&i, r, sizeof(struct ivar64_t));
3956 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3959 outs() << "\t\t\t offset ";
3960 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3961 info, n_value, i.offset);
3963 if (info->verbose && sym_name != nullptr)
3966 outs() << format("0x%" PRIx64, n_value);
3968 outs() << " + " << format("0x%" PRIx64, i.offset);
3970 outs() << format("0x%" PRIx64, i.offset);
3971 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3972 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3973 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3974 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3975 sys::swapByteOrder(ivar_offset);
3976 outs() << " " << ivar_offset << "\n";
3980 outs() << "\t\t\t name ";
3981 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
3984 if (info->verbose && sym_name != nullptr)
3987 outs() << format("0x%" PRIx64, n_value);
3989 outs() << " + " << format("0x%" PRIx64, i.name);
3991 outs() << format("0x%" PRIx64, i.name);
3992 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
3993 if (name != nullptr)
3994 outs() << format(" %.*s", left, name);
3997 outs() << "\t\t\t type ";
3998 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4000 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4002 if (info->verbose && sym_name != nullptr)
4005 outs() << format("0x%" PRIx64, n_value);
4007 outs() << " + " << format("0x%" PRIx64, i.type);
4009 outs() << format("0x%" PRIx64, i.type);
4010 if (name != nullptr)
4011 outs() << format(" %.*s", left, name);
4014 outs() << "\t\t\talignment " << i.alignment << "\n";
4015 outs() << "\t\t\t size " << i.size << "\n";
4017 p += sizeof(struct ivar64_t);
4018 offset += sizeof(struct ivar64_t);
4022 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4023 struct ivar_list32_t il;
4026 uint32_t offset, xoffset, left, j;
4028 const char *name, *ivar_offset_p;
4029 uint32_t ivar_offset;
4031 r = get_pointer_32(p, offset, left, S, info);
4034 memset(&il, '\0', sizeof(struct ivar_list32_t));
4035 if (left < sizeof(struct ivar_list32_t)) {
4036 memcpy(&il, r, left);
4037 outs() << " (ivar_list_t entends past the end of the section)\n";
4039 memcpy(&il, r, sizeof(struct ivar_list32_t));
4040 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4042 outs() << " entsize " << il.entsize << "\n";
4043 outs() << " count " << il.count << "\n";
4045 p += sizeof(struct ivar_list32_t);
4046 offset += sizeof(struct ivar_list32_t);
4047 for (j = 0; j < il.count; j++) {
4048 r = get_pointer_32(p, offset, left, S, info);
4051 memset(&i, '\0', sizeof(struct ivar32_t));
4052 if (left < sizeof(struct ivar32_t)) {
4053 memcpy(&i, r, left);
4054 outs() << " (ivar_t entends past the end of the section)\n";
4056 memcpy(&i, r, sizeof(struct ivar32_t));
4057 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4060 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4061 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4062 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4063 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4064 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4065 sys::swapByteOrder(ivar_offset);
4066 outs() << " " << ivar_offset << "\n";
4070 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4071 name = get_pointer_32(i.name, xoffset, left, xS, info);
4072 if (name != nullptr)
4073 outs() << format(" %.*s", left, name);
4076 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4077 name = get_pointer_32(i.type, xoffset, left, xS, info);
4078 if (name != nullptr)
4079 outs() << format(" %.*s", left, name);
4082 outs() << "\t\t\talignment " << i.alignment << "\n";
4083 outs() << "\t\t\t size " << i.size << "\n";
4085 p += sizeof(struct ivar32_t);
4086 offset += sizeof(struct ivar32_t);
4090 static void print_objc_property_list64(uint64_t p,
4091 struct DisassembleInfo *info) {
4092 struct objc_property_list64 opl;
4093 struct objc_property64 op;
4095 uint32_t offset, xoffset, left, j;
4097 const char *name, *sym_name;
4100 r = get_pointer_64(p, offset, left, S, info);
4103 memset(&opl, '\0', sizeof(struct objc_property_list64));
4104 if (left < sizeof(struct objc_property_list64)) {
4105 memcpy(&opl, r, left);
4106 outs() << " (objc_property_list entends past the end of the section)\n";
4108 memcpy(&opl, r, sizeof(struct objc_property_list64));
4109 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4111 outs() << " entsize " << opl.entsize << "\n";
4112 outs() << " count " << opl.count << "\n";
4114 p += sizeof(struct objc_property_list64);
4115 offset += sizeof(struct objc_property_list64);
4116 for (j = 0; j < opl.count; j++) {
4117 r = get_pointer_64(p, offset, left, S, info);
4120 memset(&op, '\0', sizeof(struct objc_property64));
4121 if (left < sizeof(struct objc_property64)) {
4122 memcpy(&op, r, left);
4123 outs() << " (objc_property entends past the end of the section)\n";
4125 memcpy(&op, r, sizeof(struct objc_property64));
4126 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4129 outs() << "\t\t\t name ";
4130 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4131 info, n_value, op.name);
4133 if (info->verbose && sym_name != nullptr)
4136 outs() << format("0x%" PRIx64, n_value);
4138 outs() << " + " << format("0x%" PRIx64, op.name);
4140 outs() << format("0x%" PRIx64, op.name);
4141 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4142 if (name != nullptr)
4143 outs() << format(" %.*s", left, name);
4146 outs() << "\t\t\tattributes ";
4148 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4149 info, n_value, op.attributes);
4151 if (info->verbose && sym_name != nullptr)
4154 outs() << format("0x%" PRIx64, n_value);
4155 if (op.attributes != 0)
4156 outs() << " + " << format("0x%" PRIx64, op.attributes);
4158 outs() << format("0x%" PRIx64, op.attributes);
4159 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4160 if (name != nullptr)
4161 outs() << format(" %.*s", left, name);
4164 p += sizeof(struct objc_property64);
4165 offset += sizeof(struct objc_property64);
4169 static void print_objc_property_list32(uint32_t p,
4170 struct DisassembleInfo *info) {
4171 struct objc_property_list32 opl;
4172 struct objc_property32 op;
4174 uint32_t offset, xoffset, left, j;
4178 r = get_pointer_32(p, offset, left, S, info);
4181 memset(&opl, '\0', sizeof(struct objc_property_list32));
4182 if (left < sizeof(struct objc_property_list32)) {
4183 memcpy(&opl, r, left);
4184 outs() << " (objc_property_list entends past the end of the section)\n";
4186 memcpy(&opl, r, sizeof(struct objc_property_list32));
4187 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4189 outs() << " entsize " << opl.entsize << "\n";
4190 outs() << " count " << opl.count << "\n";
4192 p += sizeof(struct objc_property_list32);
4193 offset += sizeof(struct objc_property_list32);
4194 for (j = 0; j < opl.count; j++) {
4195 r = get_pointer_32(p, offset, left, S, info);
4198 memset(&op, '\0', sizeof(struct objc_property32));
4199 if (left < sizeof(struct objc_property32)) {
4200 memcpy(&op, r, left);
4201 outs() << " (objc_property entends past the end of the section)\n";
4203 memcpy(&op, r, sizeof(struct objc_property32));
4204 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4207 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4208 name = get_pointer_32(op.name, xoffset, left, xS, info);
4209 if (name != nullptr)
4210 outs() << format(" %.*s", left, name);
4213 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4214 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4215 if (name != nullptr)
4216 outs() << format(" %.*s", left, name);
4219 p += sizeof(struct objc_property32);
4220 offset += sizeof(struct objc_property32);
4224 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
4225 bool &is_meta_class) {
4226 struct class_ro64_t cro;
4228 uint32_t offset, xoffset, left;
4230 const char *name, *sym_name;
4233 r = get_pointer_64(p, offset, left, S, info);
4234 if (r == nullptr || left < sizeof(struct class_ro64_t))
4236 memset(&cro, '\0', sizeof(struct class_ro64_t));
4237 if (left < sizeof(struct class_ro64_t)) {
4238 memcpy(&cro, r, left);
4239 outs() << " (class_ro_t entends past the end of the section)\n";
4241 memcpy(&cro, r, sizeof(struct class_ro64_t));
4242 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4244 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4245 if (cro.flags & RO_META)
4246 outs() << " RO_META";
4247 if (cro.flags & RO_ROOT)
4248 outs() << " RO_ROOT";
4249 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4250 outs() << " RO_HAS_CXX_STRUCTORS";
4252 outs() << " instanceStart " << cro.instanceStart << "\n";
4253 outs() << " instanceSize " << cro.instanceSize << "\n";
4254 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4256 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4258 print_layout_map64(cro.ivarLayout, info);
4261 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4262 info, n_value, cro.name);
4264 if (info->verbose && sym_name != nullptr)
4267 outs() << format("0x%" PRIx64, n_value);
4269 outs() << " + " << format("0x%" PRIx64, cro.name);
4271 outs() << format("0x%" PRIx64, cro.name);
4272 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4273 if (name != nullptr)
4274 outs() << format(" %.*s", left, name);
4277 outs() << " baseMethods ";
4278 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4279 S, info, n_value, cro.baseMethods);
4281 if (info->verbose && sym_name != nullptr)
4284 outs() << format("0x%" PRIx64, n_value);
4285 if (cro.baseMethods != 0)
4286 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4288 outs() << format("0x%" PRIx64, cro.baseMethods);
4289 outs() << " (struct method_list_t *)\n";
4290 if (cro.baseMethods + n_value != 0)
4291 print_method_list64_t(cro.baseMethods + n_value, info, "");
4293 outs() << " baseProtocols ";
4295 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4296 info, n_value, cro.baseProtocols);
4298 if (info->verbose && sym_name != nullptr)
4301 outs() << format("0x%" PRIx64, n_value);
4302 if (cro.baseProtocols != 0)
4303 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4305 outs() << format("0x%" PRIx64, cro.baseProtocols);
4307 if (cro.baseProtocols + n_value != 0)
4308 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4310 outs() << " ivars ";
4311 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
4312 info, n_value, cro.ivars);
4314 if (info->verbose && sym_name != nullptr)
4317 outs() << format("0x%" PRIx64, n_value);
4319 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4321 outs() << format("0x%" PRIx64, cro.ivars);
4323 if (cro.ivars + n_value != 0)
4324 print_ivar_list64_t(cro.ivars + n_value, info);
4326 outs() << " weakIvarLayout ";
4328 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4329 info, n_value, cro.weakIvarLayout);
4331 if (info->verbose && sym_name != nullptr)
4334 outs() << format("0x%" PRIx64, n_value);
4335 if (cro.weakIvarLayout != 0)
4336 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4338 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4340 print_layout_map64(cro.weakIvarLayout + n_value, info);
4342 outs() << " baseProperties ";
4344 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4345 info, n_value, cro.baseProperties);
4347 if (info->verbose && sym_name != nullptr)
4350 outs() << format("0x%" PRIx64, n_value);
4351 if (cro.baseProperties != 0)
4352 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4354 outs() << format("0x%" PRIx64, cro.baseProperties);
4356 if (cro.baseProperties + n_value != 0)
4357 print_objc_property_list64(cro.baseProperties + n_value, info);
4359 is_meta_class = (cro.flags & RO_META) != 0;
4363 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
4364 bool &is_meta_class) {
4365 struct class_ro32_t cro;
4367 uint32_t offset, xoffset, left;
4371 r = get_pointer_32(p, offset, left, S, info);
4374 memset(&cro, '\0', sizeof(struct class_ro32_t));
4375 if (left < sizeof(struct class_ro32_t)) {
4376 memcpy(&cro, r, left);
4377 outs() << " (class_ro_t entends past the end of the section)\n";
4379 memcpy(&cro, r, sizeof(struct class_ro32_t));
4380 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4382 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4383 if (cro.flags & RO_META)
4384 outs() << " RO_META";
4385 if (cro.flags & RO_ROOT)
4386 outs() << " RO_ROOT";
4387 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4388 outs() << " RO_HAS_CXX_STRUCTORS";
4390 outs() << " instanceStart " << cro.instanceStart << "\n";
4391 outs() << " instanceSize " << cro.instanceSize << "\n";
4392 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4394 print_layout_map32(cro.ivarLayout, info);
4396 outs() << " name " << format("0x%" PRIx32, cro.name);
4397 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4398 if (name != nullptr)
4399 outs() << format(" %.*s", left, name);
4402 outs() << " baseMethods "
4403 << format("0x%" PRIx32, cro.baseMethods)
4404 << " (struct method_list_t *)\n";
4405 if (cro.baseMethods != 0)
4406 print_method_list32_t(cro.baseMethods, info, "");
4408 outs() << " baseProtocols "
4409 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4410 if (cro.baseProtocols != 0)
4411 print_protocol_list32_t(cro.baseProtocols, info);
4412 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4415 print_ivar_list32_t(cro.ivars, info);
4416 outs() << " weakIvarLayout "
4417 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4418 print_layout_map32(cro.weakIvarLayout, info);
4419 outs() << " baseProperties "
4420 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4421 if (cro.baseProperties != 0)
4422 print_objc_property_list32(cro.baseProperties, info);
4423 is_meta_class = (cro.flags & RO_META) != 0;
4427 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4430 uint32_t offset, left;
4433 uint64_t isa_n_value, n_value;
4435 r = get_pointer_64(p, offset, left, S, info);
4436 if (r == nullptr || left < sizeof(struct class64_t))
4438 memset(&c, '\0', sizeof(struct class64_t));
4439 if (left < sizeof(struct class64_t)) {
4440 memcpy(&c, r, left);
4441 outs() << " (class_t entends past the end of the section)\n";
4443 memcpy(&c, r, sizeof(struct class64_t));
4444 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4447 outs() << " isa " << format("0x%" PRIx64, c.isa);
4448 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4449 isa_n_value, c.isa);
4450 if (name != nullptr)
4451 outs() << " " << name;
4454 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4455 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4456 n_value, c.superclass);
4457 if (name != nullptr)
4458 outs() << " " << name;
4461 outs() << " cache " << format("0x%" PRIx64, c.cache);
4462 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4464 if (name != nullptr)
4465 outs() << " " << name;
4468 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4469 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4471 if (name != nullptr)
4472 outs() << " " << name;
4475 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4479 if (info->verbose && name != nullptr)
4482 outs() << format("0x%" PRIx64, n_value);
4484 outs() << " + " << format("0x%" PRIx64, c.data);
4486 outs() << format("0x%" PRIx64, c.data);
4487 outs() << " (struct class_ro_t *)";
4489 // This is a Swift class if some of the low bits of the pointer are set.
4490 if ((c.data + n_value) & 0x7)
4491 outs() << " Swift class";
4494 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4497 if (!is_meta_class &&
4498 c.isa + isa_n_value != p &&
4499 c.isa + isa_n_value != 0 &&
4500 info->depth < 100) {
4502 outs() << "Meta Class\n";
4503 print_class64_t(c.isa + isa_n_value, info);
4507 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4510 uint32_t offset, left;
4514 r = get_pointer_32(p, offset, left, S, info);
4517 memset(&c, '\0', sizeof(struct class32_t));
4518 if (left < sizeof(struct class32_t)) {
4519 memcpy(&c, r, left);
4520 outs() << " (class_t entends past the end of the section)\n";
4522 memcpy(&c, r, sizeof(struct class32_t));
4523 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4526 outs() << " isa " << format("0x%" PRIx32, c.isa);
4528 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4529 if (name != nullptr)
4530 outs() << " " << name;
4533 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4534 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4536 if (name != nullptr)
4537 outs() << " " << name;
4540 outs() << " cache " << format("0x%" PRIx32, c.cache);
4541 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4543 if (name != nullptr)
4544 outs() << " " << name;
4547 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4548 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4550 if (name != nullptr)
4551 outs() << " " << name;
4555 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4556 outs() << " data " << format("0x%" PRIx32, c.data)
4557 << " (struct class_ro_t *)";
4559 // This is a Swift class if some of the low bits of the pointer are set.
4561 outs() << " Swift class";
4564 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4567 if (!is_meta_class) {
4568 outs() << "Meta Class\n";
4569 print_class32_t(c.isa, info);
4573 static void print_objc_class_t(struct objc_class_t *objc_class,
4574 struct DisassembleInfo *info) {
4575 uint32_t offset, left, xleft;
4576 const char *name, *p, *ivar_list;
4579 struct objc_ivar_list_t objc_ivar_list;
4580 struct objc_ivar_t ivar;
4582 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4583 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4584 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4585 if (name != nullptr)
4586 outs() << format(" %.*s", left, name);
4588 outs() << " (not in an __OBJC section)";
4592 outs() << "\t super_class "
4593 << format("0x%08" PRIx32, objc_class->super_class);
4594 if (info->verbose) {
4595 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4596 if (name != nullptr)
4597 outs() << format(" %.*s", left, name);
4599 outs() << " (not in an __OBJC section)";
4603 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4604 if (info->verbose) {
4605 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4606 if (name != nullptr)
4607 outs() << format(" %.*s", left, name);
4609 outs() << " (not in an __OBJC section)";
4613 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4616 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4617 if (info->verbose) {
4618 if (CLS_GETINFO(objc_class, CLS_CLASS))
4619 outs() << " CLS_CLASS";
4620 else if (CLS_GETINFO(objc_class, CLS_META))
4621 outs() << " CLS_META";
4625 outs() << "\t instance_size "
4626 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4628 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4629 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4631 if (left > sizeof(struct objc_ivar_list_t)) {
4633 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4635 outs() << " (entends past the end of the section)\n";
4636 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4637 memcpy(&objc_ivar_list, p, left);
4639 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4640 swapStruct(objc_ivar_list);
4641 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4642 ivar_list = p + sizeof(struct objc_ivar_list_t);
4643 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4644 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4645 outs() << "\t\t remaining ivar's extend past the of the section\n";
4648 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4649 sizeof(struct objc_ivar_t));
4650 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4653 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4654 if (info->verbose) {
4655 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4656 if (name != nullptr)
4657 outs() << format(" %.*s", xleft, name);
4659 outs() << " (not in an __OBJC section)";
4663 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4664 if (info->verbose) {
4665 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4666 if (name != nullptr)
4667 outs() << format(" %.*s", xleft, name);
4669 outs() << " (not in an __OBJC section)";
4673 outs() << "\t\t ivar_offset "
4674 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4677 outs() << " (not in an __OBJC section)\n";
4680 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4681 if (print_method_list(objc_class->methodLists, info))
4682 outs() << " (not in an __OBJC section)\n";
4684 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4687 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4688 if (print_protocol_list(objc_class->protocols, 16, info))
4689 outs() << " (not in an __OBJC section)\n";
4692 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4693 struct DisassembleInfo *info) {
4694 uint32_t offset, left;
4698 outs() << "\t category name "
4699 << format("0x%08" PRIx32, objc_category->category_name);
4700 if (info->verbose) {
4701 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4703 if (name != nullptr)
4704 outs() << format(" %.*s", left, name);
4706 outs() << " (not in an __OBJC section)";
4710 outs() << "\t\t class name "
4711 << format("0x%08" PRIx32, objc_category->class_name);
4712 if (info->verbose) {
4714 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4715 if (name != nullptr)
4716 outs() << format(" %.*s", left, name);
4718 outs() << " (not in an __OBJC section)";
4722 outs() << "\t instance methods "
4723 << format("0x%08" PRIx32, objc_category->instance_methods);
4724 if (print_method_list(objc_category->instance_methods, info))
4725 outs() << " (not in an __OBJC section)\n";
4727 outs() << "\t class methods "
4728 << format("0x%08" PRIx32, objc_category->class_methods);
4729 if (print_method_list(objc_category->class_methods, info))
4730 outs() << " (not in an __OBJC section)\n";
4733 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4734 struct category64_t c;
4736 uint32_t offset, xoffset, left;
4738 const char *name, *sym_name;
4741 r = get_pointer_64(p, offset, left, S, info);
4744 memset(&c, '\0', sizeof(struct category64_t));
4745 if (left < sizeof(struct category64_t)) {
4746 memcpy(&c, r, left);
4747 outs() << " (category_t entends past the end of the section)\n";
4749 memcpy(&c, r, sizeof(struct category64_t));
4750 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4754 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4755 info, n_value, c.name);
4757 if (info->verbose && sym_name != nullptr)
4760 outs() << format("0x%" PRIx64, n_value);
4762 outs() << " + " << format("0x%" PRIx64, c.name);
4764 outs() << format("0x%" PRIx64, c.name);
4765 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4766 if (name != nullptr)
4767 outs() << format(" %.*s", left, name);
4771 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4774 if (info->verbose && sym_name != nullptr)
4777 outs() << format("0x%" PRIx64, n_value);
4779 outs() << " + " << format("0x%" PRIx64, c.cls);
4781 outs() << format("0x%" PRIx64, c.cls);
4783 if (c.cls + n_value != 0)
4784 print_class64_t(c.cls + n_value, info);
4786 outs() << " instanceMethods ";
4788 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4789 info, n_value, c.instanceMethods);
4791 if (info->verbose && sym_name != nullptr)
4794 outs() << format("0x%" PRIx64, n_value);
4795 if (c.instanceMethods != 0)
4796 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4798 outs() << format("0x%" PRIx64, c.instanceMethods);
4800 if (c.instanceMethods + n_value != 0)
4801 print_method_list64_t(c.instanceMethods + n_value, info, "");
4803 outs() << " classMethods ";
4804 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4805 S, info, n_value, c.classMethods);
4807 if (info->verbose && sym_name != nullptr)
4810 outs() << format("0x%" PRIx64, n_value);
4811 if (c.classMethods != 0)
4812 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4814 outs() << format("0x%" PRIx64, c.classMethods);
4816 if (c.classMethods + n_value != 0)
4817 print_method_list64_t(c.classMethods + n_value, info, "");
4819 outs() << " protocols ";
4820 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4821 info, n_value, c.protocols);
4823 if (info->verbose && sym_name != nullptr)
4826 outs() << format("0x%" PRIx64, n_value);
4827 if (c.protocols != 0)
4828 outs() << " + " << format("0x%" PRIx64, c.protocols);
4830 outs() << format("0x%" PRIx64, c.protocols);
4832 if (c.protocols + n_value != 0)
4833 print_protocol_list64_t(c.protocols + n_value, info);
4835 outs() << "instanceProperties ";
4837 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4838 S, info, n_value, c.instanceProperties);
4840 if (info->verbose && sym_name != nullptr)
4843 outs() << format("0x%" PRIx64, n_value);
4844 if (c.instanceProperties != 0)
4845 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4847 outs() << format("0x%" PRIx64, c.instanceProperties);
4849 if (c.instanceProperties + n_value != 0)
4850 print_objc_property_list64(c.instanceProperties + n_value, info);
4853 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4854 struct category32_t c;
4856 uint32_t offset, left;
4860 r = get_pointer_32(p, offset, left, S, info);
4863 memset(&c, '\0', sizeof(struct category32_t));
4864 if (left < sizeof(struct category32_t)) {
4865 memcpy(&c, r, left);
4866 outs() << " (category_t entends past the end of the section)\n";
4868 memcpy(&c, r, sizeof(struct category32_t));
4869 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4872 outs() << " name " << format("0x%" PRIx32, c.name);
4873 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4876 outs() << " " << name;
4879 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4881 print_class32_t(c.cls, info);
4882 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4884 if (c.instanceMethods != 0)
4885 print_method_list32_t(c.instanceMethods, info, "");
4886 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4888 if (c.classMethods != 0)
4889 print_method_list32_t(c.classMethods, info, "");
4890 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4891 if (c.protocols != 0)
4892 print_protocol_list32_t(c.protocols, info);
4893 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4895 if (c.instanceProperties != 0)
4896 print_objc_property_list32(c.instanceProperties, info);
4899 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4900 uint32_t i, left, offset, xoffset;
4901 uint64_t p, n_value;
4902 struct message_ref64 mr;
4903 const char *name, *sym_name;
4907 if (S == SectionRef())
4911 S.getName(SectName);
4912 DataRefImpl Ref = S.getRawDataRefImpl();
4913 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4914 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4916 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4917 p = S.getAddress() + i;
4918 r = get_pointer_64(p, offset, left, S, info);
4921 memset(&mr, '\0', sizeof(struct message_ref64));
4922 if (left < sizeof(struct message_ref64)) {
4923 memcpy(&mr, r, left);
4924 outs() << " (message_ref entends past the end of the section)\n";
4926 memcpy(&mr, r, sizeof(struct message_ref64));
4927 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4931 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4934 outs() << format("0x%" PRIx64, n_value) << " ";
4936 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4938 outs() << format("0x%" PRIx64, mr.imp) << " ";
4939 if (name != nullptr)
4940 outs() << " " << name;
4944 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4945 info, n_value, mr.sel);
4947 if (info->verbose && sym_name != nullptr)
4950 outs() << format("0x%" PRIx64, n_value);
4952 outs() << " + " << format("0x%" PRIx64, mr.sel);
4954 outs() << format("0x%" PRIx64, mr.sel);
4955 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4956 if (name != nullptr)
4957 outs() << format(" %.*s", left, name);
4960 offset += sizeof(struct message_ref64);
4964 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
4965 uint32_t i, left, offset, xoffset, p;
4966 struct message_ref32 mr;
4967 const char *name, *r;
4970 if (S == SectionRef())
4974 S.getName(SectName);
4975 DataRefImpl Ref = S.getRawDataRefImpl();
4976 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4977 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4979 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4980 p = S.getAddress() + i;
4981 r = get_pointer_32(p, offset, left, S, info);
4984 memset(&mr, '\0', sizeof(struct message_ref32));
4985 if (left < sizeof(struct message_ref32)) {
4986 memcpy(&mr, r, left);
4987 outs() << " (message_ref entends past the end of the section)\n";
4989 memcpy(&mr, r, sizeof(struct message_ref32));
4990 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4993 outs() << " imp " << format("0x%" PRIx32, mr.imp);
4994 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
4996 if (name != nullptr)
4997 outs() << " " << name;
5000 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5001 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5002 if (name != nullptr)
5003 outs() << " " << name;
5006 offset += sizeof(struct message_ref32);
5010 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5011 uint32_t left, offset, swift_version;
5013 struct objc_image_info64 o;
5016 if (S == SectionRef())
5020 S.getName(SectName);
5021 DataRefImpl Ref = S.getRawDataRefImpl();
5022 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5023 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5025 r = get_pointer_64(p, offset, left, S, info);
5028 memset(&o, '\0', sizeof(struct objc_image_info64));
5029 if (left < sizeof(struct objc_image_info64)) {
5030 memcpy(&o, r, left);
5031 outs() << " (objc_image_info entends past the end of the section)\n";
5033 memcpy(&o, r, sizeof(struct objc_image_info64));
5034 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5036 outs() << " version " << o.version << "\n";
5037 outs() << " flags " << format("0x%" PRIx32, o.flags);
5038 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5039 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5040 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5041 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5042 swift_version = (o.flags >> 8) & 0xff;
5043 if (swift_version != 0) {
5044 if (swift_version == 1)
5045 outs() << " Swift 1.0";
5046 else if (swift_version == 2)
5047 outs() << " Swift 1.1";
5049 outs() << " unknown future Swift version (" << swift_version << ")";
5054 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5055 uint32_t left, offset, swift_version, p;
5056 struct objc_image_info32 o;
5060 S.getName(SectName);
5061 DataRefImpl Ref = S.getRawDataRefImpl();
5062 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5063 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5065 r = get_pointer_32(p, offset, left, S, info);
5068 memset(&o, '\0', sizeof(struct objc_image_info32));
5069 if (left < sizeof(struct objc_image_info32)) {
5070 memcpy(&o, r, left);
5071 outs() << " (objc_image_info entends past the end of the section)\n";
5073 memcpy(&o, r, sizeof(struct objc_image_info32));
5074 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5076 outs() << " version " << o.version << "\n";
5077 outs() << " flags " << format("0x%" PRIx32, o.flags);
5078 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5079 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5080 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5081 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5082 swift_version = (o.flags >> 8) & 0xff;
5083 if (swift_version != 0) {
5084 if (swift_version == 1)
5085 outs() << " Swift 1.0";
5086 else if (swift_version == 2)
5087 outs() << " Swift 1.1";
5089 outs() << " unknown future Swift version (" << swift_version << ")";
5094 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5095 uint32_t left, offset, p;
5096 struct imageInfo_t o;
5100 S.getName(SectName);
5101 DataRefImpl Ref = S.getRawDataRefImpl();
5102 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5103 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5105 r = get_pointer_32(p, offset, left, S, info);
5108 memset(&o, '\0', sizeof(struct imageInfo_t));
5109 if (left < sizeof(struct imageInfo_t)) {
5110 memcpy(&o, r, left);
5111 outs() << " (imageInfo entends past the end of the section)\n";
5113 memcpy(&o, r, sizeof(struct imageInfo_t));
5114 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5116 outs() << " version " << o.version << "\n";
5117 outs() << " flags " << format("0x%" PRIx32, o.flags);
5123 outs() << " GC-only";
5129 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5130 SymbolAddressMap AddrMap;
5132 CreateSymbolAddressMap(O, &AddrMap);
5134 std::vector<SectionRef> Sections;
5135 for (const SectionRef &Section : O->sections()) {
5137 Section.getName(SectName);
5138 Sections.push_back(Section);
5141 struct DisassembleInfo info;
5142 // Set up the block of info used by the Symbolizer call backs.
5143 info.verbose = verbose;
5145 info.AddrMap = &AddrMap;
5146 info.Sections = &Sections;
5147 info.class_name = nullptr;
5148 info.selector_name = nullptr;
5149 info.method = nullptr;
5150 info.demangled_name = nullptr;
5151 info.bindtable = nullptr;
5156 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5157 if (CL == SectionRef())
5158 CL = get_section(O, "__DATA", "__objc_classlist");
5160 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5162 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5163 if (CR == SectionRef())
5164 CR = get_section(O, "__DATA", "__objc_classrefs");
5166 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5168 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5169 if (SR == SectionRef())
5170 SR = get_section(O, "__DATA", "__objc_superrefs");
5172 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5174 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5175 if (CA == SectionRef())
5176 CA = get_section(O, "__DATA", "__objc_catlist");
5178 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5180 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5181 if (PL == SectionRef())
5182 PL = get_section(O, "__DATA", "__objc_protolist");
5184 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5186 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5187 if (MR == SectionRef())
5188 MR = get_section(O, "__DATA", "__objc_msgrefs");
5190 print_message_refs64(MR, &info);
5192 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5193 if (II == SectionRef())
5194 II = get_section(O, "__DATA", "__objc_imageinfo");
5196 print_image_info64(II, &info);
5198 if (info.bindtable != nullptr)
5199 delete info.bindtable;
5202 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5203 SymbolAddressMap AddrMap;
5205 CreateSymbolAddressMap(O, &AddrMap);
5207 std::vector<SectionRef> Sections;
5208 for (const SectionRef &Section : O->sections()) {
5210 Section.getName(SectName);
5211 Sections.push_back(Section);
5214 struct DisassembleInfo info;
5215 // Set up the block of info used by the Symbolizer call backs.
5216 info.verbose = verbose;
5218 info.AddrMap = &AddrMap;
5219 info.Sections = &Sections;
5220 info.class_name = nullptr;
5221 info.selector_name = nullptr;
5222 info.method = nullptr;
5223 info.demangled_name = nullptr;
5224 info.bindtable = nullptr;
5228 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5229 if (CL != SectionRef()) {
5231 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5233 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5235 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5238 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5239 if (CR != SectionRef()) {
5241 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5243 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5245 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5248 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5249 if (SR != SectionRef()) {
5251 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5253 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5255 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5258 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5259 if (CA != SectionRef()) {
5261 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5263 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5265 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5268 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5269 if (PL != SectionRef()) {
5271 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5273 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5275 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5278 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5279 if (MR != SectionRef()) {
5281 print_message_refs32(MR, &info);
5283 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5285 print_message_refs32(MR, &info);
5288 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5289 if (II != SectionRef()) {
5291 print_image_info32(II, &info);
5293 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5295 print_image_info32(II, &info);
5299 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5300 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5301 const char *r, *name, *defs;
5302 struct objc_module_t module;
5304 struct objc_symtab_t symtab;
5305 struct objc_class_t objc_class;
5306 struct objc_category_t objc_category;
5308 outs() << "Objective-C segment\n";
5309 S = get_section(O, "__OBJC", "__module_info");
5310 if (S == SectionRef())
5313 SymbolAddressMap AddrMap;
5315 CreateSymbolAddressMap(O, &AddrMap);
5317 std::vector<SectionRef> Sections;
5318 for (const SectionRef &Section : O->sections()) {
5320 Section.getName(SectName);
5321 Sections.push_back(Section);
5324 struct DisassembleInfo info;
5325 // Set up the block of info used by the Symbolizer call backs.
5326 info.verbose = verbose;
5328 info.AddrMap = &AddrMap;
5329 info.Sections = &Sections;
5330 info.class_name = nullptr;
5331 info.selector_name = nullptr;
5332 info.method = nullptr;
5333 info.demangled_name = nullptr;
5334 info.bindtable = nullptr;
5338 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5339 p = S.getAddress() + i;
5340 r = get_pointer_32(p, offset, left, S, &info, true);
5343 memset(&module, '\0', sizeof(struct objc_module_t));
5344 if (left < sizeof(struct objc_module_t)) {
5345 memcpy(&module, r, left);
5346 outs() << " (module extends past end of __module_info section)\n";
5348 memcpy(&module, r, sizeof(struct objc_module_t));
5349 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5352 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5353 outs() << " version " << module.version << "\n";
5354 outs() << " size " << module.size << "\n";
5356 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5357 if (name != nullptr)
5358 outs() << format("%.*s", left, name);
5360 outs() << format("0x%08" PRIx32, module.name)
5361 << "(not in an __OBJC section)";
5364 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5365 if (module.symtab == 0 || r == nullptr) {
5366 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5367 << " (not in an __OBJC section)\n";
5370 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5371 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5374 if (left < sizeof(struct objc_symtab_t)) {
5375 memcpy(&symtab, r, left);
5376 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5378 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5379 if (left > sizeof(struct objc_symtab_t)) {
5380 defs_left = left - sizeof(struct objc_symtab_t);
5381 defs = r + sizeof(struct objc_symtab_t);
5384 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5387 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5388 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5389 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5391 outs() << " (not in an __OBJC section)";
5393 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5394 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5395 if (symtab.cls_def_cnt > 0)
5396 outs() << "\tClass Definitions\n";
5397 for (j = 0; j < symtab.cls_def_cnt; j++) {
5398 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5399 outs() << "\t(remaining class defs entries entends past the end of the "
5403 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5404 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5405 sys::swapByteOrder(def);
5407 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5408 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5410 if (left > sizeof(struct objc_class_t)) {
5412 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5414 outs() << " (entends past the end of the section)\n";
5415 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5416 memcpy(&objc_class, r, left);
5418 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5419 swapStruct(objc_class);
5420 print_objc_class_t(&objc_class, &info);
5422 outs() << "(not in an __OBJC section)\n";
5425 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5426 outs() << "\tMeta Class";
5427 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5429 if (left > sizeof(struct objc_class_t)) {
5431 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5433 outs() << " (entends past the end of the section)\n";
5434 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5435 memcpy(&objc_class, r, left);
5437 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5438 swapStruct(objc_class);
5439 print_objc_class_t(&objc_class, &info);
5441 outs() << "(not in an __OBJC section)\n";
5445 if (symtab.cat_def_cnt > 0)
5446 outs() << "\tCategory Definitions\n";
5447 for (j = 0; j < symtab.cat_def_cnt; j++) {
5448 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5449 outs() << "\t(remaining category defs entries entends past the end of "
5450 << "the section)\n";
5453 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5455 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5456 sys::swapByteOrder(def);
5458 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5459 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5460 << format("0x%08" PRIx32, def);
5462 if (left > sizeof(struct objc_category_t)) {
5464 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5466 outs() << " (entends past the end of the section)\n";
5467 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5468 memcpy(&objc_category, r, left);
5470 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5471 swapStruct(objc_category);
5472 print_objc_objc_category_t(&objc_category, &info);
5474 outs() << "(not in an __OBJC section)\n";
5478 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5479 if (II != SectionRef())
5480 print_image_info(II, &info);
5485 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5486 uint32_t size, uint32_t addr) {
5487 SymbolAddressMap AddrMap;
5488 CreateSymbolAddressMap(O, &AddrMap);
5490 std::vector<SectionRef> Sections;
5491 for (const SectionRef &Section : O->sections()) {
5493 Section.getName(SectName);
5494 Sections.push_back(Section);
5497 struct DisassembleInfo info;
5498 // Set up the block of info used by the Symbolizer call backs.
5499 info.verbose = true;
5501 info.AddrMap = &AddrMap;
5502 info.Sections = &Sections;
5503 info.class_name = nullptr;
5504 info.selector_name = nullptr;
5505 info.method = nullptr;
5506 info.demangled_name = nullptr;
5507 info.bindtable = nullptr;
5512 struct objc_protocol_t protocol;
5513 uint32_t left, paddr;
5514 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5515 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5516 left = size - (p - sect);
5517 if (left < sizeof(struct objc_protocol_t)) {
5518 outs() << "Protocol extends past end of __protocol section\n";
5519 memcpy(&protocol, p, left);
5521 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5522 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5523 swapStruct(protocol);
5524 paddr = addr + (p - sect);
5525 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5526 if (print_protocol(paddr, 0, &info))
5527 outs() << "(not in an __OBJC section)\n";
5531 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5533 printObjc2_64bit_MetaData(O, verbose);
5535 MachO::mach_header H;
5537 if (H.cputype == MachO::CPU_TYPE_ARM)
5538 printObjc2_32bit_MetaData(O, verbose);
5540 // This is the 32-bit non-arm cputype case. Which is normally
5541 // the first Objective-C ABI. But it may be the case of a
5542 // binary for the iOS simulator which is the second Objective-C
5543 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5544 // and return false.
5545 if (!printObjc1_32bit_MetaData(O, verbose))
5546 printObjc2_32bit_MetaData(O, verbose);
5551 // GuessLiteralPointer returns a string which for the item in the Mach-O file
5552 // for the address passed in as ReferenceValue for printing as a comment with
5553 // the instruction and also returns the corresponding type of that item
5554 // indirectly through ReferenceType.
5556 // If ReferenceValue is an address of literal cstring then a pointer to the
5557 // cstring is returned and ReferenceType is set to
5558 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5560 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5561 // Class ref that name is returned and the ReferenceType is set accordingly.
5563 // Lastly, literals which are Symbol address in a literal pool are looked for
5564 // and if found the symbol name is returned and ReferenceType is set to
5565 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5567 // If there is no item in the Mach-O file for the address passed in as
5568 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
5569 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5570 uint64_t ReferencePC,
5571 uint64_t *ReferenceType,
5572 struct DisassembleInfo *info) {
5573 // First see if there is an external relocation entry at the ReferencePC.
5574 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
5575 uint64_t sect_addr = info->S.getAddress();
5576 uint64_t sect_offset = ReferencePC - sect_addr;
5577 bool reloc_found = false;
5579 MachO::any_relocation_info RE;
5580 bool isExtern = false;
5582 for (const RelocationRef &Reloc : info->S.relocations()) {
5583 uint64_t RelocOffset = Reloc.getOffset();
5584 if (RelocOffset == sect_offset) {
5585 Rel = Reloc.getRawDataRefImpl();
5586 RE = info->O->getRelocation(Rel);
5587 if (info->O->isRelocationScattered(RE))
5589 isExtern = info->O->getPlainRelocationExternal(RE);
5591 symbol_iterator RelocSym = Reloc.getSymbol();
5598 // If there is an external relocation entry for a symbol in a section
5599 // then used that symbol's value for the value of the reference.
5600 if (reloc_found && isExtern) {
5601 if (info->O->getAnyRelocationPCRel(RE)) {
5602 unsigned Type = info->O->getAnyRelocationType(RE);
5603 if (Type == MachO::X86_64_RELOC_SIGNED) {
5604 ReferenceValue = Symbol.getValue();
5610 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5611 // Message refs and Class refs.
5612 bool classref, selref, msgref, cfstring;
5613 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5614 selref, msgref, cfstring);
5615 if (classref && pointer_value == 0) {
5616 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5617 // And the pointer_value in that section is typically zero as it will be
5618 // set by dyld as part of the "bind information".
5619 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5620 if (name != nullptr) {
5621 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5622 const char *class_name = strrchr(name, '$');
5623 if (class_name != nullptr && class_name[1] == '_' &&
5624 class_name[2] != '\0') {
5625 info->class_name = class_name + 2;
5632 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5634 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5635 if (name != nullptr)
5636 info->class_name = name;
5638 name = "bad class ref";
5643 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5644 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5648 if (selref && pointer_value == 0)
5649 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5651 if (pointer_value != 0)
5652 ReferenceValue = pointer_value;
5654 const char *name = GuessCstringPointer(ReferenceValue, info);
5656 if (pointer_value != 0 && selref) {
5657 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5658 info->selector_name = name;
5659 } else if (pointer_value != 0 && msgref) {
5660 info->class_name = nullptr;
5661 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5662 info->selector_name = name;
5664 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5668 // Lastly look for an indirect symbol with this ReferenceValue which is in
5669 // a literal pool. If found return that symbol name.
5670 name = GuessIndirectSymbol(ReferenceValue, info);
5672 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5679 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
5680 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
5681 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5682 // is created and returns the symbol name that matches the ReferenceValue or
5683 // nullptr if none. The ReferenceType is passed in for the IN type of
5684 // reference the instruction is making from the values in defined in the header
5685 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5686 // Out type and the ReferenceName will also be set which is added as a comment
5687 // to the disassembled instruction.
5690 // If the symbol name is a C++ mangled name then the demangled name is
5691 // returned through ReferenceName and ReferenceType is set to
5692 // LLVMDisassembler_ReferenceType_DeMangled_Name .
5695 // When this is called to get a symbol name for a branch target then the
5696 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5697 // SymbolValue will be looked for in the indirect symbol table to determine if
5698 // it is an address for a symbol stub. If so then the symbol name for that
5699 // stub is returned indirectly through ReferenceName and then ReferenceType is
5700 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5702 // When this is called with an value loaded via a PC relative load then
5703 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5704 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
5705 // or an Objective-C meta data reference. If so the output ReferenceType is
5706 // set to correspond to that as well as setting the ReferenceName.
5707 static const char *SymbolizerSymbolLookUp(void *DisInfo,
5708 uint64_t ReferenceValue,
5709 uint64_t *ReferenceType,
5710 uint64_t ReferencePC,
5711 const char **ReferenceName) {
5712 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
5713 // If no verbose symbolic information is wanted then just return nullptr.
5714 if (!info->verbose) {
5715 *ReferenceName = nullptr;
5716 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5720 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
5722 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5723 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
5724 if (*ReferenceName != nullptr) {
5725 method_reference(info, ReferenceType, ReferenceName);
5726 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5727 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5730 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5731 if (info->demangled_name != nullptr)
5732 free(info->demangled_name);
5734 info->demangled_name =
5735 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5736 if (info->demangled_name != nullptr) {
5737 *ReferenceName = info->demangled_name;
5738 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5740 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5743 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5744 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5746 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5748 method_reference(info, ReferenceType, ReferenceName);
5750 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5751 // If this is arm64 and the reference is an adrp instruction save the
5752 // instruction, passed in ReferenceValue and the address of the instruction
5753 // for use later if we see and add immediate instruction.
5754 } else if (info->O->getArch() == Triple::aarch64 &&
5755 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5756 info->adrp_inst = ReferenceValue;
5757 info->adrp_addr = ReferencePC;
5758 SymbolName = nullptr;
5759 *ReferenceName = nullptr;
5760 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5761 // If this is arm64 and reference is an add immediate instruction and we
5763 // seen an adrp instruction just before it and the adrp's Xd register
5765 // this add's Xn register reconstruct the value being referenced and look to
5766 // see if it is a literal pointer. Note the add immediate instruction is
5767 // passed in ReferenceValue.
5768 } else if (info->O->getArch() == Triple::aarch64 &&
5769 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5770 ReferencePC - 4 == info->adrp_addr &&
5771 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5772 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5773 uint32_t addxri_inst;
5774 uint64_t adrp_imm, addxri_imm;
5777 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5778 if (info->adrp_inst & 0x0200000)
5779 adrp_imm |= 0xfffffffffc000000LL;
5781 addxri_inst = ReferenceValue;
5782 addxri_imm = (addxri_inst >> 10) & 0xfff;
5783 if (((addxri_inst >> 22) & 0x3) == 1)
5786 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5787 (adrp_imm << 12) + addxri_imm;
5790 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5791 if (*ReferenceName == nullptr)
5792 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5793 // If this is arm64 and the reference is a load register instruction and we
5794 // have seen an adrp instruction just before it and the adrp's Xd register
5795 // matches this add's Xn register reconstruct the value being referenced and
5796 // look to see if it is a literal pointer. Note the load register
5797 // instruction is passed in ReferenceValue.
5798 } else if (info->O->getArch() == Triple::aarch64 &&
5799 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5800 ReferencePC - 4 == info->adrp_addr &&
5801 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5802 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5803 uint32_t ldrxui_inst;
5804 uint64_t adrp_imm, ldrxui_imm;
5807 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5808 if (info->adrp_inst & 0x0200000)
5809 adrp_imm |= 0xfffffffffc000000LL;
5811 ldrxui_inst = ReferenceValue;
5812 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5814 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5815 (adrp_imm << 12) + (ldrxui_imm << 3);
5818 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5819 if (*ReferenceName == nullptr)
5820 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5822 // If this arm64 and is an load register (PC-relative) instruction the
5823 // ReferenceValue is the PC plus the immediate value.
5824 else if (info->O->getArch() == Triple::aarch64 &&
5825 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5826 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5828 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5829 if (*ReferenceName == nullptr)
5830 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5833 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5834 if (info->demangled_name != nullptr)
5835 free(info->demangled_name);
5837 info->demangled_name =
5838 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5839 if (info->demangled_name != nullptr) {
5840 *ReferenceName = info->demangled_name;
5841 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5846 *ReferenceName = nullptr;
5847 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5853 /// \brief Emits the comments that are stored in the CommentStream.
5854 /// Each comment in the CommentStream must end with a newline.
5855 static void emitComments(raw_svector_ostream &CommentStream,
5856 SmallString<128> &CommentsToEmit,
5857 formatted_raw_ostream &FormattedOS,
5858 const MCAsmInfo &MAI) {
5859 // Flush the stream before taking its content.
5860 StringRef Comments = CommentsToEmit.str();
5861 // Get the default information for printing a comment.
5862 const char *CommentBegin = MAI.getCommentString();
5863 unsigned CommentColumn = MAI.getCommentColumn();
5864 bool IsFirst = true;
5865 while (!Comments.empty()) {
5867 FormattedOS << '\n';
5868 // Emit a line of comments.
5869 FormattedOS.PadToColumn(CommentColumn);
5870 size_t Position = Comments.find('\n');
5871 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5872 // Move after the newline character.
5873 Comments = Comments.substr(Position + 1);
5876 FormattedOS.flush();
5878 // Tell the comment stream that the vector changed underneath it.
5879 CommentsToEmit.clear();
5882 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5883 StringRef DisSegName, StringRef DisSectName) {
5884 const char *McpuDefault = nullptr;
5885 const Target *ThumbTarget = nullptr;
5886 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
5888 // GetTarget prints out stuff.
5891 if (MCPU.empty() && McpuDefault)
5894 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
5895 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
5897 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
5899 // Package up features to be passed to target/subtarget
5900 std::string FeaturesStr;
5901 if (MAttrs.size()) {
5902 SubtargetFeatures Features;
5903 for (unsigned i = 0; i != MAttrs.size(); ++i)
5904 Features.AddFeature(MAttrs[i]);
5905 FeaturesStr = Features.getString();
5908 // Set up disassembler.
5909 std::unique_ptr<const MCRegisterInfo> MRI(
5910 TheTarget->createMCRegInfo(TripleName));
5911 std::unique_ptr<const MCAsmInfo> AsmInfo(
5912 TheTarget->createMCAsmInfo(*MRI, TripleName));
5913 std::unique_ptr<const MCSubtargetInfo> STI(
5914 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
5915 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
5916 std::unique_ptr<MCDisassembler> DisAsm(
5917 TheTarget->createMCDisassembler(*STI, Ctx));
5918 std::unique_ptr<MCSymbolizer> Symbolizer;
5919 struct DisassembleInfo SymbolizerInfo;
5920 std::unique_ptr<MCRelocationInfo> RelInfo(
5921 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5923 Symbolizer.reset(TheTarget->createMCSymbolizer(
5924 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5925 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
5926 DisAsm->setSymbolizer(std::move(Symbolizer));
5928 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
5929 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
5930 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
5931 // Set the display preference for hex vs. decimal immediates.
5932 IP->setPrintImmHex(PrintImmHex);
5933 // Comment stream and backing vector.
5934 SmallString<128> CommentsToEmit;
5935 raw_svector_ostream CommentStream(CommentsToEmit);
5936 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5937 // if it is done then arm64 comments for string literals don't get printed
5938 // and some constant get printed instead and not setting it causes intel
5939 // (32-bit and 64-bit) comments printed with different spacing before the
5940 // comment causing different diffs with the 'C' disassembler library API.
5941 // IP->setCommentStream(CommentStream);
5943 if (!AsmInfo || !STI || !DisAsm || !IP) {
5944 errs() << "error: couldn't initialize disassembler for target "
5945 << TripleName << '\n';
5949 // Set up thumb disassembler.
5950 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5951 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5952 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
5953 std::unique_ptr<MCDisassembler> ThumbDisAsm;
5954 std::unique_ptr<MCInstPrinter> ThumbIP;
5955 std::unique_ptr<MCContext> ThumbCtx;
5956 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5957 struct DisassembleInfo ThumbSymbolizerInfo;
5958 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
5960 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
5962 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
5964 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
5965 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
5966 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
5967 MCContext *PtrThumbCtx = ThumbCtx.get();
5969 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
5971 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
5972 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5973 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
5974 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
5976 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
5977 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
5978 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
5979 *ThumbInstrInfo, *ThumbMRI));
5980 // Set the display preference for hex vs. decimal immediates.
5981 ThumbIP->setPrintImmHex(PrintImmHex);
5984 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
5985 errs() << "error: couldn't initialize disassembler for target "
5986 << ThumbTripleName << '\n';
5990 MachO::mach_header Header = MachOOF->getHeader();
5992 // FIXME: Using the -cfg command line option, this code used to be able to
5993 // annotate relocations with the referenced symbol's name, and if this was
5994 // inside a __[cf]string section, the data it points to. This is now replaced
5995 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
5996 std::vector<SectionRef> Sections;
5997 std::vector<SymbolRef> Symbols;
5998 SmallVector<uint64_t, 8> FoundFns;
5999 uint64_t BaseSegmentAddress;
6001 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
6002 BaseSegmentAddress);
6004 // Sort the symbols by address, just in case they didn't come in that way.
6005 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
6007 // Build a data in code table that is sorted on by the address of each entry.
6008 uint64_t BaseAddress = 0;
6009 if (Header.filetype == MachO::MH_OBJECT)
6010 BaseAddress = Sections[0].getAddress();
6012 BaseAddress = BaseSegmentAddress;
6014 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
6017 DI->getOffset(Offset);
6018 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6020 array_pod_sort(Dices.begin(), Dices.end());
6023 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6025 raw_ostream &DebugOut = nulls();
6028 std::unique_ptr<DIContext> diContext;
6029 ObjectFile *DbgObj = MachOOF;
6030 // Try to find debug info and set up the DIContext for it.
6032 // A separate DSym file path was specified, parse it as a macho file,
6033 // get the sections and supply it to the section name parsing machinery.
6034 if (!DSYMFile.empty()) {
6035 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
6036 MemoryBuffer::getFileOrSTDIN(DSYMFile);
6037 if (std::error_code EC = BufOrErr.getError()) {
6038 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
6042 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6047 // Setup the DIContext
6048 diContext.reset(new DWARFContextInMemory(*DbgObj));
6051 if (FilterSections.size() == 0)
6052 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
6054 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
6056 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6059 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
6061 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
6062 if (SegmentName != DisSegName)
6066 Sections[SectIdx].getContents(BytesStr);
6067 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6069 uint64_t SectAddress = Sections[SectIdx].getAddress();
6071 bool symbolTableWorked = false;
6073 // Create a map of symbol addresses to symbol names for use by
6074 // the SymbolizerSymbolLookUp() routine.
6075 SymbolAddressMap AddrMap;
6076 bool DisSymNameFound = false;
6077 for (const SymbolRef &Symbol : MachOOF->symbols()) {
6078 SymbolRef::Type ST = Symbol.getType();
6079 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6080 ST == SymbolRef::ST_Other) {
6081 uint64_t Address = Symbol.getValue();
6082 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6083 if (std::error_code EC = SymNameOrErr.getError())
6084 report_fatal_error(EC.message());
6085 StringRef SymName = *SymNameOrErr;
6086 AddrMap[Address] = SymName;
6087 if (!DisSymName.empty() && DisSymName == SymName)
6088 DisSymNameFound = true;
6091 if (!DisSymName.empty() && !DisSymNameFound) {
6092 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6095 // Set up the block of info used by the Symbolizer call backs.
6096 SymbolizerInfo.verbose = !NoSymbolicOperands;
6097 SymbolizerInfo.O = MachOOF;
6098 SymbolizerInfo.S = Sections[SectIdx];
6099 SymbolizerInfo.AddrMap = &AddrMap;
6100 SymbolizerInfo.Sections = &Sections;
6101 SymbolizerInfo.class_name = nullptr;
6102 SymbolizerInfo.selector_name = nullptr;
6103 SymbolizerInfo.method = nullptr;
6104 SymbolizerInfo.demangled_name = nullptr;
6105 SymbolizerInfo.bindtable = nullptr;
6106 SymbolizerInfo.adrp_addr = 0;
6107 SymbolizerInfo.adrp_inst = 0;
6108 // Same for the ThumbSymbolizer
6109 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
6110 ThumbSymbolizerInfo.O = MachOOF;
6111 ThumbSymbolizerInfo.S = Sections[SectIdx];
6112 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6113 ThumbSymbolizerInfo.Sections = &Sections;
6114 ThumbSymbolizerInfo.class_name = nullptr;
6115 ThumbSymbolizerInfo.selector_name = nullptr;
6116 ThumbSymbolizerInfo.method = nullptr;
6117 ThumbSymbolizerInfo.demangled_name = nullptr;
6118 ThumbSymbolizerInfo.bindtable = nullptr;
6119 ThumbSymbolizerInfo.adrp_addr = 0;
6120 ThumbSymbolizerInfo.adrp_inst = 0;
6122 // Disassemble symbol by symbol.
6123 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
6124 ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6125 if (std::error_code EC = SymNameOrErr.getError())
6126 report_fatal_error(EC.message());
6127 StringRef SymName = *SymNameOrErr;
6129 SymbolRef::Type ST = Symbols[SymIdx].getType();
6130 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
6133 // Make sure the symbol is defined in this section.
6134 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
6138 // If we are only disassembling one symbol see if this is that symbol.
6139 if (!DisSymName.empty() && DisSymName != SymName)
6142 // Start at the address of the symbol relative to the section's address.
6143 uint64_t Start = Symbols[SymIdx].getValue();
6144 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6145 Start -= SectionAddress;
6147 // Stop disassembling either at the beginning of the next symbol or at
6148 // the end of the section.
6149 bool containsNextSym = false;
6150 uint64_t NextSym = 0;
6151 uint64_t NextSymIdx = SymIdx + 1;
6152 while (Symbols.size() > NextSymIdx) {
6153 SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
6154 if (NextSymType == SymbolRef::ST_Function) {
6156 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
6157 NextSym = Symbols[NextSymIdx].getValue();
6158 NextSym -= SectionAddress;
6164 uint64_t SectSize = Sections[SectIdx].getSize();
6165 uint64_t End = containsNextSym ? NextSym : SectSize;
6168 symbolTableWorked = true;
6170 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6172 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6174 outs() << SymName << ":\n";
6175 DILineInfo lastLine;
6176 for (uint64_t Index = Start; Index < End; Index += Size) {
6179 uint64_t PC = SectAddress + Index;
6180 if (!NoLeadingAddr) {
6181 if (FullLeadingAddr) {
6182 if (MachOOF->is64Bit())
6183 outs() << format("%016" PRIx64, PC);
6185 outs() << format("%08" PRIx64, PC);
6187 outs() << format("%8" PRIx64 ":", PC);
6193 // Check the data in code table here to see if this is data not an
6194 // instruction to be disassembled.
6196 Dice.push_back(std::make_pair(PC, DiceRef()));
6197 dice_table_iterator DTI =
6198 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6199 compareDiceTableEntries);
6200 if (DTI != Dices.end()) {
6202 DTI->second.getLength(Length);
6204 DTI->second.getKind(Kind);
6205 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
6206 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6207 (PC == (DTI->first + Length - 1)) && (Length & 1))
6212 SmallVector<char, 64> AnnotationsBytes;
6213 raw_svector_ostream Annotations(AnnotationsBytes);
6217 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
6218 PC, DebugOut, Annotations);
6220 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
6221 DebugOut, Annotations);
6223 if (!NoShowRawInsn) {
6224 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
6226 formatted_raw_ostream FormattedOS(outs());
6227 StringRef AnnotationsStr = Annotations.str();
6229 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
6231 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
6232 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
6234 // Print debug info.
6236 DILineInfo dli = diContext->getLineInfoForAddress(PC);
6237 // Print valid line info if it changed.
6238 if (dli != lastLine && dli.Line != 0)
6239 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6245 unsigned int Arch = MachOOF->getArch();
6246 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6247 outs() << format("\t.byte 0x%02x #bad opcode\n",
6248 *(Bytes.data() + Index) & 0xff);
6249 Size = 1; // skip exactly one illegible byte and move on.
6250 } else if (Arch == Triple::aarch64) {
6251 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6252 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6253 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6254 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6255 outs() << format("\t.long\t0x%08x\n", opcode);
6258 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6260 Size = 1; // skip illegible bytes
6265 if (!symbolTableWorked) {
6266 // Reading the symbol table didn't work, disassemble the whole section.
6267 uint64_t SectAddress = Sections[SectIdx].getAddress();
6268 uint64_t SectSize = Sections[SectIdx].getSize();
6270 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
6273 uint64_t PC = SectAddress + Index;
6274 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6275 DebugOut, nulls())) {
6276 if (!NoLeadingAddr) {
6277 if (FullLeadingAddr) {
6278 if (MachOOF->is64Bit())
6279 outs() << format("%016" PRIx64, PC);
6281 outs() << format("%08" PRIx64, PC);
6283 outs() << format("%8" PRIx64 ":", PC);
6286 if (!NoShowRawInsn) {
6288 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
6290 IP->printInst(&Inst, outs(), "", *STI);
6293 unsigned int Arch = MachOOF->getArch();
6294 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6295 outs() << format("\t.byte 0x%02x #bad opcode\n",
6296 *(Bytes.data() + Index) & 0xff);
6297 InstSize = 1; // skip exactly one illegible byte and move on.
6299 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6301 InstSize = 1; // skip illegible bytes
6306 // The TripleName's need to be reset if we are called again for a different
6309 ThumbTripleName = "";
6311 if (SymbolizerInfo.method != nullptr)
6312 free(SymbolizerInfo.method);
6313 if (SymbolizerInfo.demangled_name != nullptr)
6314 free(SymbolizerInfo.demangled_name);
6315 if (SymbolizerInfo.bindtable != nullptr)
6316 delete SymbolizerInfo.bindtable;
6317 if (ThumbSymbolizerInfo.method != nullptr)
6318 free(ThumbSymbolizerInfo.method);
6319 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6320 free(ThumbSymbolizerInfo.demangled_name);
6321 if (ThumbSymbolizerInfo.bindtable != nullptr)
6322 delete ThumbSymbolizerInfo.bindtable;
6326 //===----------------------------------------------------------------------===//
6327 // __compact_unwind section dumping
6328 //===----------------------------------------------------------------------===//
6332 template <typename T> static uint64_t readNext(const char *&Buf) {
6333 using llvm::support::little;
6334 using llvm::support::unaligned;
6336 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6341 struct CompactUnwindEntry {
6342 uint32_t OffsetInSection;
6344 uint64_t FunctionAddr;
6346 uint32_t CompactEncoding;
6347 uint64_t PersonalityAddr;
6350 RelocationRef FunctionReloc;
6351 RelocationRef PersonalityReloc;
6352 RelocationRef LSDAReloc;
6354 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
6355 : OffsetInSection(Offset) {
6357 read<uint64_t>(Contents.data() + Offset);
6359 read<uint32_t>(Contents.data() + Offset);
6363 template <typename UIntPtr> void read(const char *Buf) {
6364 FunctionAddr = readNext<UIntPtr>(Buf);
6365 Length = readNext<uint32_t>(Buf);
6366 CompactEncoding = readNext<uint32_t>(Buf);
6367 PersonalityAddr = readNext<UIntPtr>(Buf);
6368 LSDAAddr = readNext<UIntPtr>(Buf);
6373 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
6374 /// and data being relocated, determine the best base Name and Addend to use for
6375 /// display purposes.
6377 /// 1. An Extern relocation will directly reference a symbol (and the data is
6378 /// then already an addend), so use that.
6379 /// 2. Otherwise the data is an offset in the object file's layout; try to find
6380 // a symbol before it in the same section, and use the offset from there.
6381 /// 3. Finally, if all that fails, fall back to an offset from the start of the
6382 /// referenced section.
6383 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6384 std::map<uint64_t, SymbolRef> &Symbols,
6385 const RelocationRef &Reloc, uint64_t Addr,
6386 StringRef &Name, uint64_t &Addend) {
6387 if (Reloc.getSymbol() != Obj->symbol_end()) {
6388 ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6389 if (std::error_code EC = NameOrErr.getError())
6390 report_fatal_error(EC.message());
6396 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
6397 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
6399 uint64_t SectionAddr = RelocSection.getAddress();
6401 auto Sym = Symbols.upper_bound(Addr);
6402 if (Sym == Symbols.begin()) {
6403 // The first symbol in the object is after this reference, the best we can
6404 // do is section-relative notation.
6405 RelocSection.getName(Name);
6406 Addend = Addr - SectionAddr;
6410 // Go back one so that SymbolAddress <= Addr.
6413 section_iterator SymSection = *Sym->second.getSection();
6414 if (RelocSection == *SymSection) {
6415 // There's a valid symbol in the same section before this reference.
6416 ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6417 if (std::error_code EC = NameOrErr.getError())
6418 report_fatal_error(EC.message());
6420 Addend = Addr - Sym->first;
6424 // There is a symbol before this reference, but it's in a different
6425 // section. Probably not helpful to mention it, so use the section name.
6426 RelocSection.getName(Name);
6427 Addend = Addr - SectionAddr;
6430 static void printUnwindRelocDest(const MachOObjectFile *Obj,
6431 std::map<uint64_t, SymbolRef> &Symbols,
6432 const RelocationRef &Reloc, uint64_t Addr) {
6436 if (!Reloc.getObject())
6439 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6443 outs() << " + " << format("0x%" PRIx64, Addend);
6447 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6448 std::map<uint64_t, SymbolRef> &Symbols,
6449 const SectionRef &CompactUnwind) {
6451 assert(Obj->isLittleEndian() &&
6452 "There should not be a big-endian .o with __compact_unwind");
6454 bool Is64 = Obj->is64Bit();
6455 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6456 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6459 CompactUnwind.getContents(Contents);
6461 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6463 // First populate the initial raw offsets, encodings and so on from the entry.
6464 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6465 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6466 CompactUnwinds.push_back(Entry);
6469 // Next we need to look at the relocations to find out what objects are
6470 // actually being referred to.
6471 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
6472 uint64_t RelocAddress = Reloc.getOffset();
6474 uint32_t EntryIdx = RelocAddress / EntrySize;
6475 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6476 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6478 if (OffsetInEntry == 0)
6479 Entry.FunctionReloc = Reloc;
6480 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6481 Entry.PersonalityReloc = Reloc;
6482 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6483 Entry.LSDAReloc = Reloc;
6485 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6488 // Finally, we're ready to print the data we've gathered.
6489 outs() << "Contents of __compact_unwind section:\n";
6490 for (auto &Entry : CompactUnwinds) {
6491 outs() << " Entry at offset "
6492 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
6494 // 1. Start of the region this entry applies to.
6495 outs() << " start: " << format("0x%" PRIx64,
6496 Entry.FunctionAddr) << ' ';
6497 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
6500 // 2. Length of the region this entry applies to.
6501 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6503 // 3. The 32-bit compact encoding.
6504 outs() << " compact encoding: "
6505 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
6507 // 4. The personality function, if present.
6508 if (Entry.PersonalityReloc.getObject()) {
6509 outs() << " personality function: "
6510 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
6511 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6512 Entry.PersonalityAddr);
6516 // 5. This entry's language-specific data area.
6517 if (Entry.LSDAReloc.getObject()) {
6518 outs() << " LSDA: " << format("0x%" PRIx64,
6519 Entry.LSDAAddr) << ' ';
6520 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6526 //===----------------------------------------------------------------------===//
6527 // __unwind_info section dumping
6528 //===----------------------------------------------------------------------===//
6530 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6531 const char *Pos = PageStart;
6532 uint32_t Kind = readNext<uint32_t>(Pos);
6534 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6536 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6537 uint16_t NumEntries = readNext<uint16_t>(Pos);
6539 Pos = PageStart + EntriesStart;
6540 for (unsigned i = 0; i < NumEntries; ++i) {
6541 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6542 uint32_t Encoding = readNext<uint32_t>(Pos);
6544 outs() << " [" << i << "]: "
6545 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6547 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
6551 static void printCompressedSecondLevelUnwindPage(
6552 const char *PageStart, uint32_t FunctionBase,
6553 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6554 const char *Pos = PageStart;
6555 uint32_t Kind = readNext<uint32_t>(Pos);
6557 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6559 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6560 uint16_t NumEntries = readNext<uint16_t>(Pos);
6562 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6563 readNext<uint16_t>(Pos);
6564 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6565 PageStart + EncodingsStart);
6567 Pos = PageStart + EntriesStart;
6568 for (unsigned i = 0; i < NumEntries; ++i) {
6569 uint32_t Entry = readNext<uint32_t>(Pos);
6570 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6571 uint32_t EncodingIdx = Entry >> 24;
6574 if (EncodingIdx < CommonEncodings.size())
6575 Encoding = CommonEncodings[EncodingIdx];
6577 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6579 outs() << " [" << i << "]: "
6580 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6582 << "encoding[" << EncodingIdx
6583 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
6587 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6588 std::map<uint64_t, SymbolRef> &Symbols,
6589 const SectionRef &UnwindInfo) {
6591 assert(Obj->isLittleEndian() &&
6592 "There should not be a big-endian .o with __unwind_info");
6594 outs() << "Contents of __unwind_info section:\n";
6597 UnwindInfo.getContents(Contents);
6598 const char *Pos = Contents.data();
6600 //===----------------------------------
6602 //===----------------------------------
6604 uint32_t Version = readNext<uint32_t>(Pos);
6605 outs() << " Version: "
6606 << format("0x%" PRIx32, Version) << '\n';
6607 assert(Version == 1 && "only understand version 1");
6609 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6610 outs() << " Common encodings array section offset: "
6611 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6612 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6613 outs() << " Number of common encodings in array: "
6614 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6616 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6617 outs() << " Personality function array section offset: "
6618 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6619 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6620 outs() << " Number of personality functions in array: "
6621 << format("0x%" PRIx32, NumPersonalities) << '\n';
6623 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6624 outs() << " Index array section offset: "
6625 << format("0x%" PRIx32, IndicesStart) << '\n';
6626 uint32_t NumIndices = readNext<uint32_t>(Pos);
6627 outs() << " Number of indices in array: "
6628 << format("0x%" PRIx32, NumIndices) << '\n';
6630 //===----------------------------------
6631 // A shared list of common encodings
6632 //===----------------------------------
6634 // These occupy indices in the range [0, N] whenever an encoding is referenced
6635 // from a compressed 2nd level index table. In practice the linker only
6636 // creates ~128 of these, so that indices are available to embed encodings in
6637 // the 2nd level index.
6639 SmallVector<uint32_t, 64> CommonEncodings;
6640 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6641 Pos = Contents.data() + CommonEncodingsStart;
6642 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6643 uint32_t Encoding = readNext<uint32_t>(Pos);
6644 CommonEncodings.push_back(Encoding);
6646 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6650 //===----------------------------------
6651 // Personality functions used in this executable
6652 //===----------------------------------
6654 // There should be only a handful of these (one per source language,
6655 // roughly). Particularly since they only get 2 bits in the compact encoding.
6657 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6658 Pos = Contents.data() + PersonalitiesStart;
6659 for (unsigned i = 0; i < NumPersonalities; ++i) {
6660 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6661 outs() << " personality[" << i + 1
6662 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6665 //===----------------------------------
6666 // The level 1 index entries
6667 //===----------------------------------
6669 // These specify an approximate place to start searching for the more detailed
6670 // information, sorted by PC.
6673 uint32_t FunctionOffset;
6674 uint32_t SecondLevelPageStart;
6678 SmallVector<IndexEntry, 4> IndexEntries;
6680 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6681 Pos = Contents.data() + IndicesStart;
6682 for (unsigned i = 0; i < NumIndices; ++i) {
6685 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6686 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6687 Entry.LSDAStart = readNext<uint32_t>(Pos);
6688 IndexEntries.push_back(Entry);
6690 outs() << " [" << i << "]: "
6691 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6693 << "2nd level page offset="
6694 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
6695 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
6698 //===----------------------------------
6699 // Next come the LSDA tables
6700 //===----------------------------------
6702 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6703 // the first top-level index's LSDAOffset to the last (sentinel).
6705 outs() << " LSDA descriptors:\n";
6706 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6707 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6708 (2 * sizeof(uint32_t));
6709 for (int i = 0; i < NumLSDAs; ++i) {
6710 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6711 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6712 outs() << " [" << i << "]: "
6713 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6715 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
6718 //===----------------------------------
6719 // Finally, the 2nd level indices
6720 //===----------------------------------
6722 // Generally these are 4K in size, and have 2 possible forms:
6723 // + Regular stores up to 511 entries with disparate encodings
6724 // + Compressed stores up to 1021 entries if few enough compact encoding
6726 outs() << " Second level indices:\n";
6727 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6728 // The final sentinel top-level index has no associated 2nd level page
6729 if (IndexEntries[i].SecondLevelPageStart == 0)
6732 outs() << " Second level index[" << i << "]: "
6733 << "offset in section="
6734 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6736 << "base function offset="
6737 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6739 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
6740 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
6742 printRegularSecondLevelUnwindPage(Pos);
6744 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6747 llvm_unreachable("Do not know how to print this kind of 2nd level page");
6751 static unsigned getSizeForEncoding(bool is64Bit,
6752 unsigned symbolEncoding) {
6753 unsigned format = symbolEncoding & 0x0f;
6755 default: llvm_unreachable("Unknown Encoding");
6756 case dwarf::DW_EH_PE_absptr:
6757 case dwarf::DW_EH_PE_signed:
6758 return is64Bit ? 8 : 4;
6759 case dwarf::DW_EH_PE_udata2:
6760 case dwarf::DW_EH_PE_sdata2:
6762 case dwarf::DW_EH_PE_udata4:
6763 case dwarf::DW_EH_PE_sdata4:
6765 case dwarf::DW_EH_PE_udata8:
6766 case dwarf::DW_EH_PE_sdata8:
6771 static uint64_t readPointer(const char *&Pos, bool is64Bit, unsigned Encoding) {
6772 switch (getSizeForEncoding(is64Bit, Encoding)) {
6774 return readNext<uint16_t>(Pos);
6777 return readNext<uint32_t>(Pos);
6780 return readNext<uint64_t>(Pos);
6783 llvm_unreachable("Illegal data size");
6787 static void printMachOEHFrameSection(const MachOObjectFile *Obj,
6788 std::map<uint64_t, SymbolRef> &Symbols,
6789 const SectionRef &EHFrame) {
6790 if (!Obj->isLittleEndian()) {
6791 outs() << "warning: cannot handle big endian __eh_frame section\n";
6795 bool is64Bit = Obj->is64Bit();
6797 outs() << "Contents of __eh_frame section:\n";
6800 EHFrame.getContents(Contents);
6802 /// A few fields of the CIE are used when decoding the FDE's. This struct
6803 /// will cache those fields we need so that we don't have to decode it
6804 /// repeatedly for each FDE that references it.
6806 Optional<uint32_t> FDEPointerEncoding;
6807 Optional<uint32_t> LSDAPointerEncoding;
6808 bool hasAugmentationLength;
6811 // Map from the start offset of the CIE to the cached data for that CIE.
6812 DenseMap<uint64_t, DecodedCIE> CachedCIEs;
6814 for (const char *Pos = Contents.data(), *End = Contents.end(); Pos != End; ) {
6816 const char *EntryStartPos = Pos;
6818 uint64_t Length = readNext<uint32_t>(Pos);
6819 if (Length == 0xffffffff)
6820 Length = readNext<uint64_t>(Pos);
6822 // Save the Pos so that we can check the length we encoded against what we
6824 const char *PosAfterLength = Pos;
6825 const char *EntryEndPos = PosAfterLength + Length;
6827 assert(EntryEndPos <= End &&
6828 "__eh_frame entry length exceeds section size");
6830 uint32_t ID = readNext<uint32_t>(Pos);
6834 uint32_t Version = readNext<uint8_t>(Pos);
6836 // Parse a null terminated augmentation string
6837 SmallString<8> AugmentationString;
6838 for (uint8_t Char = readNext<uint8_t>(Pos); Char;
6839 Char = readNext<uint8_t>(Pos))
6840 AugmentationString.push_back(Char);
6842 // Optionally parse the EH data if the augmentation string says it's there.
6843 Optional<uint64_t> EHData;
6844 if (StringRef(AugmentationString).count("eh"))
6845 EHData = is64Bit ? readNext<uint64_t>(Pos) : readNext<uint32_t>(Pos);
6847 unsigned ULEBByteCount;
6848 uint64_t CodeAlignmentFactor = decodeULEB128((const uint8_t *)Pos,
6850 Pos += ULEBByteCount;
6852 int64_t DataAlignmentFactor = decodeSLEB128((const uint8_t *)Pos,
6854 Pos += ULEBByteCount;
6856 uint32_t ReturnAddressRegister = readNext<uint8_t>(Pos);
6858 Optional<uint64_t> AugmentationLength;
6859 Optional<uint32_t> LSDAPointerEncoding;
6860 Optional<uint32_t> PersonalityEncoding;
6861 Optional<uint64_t> Personality;
6862 Optional<uint32_t> FDEPointerEncoding;
6863 if (!AugmentationString.empty() && AugmentationString.front() == 'z') {
6864 AugmentationLength = decodeULEB128((const uint8_t *)Pos,
6866 Pos += ULEBByteCount;
6868 // Walk the augmentation string to get all the augmentation data.
6869 for (unsigned i = 1, e = AugmentationString.size(); i != e; ++i) {
6870 char Char = AugmentationString[i];
6873 assert((i + 1) != e && AugmentationString[i + 1] == 'h' &&
6874 "Expected 'eh' in augmentation string");
6877 assert(!LSDAPointerEncoding && "Duplicate LSDA encoding");
6878 LSDAPointerEncoding = readNext<uint8_t>(Pos);
6881 assert(!Personality && "Duplicate personality");
6882 PersonalityEncoding = readNext<uint8_t>(Pos);
6883 Personality = readPointer(Pos, is64Bit, *PersonalityEncoding);
6887 assert(!FDEPointerEncoding && "Duplicate FDE encoding");
6888 FDEPointerEncoding = readNext<uint8_t>(Pos);
6891 llvm_unreachable("'z' must be first in the augmentation string");
6897 outs() << " Length: " << Length << "\n";
6898 outs() << " CIE ID: " << ID << "\n";
6899 outs() << " Version: " << Version << "\n";
6900 outs() << " Augmentation String: " << AugmentationString << "\n";
6902 outs() << " EHData: " << *EHData << "\n";
6903 outs() << " Code Alignment Factor: " << CodeAlignmentFactor << "\n";
6904 outs() << " Data Alignment Factor: " << DataAlignmentFactor << "\n";
6905 outs() << " Return Address Register: " << ReturnAddressRegister << "\n";
6906 if (AugmentationLength) {
6907 outs() << " Augmentation Data Length: " << *AugmentationLength << "\n";
6908 if (LSDAPointerEncoding) {
6909 outs() << " FDE LSDA Pointer Encoding: "
6910 << *LSDAPointerEncoding << "\n";
6913 outs() << " Personality Encoding: " << *PersonalityEncoding << "\n";
6914 outs() << " Personality: " << *Personality << "\n";
6916 if (FDEPointerEncoding) {
6917 outs() << " FDE Address Pointer Encoding: "
6918 << *FDEPointerEncoding << "\n";
6921 // FIXME: Handle instructions.
6922 // For now just emit some bytes
6923 outs() << " Instructions:\n ";
6924 dumpBytes(makeArrayRef((const uint8_t*)Pos, (const uint8_t*)EntryEndPos),
6929 // Cache this entry.
6930 uint64_t Offset = EntryStartPos - Contents.data();
6931 CachedCIEs[Offset] = { FDEPointerEncoding, LSDAPointerEncoding,
6932 AugmentationLength.hasValue() };
6937 // The CIE pointer for an FDE is the same location as the ID which we
6939 uint32_t CIEPointer = ID;
6941 const char *CIEStart = PosAfterLength - CIEPointer;
6942 assert(CIEStart >= Contents.data() &&
6943 "FDE points to CIE before the __eh_frame start");
6945 uint64_t CIEOffset = CIEStart - Contents.data();
6946 auto CIEIt = CachedCIEs.find(CIEOffset);
6947 if (CIEIt == CachedCIEs.end())
6948 llvm_unreachable("Couldn't find CIE at offset in to __eh_frame section");
6950 const DecodedCIE &CIE = CIEIt->getSecond();
6951 assert(CIE.FDEPointerEncoding &&
6952 "FDE references CIE which did not set pointer encoding");
6954 uint64_t PCPointerSize = getSizeForEncoding(is64Bit,
6955 *CIE.FDEPointerEncoding);
6957 uint64_t PCBegin = readPointer(Pos, is64Bit, *CIE.FDEPointerEncoding);
6958 uint64_t PCRange = readPointer(Pos, is64Bit, *CIE.FDEPointerEncoding);
6960 Optional<uint64_t> AugmentationLength;
6961 uint32_t LSDAPointerSize;
6962 Optional<uint64_t> LSDAPointer;
6963 if (CIE.hasAugmentationLength) {
6964 unsigned ULEBByteCount;
6965 AugmentationLength = decodeULEB128((const uint8_t *)Pos,
6967 Pos += ULEBByteCount;
6969 // Decode the LSDA if the CIE augmentation string said we should.
6970 if (CIE.LSDAPointerEncoding) {
6971 LSDAPointerSize = getSizeForEncoding(is64Bit, *CIE.LSDAPointerEncoding);
6972 LSDAPointer = readPointer(Pos, is64Bit, *CIE.LSDAPointerEncoding);
6977 outs() << " Length: " << Length << "\n";
6978 outs() << " CIE Offset: " << CIEOffset << "\n";
6980 if (PCPointerSize == 8) {
6981 outs() << format(" PC Begin: %016" PRIx64, PCBegin) << "\n";
6982 outs() << format(" PC Range: %016" PRIx64, PCRange) << "\n";
6984 outs() << format(" PC Begin: %08" PRIx64, PCBegin) << "\n";
6985 outs() << format(" PC Range: %08" PRIx64, PCRange) << "\n";
6987 if (AugmentationLength) {
6988 outs() << " Augmentation Data Length: " << *AugmentationLength << "\n";
6990 if (LSDAPointerSize == 8)
6991 outs() << format(" LSDA Pointer: %016\n" PRIx64, *LSDAPointer);
6993 outs() << format(" LSDA Pointer: %08\n" PRIx64, *LSDAPointer);
6997 // FIXME: Handle instructions.
6998 // For now just emit some bytes
6999 outs() << " Instructions:\n ";
7000 dumpBytes(makeArrayRef((const uint8_t*)Pos, (const uint8_t*)EntryEndPos),
7007 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7008 std::map<uint64_t, SymbolRef> Symbols;
7009 for (const SymbolRef &SymRef : Obj->symbols()) {
7010 // Discard any undefined or absolute symbols. They're not going to take part
7011 // in the convenience lookup for unwind info and just take up resources.
7012 section_iterator Section = *SymRef.getSection();
7013 if (Section == Obj->section_end())
7016 uint64_t Addr = SymRef.getValue();
7017 Symbols.insert(std::make_pair(Addr, SymRef));
7020 for (const SectionRef &Section : Obj->sections()) {
7022 Section.getName(SectName);
7023 if (SectName == "__compact_unwind")
7024 printMachOCompactUnwindSection(Obj, Symbols, Section);
7025 else if (SectName == "__unwind_info")
7026 printMachOUnwindInfoSection(Obj, Symbols, Section);
7027 else if (SectName == "__eh_frame")
7028 printMachOEHFrameSection(Obj, Symbols, Section);
7032 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7033 uint32_t cpusubtype, uint32_t filetype,
7034 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7036 outs() << "Mach header\n";
7037 outs() << " magic cputype cpusubtype caps filetype ncmds "
7038 "sizeofcmds flags\n";
7040 if (magic == MachO::MH_MAGIC)
7041 outs() << " MH_MAGIC";
7042 else if (magic == MachO::MH_MAGIC_64)
7043 outs() << "MH_MAGIC_64";
7045 outs() << format(" 0x%08" PRIx32, magic);
7047 case MachO::CPU_TYPE_I386:
7049 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7050 case MachO::CPU_SUBTYPE_I386_ALL:
7054 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7058 case MachO::CPU_TYPE_X86_64:
7059 outs() << " X86_64";
7060 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7061 case MachO::CPU_SUBTYPE_X86_64_ALL:
7064 case MachO::CPU_SUBTYPE_X86_64_H:
7065 outs() << " Haswell";
7068 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7072 case MachO::CPU_TYPE_ARM:
7074 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7075 case MachO::CPU_SUBTYPE_ARM_ALL:
7078 case MachO::CPU_SUBTYPE_ARM_V4T:
7081 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7084 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7085 outs() << " XSCALE";
7087 case MachO::CPU_SUBTYPE_ARM_V6:
7090 case MachO::CPU_SUBTYPE_ARM_V6M:
7093 case MachO::CPU_SUBTYPE_ARM_V7:
7096 case MachO::CPU_SUBTYPE_ARM_V7EM:
7099 case MachO::CPU_SUBTYPE_ARM_V7K:
7102 case MachO::CPU_SUBTYPE_ARM_V7M:
7105 case MachO::CPU_SUBTYPE_ARM_V7S:
7109 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7113 case MachO::CPU_TYPE_ARM64:
7115 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7116 case MachO::CPU_SUBTYPE_ARM64_ALL:
7120 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7124 case MachO::CPU_TYPE_POWERPC:
7126 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7127 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7131 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7135 case MachO::CPU_TYPE_POWERPC64:
7137 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7138 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7142 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7147 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
7150 outs() << format(" 0x%02" PRIx32,
7151 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7154 case MachO::MH_OBJECT:
7155 outs() << " OBJECT";
7157 case MachO::MH_EXECUTE:
7158 outs() << " EXECUTE";
7160 case MachO::MH_FVMLIB:
7161 outs() << " FVMLIB";
7163 case MachO::MH_CORE:
7166 case MachO::MH_PRELOAD:
7167 outs() << " PRELOAD";
7169 case MachO::MH_DYLIB:
7172 case MachO::MH_DYLIB_STUB:
7173 outs() << " DYLIB_STUB";
7175 case MachO::MH_DYLINKER:
7176 outs() << " DYLINKER";
7178 case MachO::MH_BUNDLE:
7179 outs() << " BUNDLE";
7181 case MachO::MH_DSYM:
7184 case MachO::MH_KEXT_BUNDLE:
7185 outs() << " KEXTBUNDLE";
7188 outs() << format(" %10u", filetype);
7191 outs() << format(" %5u", ncmds);
7192 outs() << format(" %10u", sizeofcmds);
7194 if (f & MachO::MH_NOUNDEFS) {
7195 outs() << " NOUNDEFS";
7196 f &= ~MachO::MH_NOUNDEFS;
7198 if (f & MachO::MH_INCRLINK) {
7199 outs() << " INCRLINK";
7200 f &= ~MachO::MH_INCRLINK;
7202 if (f & MachO::MH_DYLDLINK) {
7203 outs() << " DYLDLINK";
7204 f &= ~MachO::MH_DYLDLINK;
7206 if (f & MachO::MH_BINDATLOAD) {
7207 outs() << " BINDATLOAD";
7208 f &= ~MachO::MH_BINDATLOAD;
7210 if (f & MachO::MH_PREBOUND) {
7211 outs() << " PREBOUND";
7212 f &= ~MachO::MH_PREBOUND;
7214 if (f & MachO::MH_SPLIT_SEGS) {
7215 outs() << " SPLIT_SEGS";
7216 f &= ~MachO::MH_SPLIT_SEGS;
7218 if (f & MachO::MH_LAZY_INIT) {
7219 outs() << " LAZY_INIT";
7220 f &= ~MachO::MH_LAZY_INIT;
7222 if (f & MachO::MH_TWOLEVEL) {
7223 outs() << " TWOLEVEL";
7224 f &= ~MachO::MH_TWOLEVEL;
7226 if (f & MachO::MH_FORCE_FLAT) {
7227 outs() << " FORCE_FLAT";
7228 f &= ~MachO::MH_FORCE_FLAT;
7230 if (f & MachO::MH_NOMULTIDEFS) {
7231 outs() << " NOMULTIDEFS";
7232 f &= ~MachO::MH_NOMULTIDEFS;
7234 if (f & MachO::MH_NOFIXPREBINDING) {
7235 outs() << " NOFIXPREBINDING";
7236 f &= ~MachO::MH_NOFIXPREBINDING;
7238 if (f & MachO::MH_PREBINDABLE) {
7239 outs() << " PREBINDABLE";
7240 f &= ~MachO::MH_PREBINDABLE;
7242 if (f & MachO::MH_ALLMODSBOUND) {
7243 outs() << " ALLMODSBOUND";
7244 f &= ~MachO::MH_ALLMODSBOUND;
7246 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7247 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7248 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7250 if (f & MachO::MH_CANONICAL) {
7251 outs() << " CANONICAL";
7252 f &= ~MachO::MH_CANONICAL;
7254 if (f & MachO::MH_WEAK_DEFINES) {
7255 outs() << " WEAK_DEFINES";
7256 f &= ~MachO::MH_WEAK_DEFINES;
7258 if (f & MachO::MH_BINDS_TO_WEAK) {
7259 outs() << " BINDS_TO_WEAK";
7260 f &= ~MachO::MH_BINDS_TO_WEAK;
7262 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7263 outs() << " ALLOW_STACK_EXECUTION";
7264 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7266 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7267 outs() << " DEAD_STRIPPABLE_DYLIB";
7268 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7270 if (f & MachO::MH_PIE) {
7272 f &= ~MachO::MH_PIE;
7274 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7275 outs() << " NO_REEXPORTED_DYLIBS";
7276 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7278 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7279 outs() << " MH_HAS_TLV_DESCRIPTORS";
7280 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7282 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7283 outs() << " MH_NO_HEAP_EXECUTION";
7284 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7286 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7287 outs() << " APP_EXTENSION_SAFE";
7288 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7290 if (f != 0 || flags == 0)
7291 outs() << format(" 0x%08" PRIx32, f);
7293 outs() << format(" 0x%08" PRIx32, magic);
7294 outs() << format(" %7d", cputype);
7295 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7296 outs() << format(" 0x%02" PRIx32,
7297 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7298 outs() << format(" %10u", filetype);
7299 outs() << format(" %5u", ncmds);
7300 outs() << format(" %10u", sizeofcmds);
7301 outs() << format(" 0x%08" PRIx32, flags);
7306 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7307 StringRef SegName, uint64_t vmaddr,
7308 uint64_t vmsize, uint64_t fileoff,
7309 uint64_t filesize, uint32_t maxprot,
7310 uint32_t initprot, uint32_t nsects,
7311 uint32_t flags, uint32_t object_size,
7313 uint64_t expected_cmdsize;
7314 if (cmd == MachO::LC_SEGMENT) {
7315 outs() << " cmd LC_SEGMENT\n";
7316 expected_cmdsize = nsects;
7317 expected_cmdsize *= sizeof(struct MachO::section);
7318 expected_cmdsize += sizeof(struct MachO::segment_command);
7320 outs() << " cmd LC_SEGMENT_64\n";
7321 expected_cmdsize = nsects;
7322 expected_cmdsize *= sizeof(struct MachO::section_64);
7323 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7325 outs() << " cmdsize " << cmdsize;
7326 if (cmdsize != expected_cmdsize)
7327 outs() << " Inconsistent size\n";
7330 outs() << " segname " << SegName << "\n";
7331 if (cmd == MachO::LC_SEGMENT_64) {
7332 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7333 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7335 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7336 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
7338 outs() << " fileoff " << fileoff;
7339 if (fileoff > object_size)
7340 outs() << " (past end of file)\n";
7343 outs() << " filesize " << filesize;
7344 if (fileoff + filesize > object_size)
7345 outs() << " (past end of file)\n";
7350 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7351 MachO::VM_PROT_EXECUTE)) != 0)
7352 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7354 outs() << " maxprot ";
7355 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7356 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7357 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7360 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7361 MachO::VM_PROT_EXECUTE)) != 0)
7362 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7364 outs() << " initprot ";
7365 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7366 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7367 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7370 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7371 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7373 outs() << " nsects " << nsects << "\n";
7377 outs() << " (none)\n";
7379 if (flags & MachO::SG_HIGHVM) {
7380 outs() << " HIGHVM";
7381 flags &= ~MachO::SG_HIGHVM;
7383 if (flags & MachO::SG_FVMLIB) {
7384 outs() << " FVMLIB";
7385 flags &= ~MachO::SG_FVMLIB;
7387 if (flags & MachO::SG_NORELOC) {
7388 outs() << " NORELOC";
7389 flags &= ~MachO::SG_NORELOC;
7391 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7392 outs() << " PROTECTED_VERSION_1";
7393 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7396 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7401 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7405 static void PrintSection(const char *sectname, const char *segname,
7406 uint64_t addr, uint64_t size, uint32_t offset,
7407 uint32_t align, uint32_t reloff, uint32_t nreloc,
7408 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7409 uint32_t cmd, const char *sg_segname,
7410 uint32_t filetype, uint32_t object_size,
7412 outs() << "Section\n";
7413 outs() << " sectname " << format("%.16s\n", sectname);
7414 outs() << " segname " << format("%.16s", segname);
7415 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7416 outs() << " (does not match segment)\n";
7419 if (cmd == MachO::LC_SEGMENT_64) {
7420 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7421 outs() << " size " << format("0x%016" PRIx64, size);
7423 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7424 outs() << " size " << format("0x%08" PRIx64, size);
7426 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7427 outs() << " (past end of file)\n";
7430 outs() << " offset " << offset;
7431 if (offset > object_size)
7432 outs() << " (past end of file)\n";
7435 uint32_t align_shifted = 1 << align;
7436 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7437 outs() << " reloff " << reloff;
7438 if (reloff > object_size)
7439 outs() << " (past end of file)\n";
7442 outs() << " nreloc " << nreloc;
7443 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7444 outs() << " (past end of file)\n";
7447 uint32_t section_type = flags & MachO::SECTION_TYPE;
7450 if (section_type == MachO::S_REGULAR)
7451 outs() << " S_REGULAR\n";
7452 else if (section_type == MachO::S_ZEROFILL)
7453 outs() << " S_ZEROFILL\n";
7454 else if (section_type == MachO::S_CSTRING_LITERALS)
7455 outs() << " S_CSTRING_LITERALS\n";
7456 else if (section_type == MachO::S_4BYTE_LITERALS)
7457 outs() << " S_4BYTE_LITERALS\n";
7458 else if (section_type == MachO::S_8BYTE_LITERALS)
7459 outs() << " S_8BYTE_LITERALS\n";
7460 else if (section_type == MachO::S_16BYTE_LITERALS)
7461 outs() << " S_16BYTE_LITERALS\n";
7462 else if (section_type == MachO::S_LITERAL_POINTERS)
7463 outs() << " S_LITERAL_POINTERS\n";
7464 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7465 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7466 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7467 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7468 else if (section_type == MachO::S_SYMBOL_STUBS)
7469 outs() << " S_SYMBOL_STUBS\n";
7470 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7471 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7472 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7473 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7474 else if (section_type == MachO::S_COALESCED)
7475 outs() << " S_COALESCED\n";
7476 else if (section_type == MachO::S_INTERPOSING)
7477 outs() << " S_INTERPOSING\n";
7478 else if (section_type == MachO::S_DTRACE_DOF)
7479 outs() << " S_DTRACE_DOF\n";
7480 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7481 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7482 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7483 outs() << " S_THREAD_LOCAL_REGULAR\n";
7484 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7485 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7486 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7487 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7488 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7489 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7490 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7491 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7493 outs() << format("0x%08" PRIx32, section_type) << "\n";
7494 outs() << "attributes";
7495 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7496 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7497 outs() << " PURE_INSTRUCTIONS";
7498 if (section_attributes & MachO::S_ATTR_NO_TOC)
7499 outs() << " NO_TOC";
7500 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7501 outs() << " STRIP_STATIC_SYMS";
7502 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7503 outs() << " NO_DEAD_STRIP";
7504 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7505 outs() << " LIVE_SUPPORT";
7506 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7507 outs() << " SELF_MODIFYING_CODE";
7508 if (section_attributes & MachO::S_ATTR_DEBUG)
7510 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7511 outs() << " SOME_INSTRUCTIONS";
7512 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7513 outs() << " EXT_RELOC";
7514 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7515 outs() << " LOC_RELOC";
7516 if (section_attributes == 0)
7517 outs() << " (none)";
7520 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7521 outs() << " reserved1 " << reserved1;
7522 if (section_type == MachO::S_SYMBOL_STUBS ||
7523 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7524 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7525 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7526 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7527 outs() << " (index into indirect symbol table)\n";
7530 outs() << " reserved2 " << reserved2;
7531 if (section_type == MachO::S_SYMBOL_STUBS)
7532 outs() << " (size of stubs)\n";
7537 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
7538 uint32_t object_size) {
7539 outs() << " cmd LC_SYMTAB\n";
7540 outs() << " cmdsize " << st.cmdsize;
7541 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7542 outs() << " Incorrect size\n";
7545 outs() << " symoff " << st.symoff;
7546 if (st.symoff > object_size)
7547 outs() << " (past end of file)\n";
7550 outs() << " nsyms " << st.nsyms;
7553 big_size = st.nsyms;
7554 big_size *= sizeof(struct MachO::nlist_64);
7555 big_size += st.symoff;
7556 if (big_size > object_size)
7557 outs() << " (past end of file)\n";
7561 big_size = st.nsyms;
7562 big_size *= sizeof(struct MachO::nlist);
7563 big_size += st.symoff;
7564 if (big_size > object_size)
7565 outs() << " (past end of file)\n";
7569 outs() << " stroff " << st.stroff;
7570 if (st.stroff > object_size)
7571 outs() << " (past end of file)\n";
7574 outs() << " strsize " << st.strsize;
7575 big_size = st.stroff;
7576 big_size += st.strsize;
7577 if (big_size > object_size)
7578 outs() << " (past end of file)\n";
7583 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7584 uint32_t nsyms, uint32_t object_size,
7586 outs() << " cmd LC_DYSYMTAB\n";
7587 outs() << " cmdsize " << dyst.cmdsize;
7588 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7589 outs() << " Incorrect size\n";
7592 outs() << " ilocalsym " << dyst.ilocalsym;
7593 if (dyst.ilocalsym > nsyms)
7594 outs() << " (greater than the number of symbols)\n";
7597 outs() << " nlocalsym " << dyst.nlocalsym;
7599 big_size = dyst.ilocalsym;
7600 big_size += dyst.nlocalsym;
7601 if (big_size > nsyms)
7602 outs() << " (past the end of the symbol table)\n";
7605 outs() << " iextdefsym " << dyst.iextdefsym;
7606 if (dyst.iextdefsym > nsyms)
7607 outs() << " (greater than the number of symbols)\n";
7610 outs() << " nextdefsym " << dyst.nextdefsym;
7611 big_size = dyst.iextdefsym;
7612 big_size += dyst.nextdefsym;
7613 if (big_size > nsyms)
7614 outs() << " (past the end of the symbol table)\n";
7617 outs() << " iundefsym " << dyst.iundefsym;
7618 if (dyst.iundefsym > nsyms)
7619 outs() << " (greater than the number of symbols)\n";
7622 outs() << " nundefsym " << dyst.nundefsym;
7623 big_size = dyst.iundefsym;
7624 big_size += dyst.nundefsym;
7625 if (big_size > nsyms)
7626 outs() << " (past the end of the symbol table)\n";
7629 outs() << " tocoff " << dyst.tocoff;
7630 if (dyst.tocoff > object_size)
7631 outs() << " (past end of file)\n";
7634 outs() << " ntoc " << dyst.ntoc;
7635 big_size = dyst.ntoc;
7636 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7637 big_size += dyst.tocoff;
7638 if (big_size > object_size)
7639 outs() << " (past end of file)\n";
7642 outs() << " modtaboff " << dyst.modtaboff;
7643 if (dyst.modtaboff > object_size)
7644 outs() << " (past end of file)\n";
7647 outs() << " nmodtab " << dyst.nmodtab;
7650 modtabend = dyst.nmodtab;
7651 modtabend *= sizeof(struct MachO::dylib_module_64);
7652 modtabend += dyst.modtaboff;
7654 modtabend = dyst.nmodtab;
7655 modtabend *= sizeof(struct MachO::dylib_module);
7656 modtabend += dyst.modtaboff;
7658 if (modtabend > object_size)
7659 outs() << " (past end of file)\n";
7662 outs() << " extrefsymoff " << dyst.extrefsymoff;
7663 if (dyst.extrefsymoff > object_size)
7664 outs() << " (past end of file)\n";
7667 outs() << " nextrefsyms " << dyst.nextrefsyms;
7668 big_size = dyst.nextrefsyms;
7669 big_size *= sizeof(struct MachO::dylib_reference);
7670 big_size += dyst.extrefsymoff;
7671 if (big_size > object_size)
7672 outs() << " (past end of file)\n";
7675 outs() << " indirectsymoff " << dyst.indirectsymoff;
7676 if (dyst.indirectsymoff > object_size)
7677 outs() << " (past end of file)\n";
7680 outs() << " nindirectsyms " << dyst.nindirectsyms;
7681 big_size = dyst.nindirectsyms;
7682 big_size *= sizeof(uint32_t);
7683 big_size += dyst.indirectsymoff;
7684 if (big_size > object_size)
7685 outs() << " (past end of file)\n";
7688 outs() << " extreloff " << dyst.extreloff;
7689 if (dyst.extreloff > object_size)
7690 outs() << " (past end of file)\n";
7693 outs() << " nextrel " << dyst.nextrel;
7694 big_size = dyst.nextrel;
7695 big_size *= sizeof(struct MachO::relocation_info);
7696 big_size += dyst.extreloff;
7697 if (big_size > object_size)
7698 outs() << " (past end of file)\n";
7701 outs() << " locreloff " << dyst.locreloff;
7702 if (dyst.locreloff > object_size)
7703 outs() << " (past end of file)\n";
7706 outs() << " nlocrel " << dyst.nlocrel;
7707 big_size = dyst.nlocrel;
7708 big_size *= sizeof(struct MachO::relocation_info);
7709 big_size += dyst.locreloff;
7710 if (big_size > object_size)
7711 outs() << " (past end of file)\n";
7716 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7717 uint32_t object_size) {
7718 if (dc.cmd == MachO::LC_DYLD_INFO)
7719 outs() << " cmd LC_DYLD_INFO\n";
7721 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7722 outs() << " cmdsize " << dc.cmdsize;
7723 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7724 outs() << " Incorrect size\n";
7727 outs() << " rebase_off " << dc.rebase_off;
7728 if (dc.rebase_off > object_size)
7729 outs() << " (past end of file)\n";
7732 outs() << " rebase_size " << dc.rebase_size;
7734 big_size = dc.rebase_off;
7735 big_size += dc.rebase_size;
7736 if (big_size > object_size)
7737 outs() << " (past end of file)\n";
7740 outs() << " bind_off " << dc.bind_off;
7741 if (dc.bind_off > object_size)
7742 outs() << " (past end of file)\n";
7745 outs() << " bind_size " << dc.bind_size;
7746 big_size = dc.bind_off;
7747 big_size += dc.bind_size;
7748 if (big_size > object_size)
7749 outs() << " (past end of file)\n";
7752 outs() << " weak_bind_off " << dc.weak_bind_off;
7753 if (dc.weak_bind_off > object_size)
7754 outs() << " (past end of file)\n";
7757 outs() << " weak_bind_size " << dc.weak_bind_size;
7758 big_size = dc.weak_bind_off;
7759 big_size += dc.weak_bind_size;
7760 if (big_size > object_size)
7761 outs() << " (past end of file)\n";
7764 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7765 if (dc.lazy_bind_off > object_size)
7766 outs() << " (past end of file)\n";
7769 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7770 big_size = dc.lazy_bind_off;
7771 big_size += dc.lazy_bind_size;
7772 if (big_size > object_size)
7773 outs() << " (past end of file)\n";
7776 outs() << " export_off " << dc.export_off;
7777 if (dc.export_off > object_size)
7778 outs() << " (past end of file)\n";
7781 outs() << " export_size " << dc.export_size;
7782 big_size = dc.export_off;
7783 big_size += dc.export_size;
7784 if (big_size > object_size)
7785 outs() << " (past end of file)\n";
7790 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7792 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7793 outs() << " cmd LC_ID_DYLINKER\n";
7794 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7795 outs() << " cmd LC_LOAD_DYLINKER\n";
7796 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7797 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7799 outs() << " cmd ?(" << dyld.cmd << ")\n";
7800 outs() << " cmdsize " << dyld.cmdsize;
7801 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7802 outs() << " Incorrect size\n";
7805 if (dyld.name >= dyld.cmdsize)
7806 outs() << " name ?(bad offset " << dyld.name << ")\n";
7808 const char *P = (const char *)(Ptr) + dyld.name;
7809 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7813 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7814 outs() << " cmd LC_UUID\n";
7815 outs() << " cmdsize " << uuid.cmdsize;
7816 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7817 outs() << " Incorrect size\n";
7821 for (int i = 0; i < 16; ++i) {
7822 outs() << format("%02" PRIX32, uuid.uuid[i]);
7823 if (i == 3 || i == 5 || i == 7 || i == 9)
7829 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
7830 outs() << " cmd LC_RPATH\n";
7831 outs() << " cmdsize " << rpath.cmdsize;
7832 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7833 outs() << " Incorrect size\n";
7836 if (rpath.path >= rpath.cmdsize)
7837 outs() << " path ?(bad offset " << rpath.path << ")\n";
7839 const char *P = (const char *)(Ptr) + rpath.path;
7840 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7844 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
7845 StringRef LoadCmdName;
7847 case MachO::LC_VERSION_MIN_MACOSX:
7848 LoadCmdName = "LC_VERSION_MIN_MACOSX";
7850 case MachO::LC_VERSION_MIN_IPHONEOS:
7851 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
7853 case MachO::LC_VERSION_MIN_TVOS:
7854 LoadCmdName = "LC_VERSION_MIN_TVOS";
7856 case MachO::LC_VERSION_MIN_WATCHOS:
7857 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
7860 llvm_unreachable("Unknown version min load command");
7863 outs() << " cmd " << LoadCmdName << '\n';
7864 outs() << " cmdsize " << vd.cmdsize;
7865 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7866 outs() << " Incorrect size\n";
7869 outs() << " version "
7870 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7871 << MachOObjectFile::getVersionMinMinor(vd, false);
7872 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7874 outs() << "." << Update;
7877 outs() << " sdk n/a";
7880 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7881 << MachOObjectFile::getVersionMinMinor(vd, true);
7883 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7885 outs() << "." << Update;
7889 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7890 outs() << " cmd LC_SOURCE_VERSION\n";
7891 outs() << " cmdsize " << sd.cmdsize;
7892 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7893 outs() << " Incorrect size\n";
7896 uint64_t a = (sd.version >> 40) & 0xffffff;
7897 uint64_t b = (sd.version >> 30) & 0x3ff;
7898 uint64_t c = (sd.version >> 20) & 0x3ff;
7899 uint64_t d = (sd.version >> 10) & 0x3ff;
7900 uint64_t e = sd.version & 0x3ff;
7901 outs() << " version " << a << "." << b;
7903 outs() << "." << c << "." << d << "." << e;
7905 outs() << "." << c << "." << d;
7911 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7912 outs() << " cmd LC_MAIN\n";
7913 outs() << " cmdsize " << ep.cmdsize;
7914 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7915 outs() << " Incorrect size\n";
7918 outs() << " entryoff " << ep.entryoff << "\n";
7919 outs() << " stacksize " << ep.stacksize << "\n";
7922 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7923 uint32_t object_size) {
7924 outs() << " cmd LC_ENCRYPTION_INFO\n";
7925 outs() << " cmdsize " << ec.cmdsize;
7926 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7927 outs() << " Incorrect size\n";
7930 outs() << " cryptoff " << ec.cryptoff;
7931 if (ec.cryptoff > object_size)
7932 outs() << " (past end of file)\n";
7935 outs() << " cryptsize " << ec.cryptsize;
7936 if (ec.cryptsize > object_size)
7937 outs() << " (past end of file)\n";
7940 outs() << " cryptid " << ec.cryptid << "\n";
7943 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
7944 uint32_t object_size) {
7945 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7946 outs() << " cmdsize " << ec.cmdsize;
7947 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7948 outs() << " Incorrect size\n";
7951 outs() << " cryptoff " << ec.cryptoff;
7952 if (ec.cryptoff > object_size)
7953 outs() << " (past end of file)\n";
7956 outs() << " cryptsize " << ec.cryptsize;
7957 if (ec.cryptsize > object_size)
7958 outs() << " (past end of file)\n";
7961 outs() << " cryptid " << ec.cryptid << "\n";
7962 outs() << " pad " << ec.pad << "\n";
7965 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7967 outs() << " cmd LC_LINKER_OPTION\n";
7968 outs() << " cmdsize " << lo.cmdsize;
7969 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7970 outs() << " Incorrect size\n";
7973 outs() << " count " << lo.count << "\n";
7974 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7975 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7978 while (*string == '\0' && left > 0) {
7984 outs() << " string #" << i << " " << format("%.*s\n", left, string);
7985 uint32_t NullPos = StringRef(string, left).find('\0');
7986 uint32_t len = std::min(NullPos, left) + 1;
7992 outs() << " count " << lo.count << " does not match number of strings "
7996 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7998 outs() << " cmd LC_SUB_FRAMEWORK\n";
7999 outs() << " cmdsize " << sub.cmdsize;
8000 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8001 outs() << " Incorrect size\n";
8004 if (sub.umbrella < sub.cmdsize) {
8005 const char *P = Ptr + sub.umbrella;
8006 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8008 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8012 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8014 outs() << " cmd LC_SUB_UMBRELLA\n";
8015 outs() << " cmdsize " << sub.cmdsize;
8016 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8017 outs() << " Incorrect size\n";
8020 if (sub.sub_umbrella < sub.cmdsize) {
8021 const char *P = Ptr + sub.sub_umbrella;
8022 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8024 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8028 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
8030 outs() << " cmd LC_SUB_LIBRARY\n";
8031 outs() << " cmdsize " << sub.cmdsize;
8032 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8033 outs() << " Incorrect size\n";
8036 if (sub.sub_library < sub.cmdsize) {
8037 const char *P = Ptr + sub.sub_library;
8038 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8040 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8044 static void PrintSubClientCommand(MachO::sub_client_command sub,
8046 outs() << " cmd LC_SUB_CLIENT\n";
8047 outs() << " cmdsize " << sub.cmdsize;
8048 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8049 outs() << " Incorrect size\n";
8052 if (sub.client < sub.cmdsize) {
8053 const char *P = Ptr + sub.client;
8054 outs() << " client " << P << " (offset " << sub.client << ")\n";
8056 outs() << " client ?(bad offset " << sub.client << ")\n";
8060 static void PrintRoutinesCommand(MachO::routines_command r) {
8061 outs() << " cmd LC_ROUTINES\n";
8062 outs() << " cmdsize " << r.cmdsize;
8063 if (r.cmdsize != sizeof(struct MachO::routines_command))
8064 outs() << " Incorrect size\n";
8067 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8068 outs() << " init_module " << r.init_module << "\n";
8069 outs() << " reserved1 " << r.reserved1 << "\n";
8070 outs() << " reserved2 " << r.reserved2 << "\n";
8071 outs() << " reserved3 " << r.reserved3 << "\n";
8072 outs() << " reserved4 " << r.reserved4 << "\n";
8073 outs() << " reserved5 " << r.reserved5 << "\n";
8074 outs() << " reserved6 " << r.reserved6 << "\n";
8077 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8078 outs() << " cmd LC_ROUTINES_64\n";
8079 outs() << " cmdsize " << r.cmdsize;
8080 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8081 outs() << " Incorrect size\n";
8084 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8085 outs() << " init_module " << r.init_module << "\n";
8086 outs() << " reserved1 " << r.reserved1 << "\n";
8087 outs() << " reserved2 " << r.reserved2 << "\n";
8088 outs() << " reserved3 " << r.reserved3 << "\n";
8089 outs() << " reserved4 " << r.reserved4 << "\n";
8090 outs() << " reserved5 " << r.reserved5 << "\n";
8091 outs() << " reserved6 " << r.reserved6 << "\n";
8094 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8095 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8096 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8097 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8098 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8099 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8100 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8101 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8102 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8103 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8104 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8105 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8106 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8107 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8108 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8109 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8110 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8111 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8112 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8113 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8114 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8115 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8118 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
8120 outs() << "\t mmst_reg ";
8121 for (f = 0; f < 10; f++)
8122 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8124 outs() << "\t mmst_rsrv ";
8125 for (f = 0; f < 6; f++)
8126 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8130 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
8132 outs() << "\t xmm_reg ";
8133 for (f = 0; f < 16; f++)
8134 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8138 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8139 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8140 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8141 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8142 outs() << " denorm " << fpu.fpu_fcw.denorm;
8143 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8144 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8145 outs() << " undfl " << fpu.fpu_fcw.undfl;
8146 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8147 outs() << "\t\t pc ";
8148 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8149 outs() << "FP_PREC_24B ";
8150 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8151 outs() << "FP_PREC_53B ";
8152 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8153 outs() << "FP_PREC_64B ";
8155 outs() << fpu.fpu_fcw.pc << " ";
8157 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8158 outs() << "FP_RND_NEAR ";
8159 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8160 outs() << "FP_RND_DOWN ";
8161 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8162 outs() << "FP_RND_UP ";
8163 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
8164 outs() << "FP_CHOP ";
8166 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8167 outs() << " denorm " << fpu.fpu_fsw.denorm;
8168 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8169 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8170 outs() << " undfl " << fpu.fpu_fsw.undfl;
8171 outs() << " precis " << fpu.fpu_fsw.precis;
8172 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8173 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8174 outs() << " c0 " << fpu.fpu_fsw.c0;
8175 outs() << " c1 " << fpu.fpu_fsw.c1;
8176 outs() << " c2 " << fpu.fpu_fsw.c2;
8177 outs() << " tos " << fpu.fpu_fsw.tos;
8178 outs() << " c3 " << fpu.fpu_fsw.c3;
8179 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8180 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8181 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8182 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8183 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8184 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8185 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8186 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8187 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8188 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8189 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8190 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8192 outs() << "\t fpu_stmm0:\n";
8193 Print_mmst_reg(fpu.fpu_stmm0);
8194 outs() << "\t fpu_stmm1:\n";
8195 Print_mmst_reg(fpu.fpu_stmm1);
8196 outs() << "\t fpu_stmm2:\n";
8197 Print_mmst_reg(fpu.fpu_stmm2);
8198 outs() << "\t fpu_stmm3:\n";
8199 Print_mmst_reg(fpu.fpu_stmm3);
8200 outs() << "\t fpu_stmm4:\n";
8201 Print_mmst_reg(fpu.fpu_stmm4);
8202 outs() << "\t fpu_stmm5:\n";
8203 Print_mmst_reg(fpu.fpu_stmm5);
8204 outs() << "\t fpu_stmm6:\n";
8205 Print_mmst_reg(fpu.fpu_stmm6);
8206 outs() << "\t fpu_stmm7:\n";
8207 Print_mmst_reg(fpu.fpu_stmm7);
8208 outs() << "\t fpu_xmm0:\n";
8209 Print_xmm_reg(fpu.fpu_xmm0);
8210 outs() << "\t fpu_xmm1:\n";
8211 Print_xmm_reg(fpu.fpu_xmm1);
8212 outs() << "\t fpu_xmm2:\n";
8213 Print_xmm_reg(fpu.fpu_xmm2);
8214 outs() << "\t fpu_xmm3:\n";
8215 Print_xmm_reg(fpu.fpu_xmm3);
8216 outs() << "\t fpu_xmm4:\n";
8217 Print_xmm_reg(fpu.fpu_xmm4);
8218 outs() << "\t fpu_xmm5:\n";
8219 Print_xmm_reg(fpu.fpu_xmm5);
8220 outs() << "\t fpu_xmm6:\n";
8221 Print_xmm_reg(fpu.fpu_xmm6);
8222 outs() << "\t fpu_xmm7:\n";
8223 Print_xmm_reg(fpu.fpu_xmm7);
8224 outs() << "\t fpu_xmm8:\n";
8225 Print_xmm_reg(fpu.fpu_xmm8);
8226 outs() << "\t fpu_xmm9:\n";
8227 Print_xmm_reg(fpu.fpu_xmm9);
8228 outs() << "\t fpu_xmm10:\n";
8229 Print_xmm_reg(fpu.fpu_xmm10);
8230 outs() << "\t fpu_xmm11:\n";
8231 Print_xmm_reg(fpu.fpu_xmm11);
8232 outs() << "\t fpu_xmm12:\n";
8233 Print_xmm_reg(fpu.fpu_xmm12);
8234 outs() << "\t fpu_xmm13:\n";
8235 Print_xmm_reg(fpu.fpu_xmm13);
8236 outs() << "\t fpu_xmm14:\n";
8237 Print_xmm_reg(fpu.fpu_xmm14);
8238 outs() << "\t fpu_xmm15:\n";
8239 Print_xmm_reg(fpu.fpu_xmm15);
8240 outs() << "\t fpu_rsrv4:\n";
8241 for (uint32_t f = 0; f < 6; f++) {
8243 for (uint32_t g = 0; g < 16; g++)
8244 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
8247 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8251 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8252 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8253 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8254 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8257 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8258 bool isLittleEndian, uint32_t cputype) {
8259 if (t.cmd == MachO::LC_THREAD)
8260 outs() << " cmd LC_THREAD\n";
8261 else if (t.cmd == MachO::LC_UNIXTHREAD)
8262 outs() << " cmd LC_UNIXTHREAD\n";
8264 outs() << " cmd " << t.cmd << " (unknown)\n";
8265 outs() << " cmdsize " << t.cmdsize;
8266 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8267 outs() << " Incorrect size\n";
8271 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8272 const char *end = Ptr + t.cmdsize;
8273 uint32_t flavor, count, left;
8274 if (cputype == MachO::CPU_TYPE_X86_64) {
8275 while (begin < end) {
8276 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8277 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8278 begin += sizeof(uint32_t);
8283 if (isLittleEndian != sys::IsLittleEndianHost)
8284 sys::swapByteOrder(flavor);
8285 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8286 memcpy((char *)&count, begin, sizeof(uint32_t));
8287 begin += sizeof(uint32_t);
8292 if (isLittleEndian != sys::IsLittleEndianHost)
8293 sys::swapByteOrder(count);
8294 if (flavor == MachO::x86_THREAD_STATE64) {
8295 outs() << " flavor x86_THREAD_STATE64\n";
8296 if (count == MachO::x86_THREAD_STATE64_COUNT)
8297 outs() << " count x86_THREAD_STATE64_COUNT\n";
8299 outs() << " count " << count
8300 << " (not x86_THREAD_STATE64_COUNT)\n";
8301 MachO::x86_thread_state64_t cpu64;
8303 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8304 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8305 begin += sizeof(MachO::x86_thread_state64_t);
8307 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8308 memcpy(&cpu64, begin, left);
8311 if (isLittleEndian != sys::IsLittleEndianHost)
8313 Print_x86_thread_state64_t(cpu64);
8314 } else if (flavor == MachO::x86_THREAD_STATE) {
8315 outs() << " flavor x86_THREAD_STATE\n";
8316 if (count == MachO::x86_THREAD_STATE_COUNT)
8317 outs() << " count x86_THREAD_STATE_COUNT\n";
8319 outs() << " count " << count
8320 << " (not x86_THREAD_STATE_COUNT)\n";
8321 struct MachO::x86_thread_state_t ts;
8323 if (left >= sizeof(MachO::x86_thread_state_t)) {
8324 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8325 begin += sizeof(MachO::x86_thread_state_t);
8327 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8328 memcpy(&ts, begin, left);
8331 if (isLittleEndian != sys::IsLittleEndianHost)
8333 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8334 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8335 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8336 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8338 outs() << "tsh.count " << ts.tsh.count
8339 << " (not x86_THREAD_STATE64_COUNT\n";
8340 Print_x86_thread_state64_t(ts.uts.ts64);
8342 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8343 << ts.tsh.count << "\n";
8345 } else if (flavor == MachO::x86_FLOAT_STATE) {
8346 outs() << " flavor x86_FLOAT_STATE\n";
8347 if (count == MachO::x86_FLOAT_STATE_COUNT)
8348 outs() << " count x86_FLOAT_STATE_COUNT\n";
8350 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
8351 struct MachO::x86_float_state_t fs;
8353 if (left >= sizeof(MachO::x86_float_state_t)) {
8354 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8355 begin += sizeof(MachO::x86_float_state_t);
8357 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8358 memcpy(&fs, begin, left);
8361 if (isLittleEndian != sys::IsLittleEndianHost)
8363 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8364 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
8365 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
8366 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8368 outs() << "fsh.count " << fs.fsh.count
8369 << " (not x86_FLOAT_STATE64_COUNT\n";
8370 Print_x86_float_state_t(fs.ufs.fs64);
8372 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8373 << fs.fsh.count << "\n";
8375 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8376 outs() << " flavor x86_EXCEPTION_STATE\n";
8377 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8378 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8380 outs() << " count " << count
8381 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8382 struct MachO::x86_exception_state_t es;
8384 if (left >= sizeof(MachO::x86_exception_state_t)) {
8385 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8386 begin += sizeof(MachO::x86_exception_state_t);
8388 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8389 memcpy(&es, begin, left);
8392 if (isLittleEndian != sys::IsLittleEndianHost)
8394 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8395 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
8396 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
8397 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8399 outs() << "\t esh.count " << es.esh.count
8400 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8401 Print_x86_exception_state_t(es.ues.es64);
8403 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8404 << es.esh.count << "\n";
8407 outs() << " flavor " << flavor << " (unknown)\n";
8408 outs() << " count " << count << "\n";
8409 outs() << " state (unknown)\n";
8410 begin += count * sizeof(uint32_t);
8414 while (begin < end) {
8415 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8416 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8417 begin += sizeof(uint32_t);
8422 if (isLittleEndian != sys::IsLittleEndianHost)
8423 sys::swapByteOrder(flavor);
8424 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8425 memcpy((char *)&count, begin, sizeof(uint32_t));
8426 begin += sizeof(uint32_t);
8431 if (isLittleEndian != sys::IsLittleEndianHost)
8432 sys::swapByteOrder(count);
8433 outs() << " flavor " << flavor << "\n";
8434 outs() << " count " << count << "\n";
8435 outs() << " state (Unknown cputype/cpusubtype)\n";
8436 begin += count * sizeof(uint32_t);
8441 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8442 if (dl.cmd == MachO::LC_ID_DYLIB)
8443 outs() << " cmd LC_ID_DYLIB\n";
8444 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8445 outs() << " cmd LC_LOAD_DYLIB\n";
8446 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8447 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8448 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8449 outs() << " cmd LC_REEXPORT_DYLIB\n";
8450 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8451 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8452 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8453 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8455 outs() << " cmd " << dl.cmd << " (unknown)\n";
8456 outs() << " cmdsize " << dl.cmdsize;
8457 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8458 outs() << " Incorrect size\n";
8461 if (dl.dylib.name < dl.cmdsize) {
8462 const char *P = (const char *)(Ptr) + dl.dylib.name;
8463 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8465 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8467 outs() << " time stamp " << dl.dylib.timestamp << " ";
8468 time_t t = dl.dylib.timestamp;
8469 outs() << ctime(&t);
8470 outs() << " current version ";
8471 if (dl.dylib.current_version == 0xffffffff)
8474 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8475 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8476 << (dl.dylib.current_version & 0xff) << "\n";
8477 outs() << "compatibility version ";
8478 if (dl.dylib.compatibility_version == 0xffffffff)
8481 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8482 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8483 << (dl.dylib.compatibility_version & 0xff) << "\n";
8486 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8487 uint32_t object_size) {
8488 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8489 outs() << " cmd LC_FUNCTION_STARTS\n";
8490 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8491 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8492 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8493 outs() << " cmd LC_FUNCTION_STARTS\n";
8494 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8495 outs() << " cmd LC_DATA_IN_CODE\n";
8496 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8497 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8498 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8499 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8501 outs() << " cmd " << ld.cmd << " (?)\n";
8502 outs() << " cmdsize " << ld.cmdsize;
8503 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8504 outs() << " Incorrect size\n";
8507 outs() << " dataoff " << ld.dataoff;
8508 if (ld.dataoff > object_size)
8509 outs() << " (past end of file)\n";
8512 outs() << " datasize " << ld.datasize;
8513 uint64_t big_size = ld.dataoff;
8514 big_size += ld.datasize;
8515 if (big_size > object_size)
8516 outs() << " (past end of file)\n";
8521 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8522 uint32_t cputype, bool verbose) {
8523 StringRef Buf = Obj->getData();
8525 for (const auto &Command : Obj->load_commands()) {
8526 outs() << "Load command " << Index++ << "\n";
8527 if (Command.C.cmd == MachO::LC_SEGMENT) {
8528 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8529 const char *sg_segname = SLC.segname;
8530 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8531 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8532 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8534 for (unsigned j = 0; j < SLC.nsects; j++) {
8535 MachO::section S = Obj->getSection(Command, j);
8536 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8537 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8538 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8540 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8541 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8542 const char *sg_segname = SLC_64.segname;
8543 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8544 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8545 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8546 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8547 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8548 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8549 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8550 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8551 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8552 sg_segname, filetype, Buf.size(), verbose);
8554 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8555 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8556 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
8557 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8558 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8559 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8560 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8562 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8563 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8564 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8565 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8566 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8567 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8568 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8569 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8570 PrintDyldLoadCommand(Dyld, Command.Ptr);
8571 } else if (Command.C.cmd == MachO::LC_UUID) {
8572 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8573 PrintUuidLoadCommand(Uuid);
8574 } else if (Command.C.cmd == MachO::LC_RPATH) {
8575 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8576 PrintRpathLoadCommand(Rpath, Command.Ptr);
8577 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
8578 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8579 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8580 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
8581 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8582 PrintVersionMinLoadCommand(Vd);
8583 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8584 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8585 PrintSourceVersionCommand(Sd);
8586 } else if (Command.C.cmd == MachO::LC_MAIN) {
8587 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8588 PrintEntryPointCommand(Ep);
8589 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
8590 MachO::encryption_info_command Ei =
8591 Obj->getEncryptionInfoCommand(Command);
8592 PrintEncryptionInfoCommand(Ei, Buf.size());
8593 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
8594 MachO::encryption_info_command_64 Ei =
8595 Obj->getEncryptionInfoCommand64(Command);
8596 PrintEncryptionInfoCommand64(Ei, Buf.size());
8597 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
8598 MachO::linker_option_command Lo =
8599 Obj->getLinkerOptionLoadCommand(Command);
8600 PrintLinkerOptionCommand(Lo, Command.Ptr);
8601 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8602 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8603 PrintSubFrameworkCommand(Sf, Command.Ptr);
8604 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8605 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8606 PrintSubUmbrellaCommand(Sf, Command.Ptr);
8607 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8608 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8609 PrintSubLibraryCommand(Sl, Command.Ptr);
8610 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8611 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8612 PrintSubClientCommand(Sc, Command.Ptr);
8613 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8614 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8615 PrintRoutinesCommand(Rc);
8616 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8617 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8618 PrintRoutinesCommand64(Rc);
8619 } else if (Command.C.cmd == MachO::LC_THREAD ||
8620 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8621 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8622 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
8623 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8624 Command.C.cmd == MachO::LC_ID_DYLIB ||
8625 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8626 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8627 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8628 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
8629 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8630 PrintDylibCommand(Dl, Command.Ptr);
8631 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8632 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8633 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8634 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8635 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8636 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8637 MachO::linkedit_data_command Ld =
8638 Obj->getLinkeditDataLoadCommand(Command);
8639 PrintLinkEditDataCommand(Ld, Buf.size());
8641 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8643 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8644 // TODO: get and print the raw bytes of the load command.
8646 // TODO: print all the other kinds of load commands.
8650 static void getAndPrintMachHeader(const MachOObjectFile *Obj,
8651 uint32_t &filetype, uint32_t &cputype,
8653 if (Obj->is64Bit()) {
8654 MachO::mach_header_64 H_64;
8655 H_64 = Obj->getHeader64();
8656 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8657 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8658 filetype = H_64.filetype;
8659 cputype = H_64.cputype;
8661 MachO::mach_header H;
8662 H = Obj->getHeader();
8663 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8664 H.sizeofcmds, H.flags, verbose);
8665 filetype = H.filetype;
8666 cputype = H.cputype;
8670 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8671 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
8672 uint32_t filetype = 0;
8673 uint32_t cputype = 0;
8674 getAndPrintMachHeader(file, filetype, cputype, !NonVerbose);
8675 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
8678 //===----------------------------------------------------------------------===//
8679 // export trie dumping
8680 //===----------------------------------------------------------------------===//
8682 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
8683 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8684 uint64_t Flags = Entry.flags();
8685 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8686 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8687 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8688 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8689 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8690 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8691 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8693 outs() << "[re-export] ";
8695 outs() << format("0x%08llX ",
8696 Entry.address()); // FIXME:add in base address
8697 outs() << Entry.name();
8698 if (WeakDef || ThreadLocal || Resolver || Abs) {
8699 bool NeedsComma = false;
8702 outs() << "weak_def";
8708 outs() << "per-thread";
8714 outs() << "absolute";
8720 outs() << format("resolver=0x%08llX", Entry.other());
8726 StringRef DylibName = "unknown";
8727 int Ordinal = Entry.other() - 1;
8728 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8729 if (Entry.otherName().empty())
8730 outs() << " (from " << DylibName << ")";
8732 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
8738 //===----------------------------------------------------------------------===//
8739 // rebase table dumping
8740 //===----------------------------------------------------------------------===//
8745 SegInfo(const object::MachOObjectFile *Obj);
8747 StringRef segmentName(uint32_t SegIndex);
8748 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8749 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
8750 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
8753 struct SectionInfo {
8756 StringRef SectionName;
8757 StringRef SegmentName;
8758 uint64_t OffsetInSegment;
8759 uint64_t SegmentStartAddress;
8760 uint32_t SegmentIndex;
8762 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8763 SmallVector<SectionInfo, 32> Sections;
8767 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8768 // Build table of sections so segIndex/offset pairs can be translated.
8769 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
8770 StringRef CurSegName;
8771 uint64_t CurSegAddress;
8772 for (const SectionRef &Section : Obj->sections()) {
8774 error(Section.getName(Info.SectionName));
8775 Info.Address = Section.getAddress();
8776 Info.Size = Section.getSize();
8778 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8779 if (!Info.SegmentName.equals(CurSegName)) {
8781 CurSegName = Info.SegmentName;
8782 CurSegAddress = Info.Address;
8784 Info.SegmentIndex = CurSegIndex - 1;
8785 Info.OffsetInSegment = Info.Address - CurSegAddress;
8786 Info.SegmentStartAddress = CurSegAddress;
8787 Sections.push_back(Info);
8791 StringRef SegInfo::segmentName(uint32_t SegIndex) {
8792 for (const SectionInfo &SI : Sections) {
8793 if (SI.SegmentIndex == SegIndex)
8794 return SI.SegmentName;
8796 llvm_unreachable("invalid segIndex");
8799 bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
8800 uint64_t OffsetInSeg) {
8801 for (const SectionInfo &SI : Sections) {
8802 if (SI.SegmentIndex != SegIndex)
8804 if (SI.OffsetInSegment > OffsetInSeg)
8806 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8813 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8814 uint64_t OffsetInSeg) {
8815 for (const SectionInfo &SI : Sections) {
8816 if (SI.SegmentIndex != SegIndex)
8818 if (SI.OffsetInSegment > OffsetInSeg)
8820 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8824 llvm_unreachable("segIndex and offset not in any section");
8827 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8828 return findSection(SegIndex, OffsetInSeg).SectionName;
8831 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8832 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8833 return SI.SegmentStartAddress + OffsetInSeg;
8836 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8837 // Build table of sections so names can used in final output.
8838 SegInfo sectionTable(Obj);
8840 outs() << "segment section address type\n";
8841 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8842 uint32_t SegIndex = Entry.segmentIndex();
8843 uint64_t OffsetInSeg = Entry.segmentOffset();
8844 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8845 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8846 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8848 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
8849 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8850 SegmentName.str().c_str(), SectionName.str().c_str(),
8851 Address, Entry.typeName().str().c_str());
8855 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8856 StringRef DylibName;
8858 case MachO::BIND_SPECIAL_DYLIB_SELF:
8859 return "this-image";
8860 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8861 return "main-executable";
8862 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8863 return "flat-namespace";
8866 std::error_code EC =
8867 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
8869 return "<<bad library ordinal>>";
8873 return "<<unknown special ordinal>>";
8876 //===----------------------------------------------------------------------===//
8877 // bind table dumping
8878 //===----------------------------------------------------------------------===//
8880 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8881 // Build table of sections so names can used in final output.
8882 SegInfo sectionTable(Obj);
8884 outs() << "segment section address type "
8885 "addend dylib symbol\n";
8886 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8887 uint32_t SegIndex = Entry.segmentIndex();
8888 uint64_t OffsetInSeg = Entry.segmentOffset();
8889 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8890 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8891 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8893 // Table lines look like:
8894 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
8896 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
8897 Attr = " (weak_import)";
8898 outs() << left_justify(SegmentName, 8) << " "
8899 << left_justify(SectionName, 18) << " "
8900 << format_hex(Address, 10, true) << " "
8901 << left_justify(Entry.typeName(), 8) << " "
8902 << format_decimal(Entry.addend(), 8) << " "
8903 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8904 << Entry.symbolName() << Attr << "\n";
8908 //===----------------------------------------------------------------------===//
8909 // lazy bind table dumping
8910 //===----------------------------------------------------------------------===//
8912 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8913 // Build table of sections so names can used in final output.
8914 SegInfo sectionTable(Obj);
8916 outs() << "segment section address "
8918 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8919 uint32_t SegIndex = Entry.segmentIndex();
8920 uint64_t OffsetInSeg = Entry.segmentOffset();
8921 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8922 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8923 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8925 // Table lines look like:
8926 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
8927 outs() << left_justify(SegmentName, 8) << " "
8928 << left_justify(SectionName, 18) << " "
8929 << format_hex(Address, 10, true) << " "
8930 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8931 << Entry.symbolName() << "\n";
8935 //===----------------------------------------------------------------------===//
8936 // weak bind table dumping
8937 //===----------------------------------------------------------------------===//
8939 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8940 // Build table of sections so names can used in final output.
8941 SegInfo sectionTable(Obj);
8943 outs() << "segment section address "
8944 "type addend symbol\n";
8945 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8946 // Strong symbols don't have a location to update.
8947 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
8948 outs() << " strong "
8949 << Entry.symbolName() << "\n";
8952 uint32_t SegIndex = Entry.segmentIndex();
8953 uint64_t OffsetInSeg = Entry.segmentOffset();
8954 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8955 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8956 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8958 // Table lines look like:
8959 // __DATA __data 0x00001000 pointer 0 _foo
8960 outs() << left_justify(SegmentName, 8) << " "
8961 << left_justify(SectionName, 18) << " "
8962 << format_hex(Address, 10, true) << " "
8963 << left_justify(Entry.typeName(), 8) << " "
8964 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8969 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
8970 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8971 // information for that address. If the address is found its binding symbol
8972 // name is returned. If not nullptr is returned.
8973 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8974 struct DisassembleInfo *info) {
8975 if (info->bindtable == nullptr) {
8976 info->bindtable = new (BindTable);
8977 SegInfo sectionTable(info->O);
8978 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8979 uint32_t SegIndex = Entry.segmentIndex();
8980 uint64_t OffsetInSeg = Entry.segmentOffset();
8981 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8983 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8984 const char *SymbolName = nullptr;
8985 StringRef name = Entry.symbolName();
8987 SymbolName = name.data();
8988 info->bindtable->push_back(std::make_pair(Address, SymbolName));
8991 for (bind_table_iterator BI = info->bindtable->begin(),
8992 BE = info->bindtable->end();
8994 uint64_t Address = BI->first;
8995 if (ReferenceValue == Address) {
8996 const char *SymbolName = BI->second;