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,
918 stride = sizeof(uint64_t);
920 stride = sizeof(uint32_t);
921 for (uint32_t i = 0; i < sect_size; i += stride) {
922 const char *SymbolName = nullptr;
924 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
925 uint64_t pointer_value;
926 memcpy(&pointer_value, sect + i, stride);
927 if (O->isLittleEndian() != sys::IsLittleEndianHost)
928 sys::swapByteOrder(pointer_value);
929 outs() << format("0x%016" PRIx64, pointer_value);
931 SymbolName = GuessSymbolName(pointer_value, AddrMap);
933 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
934 uint32_t pointer_value;
935 memcpy(&pointer_value, sect + i, stride);
936 if (O->isLittleEndian() != sys::IsLittleEndianHost)
937 sys::swapByteOrder(pointer_value);
938 outs() << format("0x%08" PRIx32, pointer_value);
940 SymbolName = GuessSymbolName(pointer_value, AddrMap);
943 outs() << " " << SymbolName;
948 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
949 uint32_t size, uint64_t addr) {
950 uint32_t cputype = O->getHeader().cputype;
951 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
953 for (uint32_t i = 0; i < size; i += j, addr += j) {
955 outs() << format("%016" PRIx64, addr) << "\t";
957 outs() << format("%08" PRIx64, addr) << "\t";
958 for (j = 0; j < 16 && i + j < size; j++) {
959 uint8_t byte_word = *(sect + i + j);
960 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
966 for (uint32_t i = 0; i < size; i += j, addr += j) {
968 outs() << format("%016" PRIx64, addr) << "\t";
970 outs() << format("%08" PRIx64, sect) << "\t";
971 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
972 j += sizeof(int32_t)) {
973 if (i + j + sizeof(int32_t) < size) {
975 memcpy(&long_word, sect + i + j, sizeof(int32_t));
976 if (O->isLittleEndian() != sys::IsLittleEndianHost)
977 sys::swapByteOrder(long_word);
978 outs() << format("%08" PRIx32, long_word) << " ";
980 for (uint32_t k = 0; i + j + k < size; k++) {
981 uint8_t byte_word = *(sect + i + j);
982 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
991 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
992 StringRef DisSegName, StringRef DisSectName);
993 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
994 uint32_t size, uint32_t addr);
996 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
998 SymbolAddressMap AddrMap;
1000 CreateSymbolAddressMap(O, &AddrMap);
1002 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1003 StringRef DumpSection = FilterSections[i];
1004 std::pair<StringRef, StringRef> DumpSegSectName;
1005 DumpSegSectName = DumpSection.split(',');
1006 StringRef DumpSegName, DumpSectName;
1007 if (DumpSegSectName.second.size()) {
1008 DumpSegName = DumpSegSectName.first;
1009 DumpSectName = DumpSegSectName.second;
1012 DumpSectName = DumpSegSectName.first;
1014 for (const SectionRef &Section : O->sections()) {
1016 Section.getName(SectName);
1017 DataRefImpl Ref = Section.getRawDataRefImpl();
1018 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1019 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1020 (SectName == DumpSectName)) {
1022 uint32_t section_flags;
1024 const MachO::section_64 Sec = O->getSection64(Ref);
1025 section_flags = Sec.flags;
1028 const MachO::section Sec = O->getSection(Ref);
1029 section_flags = Sec.flags;
1031 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1034 Section.getContents(BytesStr);
1035 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1036 uint32_t sect_size = BytesStr.size();
1037 uint64_t sect_addr = Section.getAddress();
1039 outs() << "Contents of (" << SegName << "," << SectName
1043 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1044 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1045 DisassembleMachO(Filename, O, SegName, SectName);
1048 if (SegName == "__TEXT" && SectName == "__info_plist") {
1052 if (SegName == "__OBJC" && SectName == "__protocol") {
1053 DumpProtocolSection(O, sect, sect_size, sect_addr);
1056 switch (section_type) {
1057 case MachO::S_REGULAR:
1058 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1060 case MachO::S_ZEROFILL:
1061 outs() << "zerofill section and has no contents in the file\n";
1063 case MachO::S_CSTRING_LITERALS:
1064 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1066 case MachO::S_4BYTE_LITERALS:
1067 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1069 case MachO::S_8BYTE_LITERALS:
1070 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1072 case MachO::S_16BYTE_LITERALS:
1073 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1075 case MachO::S_LITERAL_POINTERS:
1076 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1079 case MachO::S_MOD_INIT_FUNC_POINTERS:
1080 case MachO::S_MOD_TERM_FUNC_POINTERS:
1081 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1085 outs() << "Unknown section type ("
1086 << format("0x%08" PRIx32, section_type) << ")\n";
1087 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1091 if (section_type == MachO::S_ZEROFILL)
1092 outs() << "zerofill section and has no contents in the file\n";
1094 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1101 static void DumpInfoPlistSectionContents(StringRef Filename,
1102 MachOObjectFile *O) {
1103 for (const SectionRef &Section : O->sections()) {
1105 Section.getName(SectName);
1106 DataRefImpl Ref = Section.getRawDataRefImpl();
1107 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1108 if (SegName == "__TEXT" && SectName == "__info_plist") {
1109 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1111 Section.getContents(BytesStr);
1112 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1119 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1120 // and if it is and there is a list of architecture flags is specified then
1121 // check to make sure this Mach-O file is one of those architectures or all
1122 // architectures were specified. If not then an error is generated and this
1123 // routine returns false. Else it returns true.
1124 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1125 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1126 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1127 bool ArchFound = false;
1128 MachO::mach_header H;
1129 MachO::mach_header_64 H_64;
1131 if (MachO->is64Bit()) {
1132 H_64 = MachO->MachOObjectFile::getHeader64();
1133 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1135 H = MachO->MachOObjectFile::getHeader();
1136 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1139 for (i = 0; i < ArchFlags.size(); ++i) {
1140 if (ArchFlags[i] == T.getArchName())
1145 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1146 << "architecture: " + ArchFlags[i] + "\n";
1153 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1155 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1156 // archive member and or in a slice of a universal file. It prints the
1157 // the file name and header info and then processes it according to the
1158 // command line options.
1159 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1160 StringRef ArchiveMemberName = StringRef(),
1161 StringRef ArchitectureName = StringRef()) {
1162 // If we are doing some processing here on the Mach-O file print the header
1163 // info. And don't print it otherwise like in the case of printing the
1164 // UniversalHeaders or ArchiveHeaders.
1165 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
1166 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1167 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
1169 if (!ArchiveMemberName.empty())
1170 outs() << '(' << ArchiveMemberName << ')';
1171 if (!ArchitectureName.empty())
1172 outs() << " (architecture " << ArchitectureName << ")";
1177 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1178 if (IndirectSymbols)
1179 PrintIndirectSymbols(MachOOF, !NonVerbose);
1181 PrintDataInCodeTable(MachOOF, !NonVerbose);
1183 PrintLinkOptHints(MachOOF);
1185 PrintRelocations(MachOOF);
1187 PrintSectionHeaders(MachOOF);
1188 if (SectionContents)
1189 PrintSectionContents(MachOOF);
1190 if (FilterSections.size() != 0)
1191 DumpSectionContents(Filename, MachOOF, !NonVerbose);
1193 DumpInfoPlistSectionContents(Filename, MachOOF);
1195 PrintDylibs(MachOOF, false);
1197 PrintDylibs(MachOOF, true);
1199 PrintSymbolTable(MachOOF);
1201 printMachOUnwindInfo(MachOOF);
1203 printMachOFileHeader(MachOOF);
1205 printObjcMetaData(MachOOF, !NonVerbose);
1207 printExportsTrie(MachOOF);
1209 printRebaseTable(MachOOF);
1211 printBindTable(MachOOF);
1213 printLazyBindTable(MachOOF);
1215 printWeakBindTable(MachOOF);
1218 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1219 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1220 outs() << " cputype (" << cputype << ")\n";
1221 outs() << " cpusubtype (" << cpusubtype << ")\n";
1224 // printCPUType() helps print_fat_headers by printing the cputype and
1225 // pusubtype (symbolically for the one's it knows about).
1226 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1228 case MachO::CPU_TYPE_I386:
1229 switch (cpusubtype) {
1230 case MachO::CPU_SUBTYPE_I386_ALL:
1231 outs() << " cputype CPU_TYPE_I386\n";
1232 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1235 printUnknownCPUType(cputype, cpusubtype);
1239 case MachO::CPU_TYPE_X86_64:
1240 switch (cpusubtype) {
1241 case MachO::CPU_SUBTYPE_X86_64_ALL:
1242 outs() << " cputype CPU_TYPE_X86_64\n";
1243 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1245 case MachO::CPU_SUBTYPE_X86_64_H:
1246 outs() << " cputype CPU_TYPE_X86_64\n";
1247 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1250 printUnknownCPUType(cputype, cpusubtype);
1254 case MachO::CPU_TYPE_ARM:
1255 switch (cpusubtype) {
1256 case MachO::CPU_SUBTYPE_ARM_ALL:
1257 outs() << " cputype CPU_TYPE_ARM\n";
1258 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1260 case MachO::CPU_SUBTYPE_ARM_V4T:
1261 outs() << " cputype CPU_TYPE_ARM\n";
1262 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1264 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1265 outs() << " cputype CPU_TYPE_ARM\n";
1266 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1268 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1269 outs() << " cputype CPU_TYPE_ARM\n";
1270 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1272 case MachO::CPU_SUBTYPE_ARM_V6:
1273 outs() << " cputype CPU_TYPE_ARM\n";
1274 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1276 case MachO::CPU_SUBTYPE_ARM_V6M:
1277 outs() << " cputype CPU_TYPE_ARM\n";
1278 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1280 case MachO::CPU_SUBTYPE_ARM_V7:
1281 outs() << " cputype CPU_TYPE_ARM\n";
1282 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1284 case MachO::CPU_SUBTYPE_ARM_V7EM:
1285 outs() << " cputype CPU_TYPE_ARM\n";
1286 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1288 case MachO::CPU_SUBTYPE_ARM_V7K:
1289 outs() << " cputype CPU_TYPE_ARM\n";
1290 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1292 case MachO::CPU_SUBTYPE_ARM_V7M:
1293 outs() << " cputype CPU_TYPE_ARM\n";
1294 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1296 case MachO::CPU_SUBTYPE_ARM_V7S:
1297 outs() << " cputype CPU_TYPE_ARM\n";
1298 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1301 printUnknownCPUType(cputype, cpusubtype);
1305 case MachO::CPU_TYPE_ARM64:
1306 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1307 case MachO::CPU_SUBTYPE_ARM64_ALL:
1308 outs() << " cputype CPU_TYPE_ARM64\n";
1309 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1312 printUnknownCPUType(cputype, cpusubtype);
1317 printUnknownCPUType(cputype, cpusubtype);
1322 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1324 outs() << "Fat headers\n";
1326 outs() << "fat_magic FAT_MAGIC\n";
1328 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1330 uint32_t nfat_arch = UB->getNumberOfObjects();
1331 StringRef Buf = UB->getData();
1332 uint64_t size = Buf.size();
1333 uint64_t big_size = sizeof(struct MachO::fat_header) +
1334 nfat_arch * sizeof(struct MachO::fat_arch);
1335 outs() << "nfat_arch " << UB->getNumberOfObjects();
1337 outs() << " (malformed, contains zero architecture types)\n";
1338 else if (big_size > size)
1339 outs() << " (malformed, architectures past end of file)\n";
1343 for (uint32_t i = 0; i < nfat_arch; ++i) {
1344 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1345 uint32_t cputype = OFA.getCPUType();
1346 uint32_t cpusubtype = OFA.getCPUSubType();
1347 outs() << "architecture ";
1348 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1349 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1350 uint32_t other_cputype = other_OFA.getCPUType();
1351 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1352 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1353 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1354 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1355 outs() << "(illegal duplicate architecture) ";
1360 outs() << OFA.getArchTypeName() << "\n";
1361 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1363 outs() << i << "\n";
1364 outs() << " cputype " << cputype << "\n";
1365 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1369 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1370 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1372 outs() << " capabilities "
1373 << format("0x%" PRIx32,
1374 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1375 outs() << " offset " << OFA.getOffset();
1376 if (OFA.getOffset() > size)
1377 outs() << " (past end of file)";
1378 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1379 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1381 outs() << " size " << OFA.getSize();
1382 big_size = OFA.getOffset() + OFA.getSize();
1383 if (big_size > size)
1384 outs() << " (past end of file)";
1386 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1391 static void printArchiveChild(const Archive::Child &C, bool verbose,
1392 bool print_offset) {
1394 outs() << C.getChildOffset() << "\t";
1395 sys::fs::perms Mode = C.getAccessMode();
1397 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1398 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1400 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1401 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1402 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1403 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1404 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1405 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1406 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1407 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1408 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1410 outs() << format("0%o ", Mode);
1413 unsigned UID = C.getUID();
1414 outs() << format("%3d/", UID);
1415 unsigned GID = C.getGID();
1416 outs() << format("%-3d ", GID);
1417 ErrorOr<uint64_t> Size = C.getRawSize();
1418 if (std::error_code EC = Size.getError())
1419 report_fatal_error(EC.message());
1420 outs() << format("%5" PRId64, Size.get()) << " ";
1422 StringRef RawLastModified = C.getRawLastModified();
1425 if (RawLastModified.getAsInteger(10, Seconds))
1426 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1428 // Since cime(3) returns a 26 character string of the form:
1429 // "Sun Sep 16 01:03:52 1973\n\0"
1430 // just print 24 characters.
1432 outs() << format("%.24s ", ctime(&t));
1435 outs() << RawLastModified << " ";
1439 ErrorOr<StringRef> NameOrErr = C.getName();
1440 if (NameOrErr.getError()) {
1441 StringRef RawName = C.getRawName();
1442 outs() << RawName << "\n";
1444 StringRef Name = NameOrErr.get();
1445 outs() << Name << "\n";
1448 StringRef RawName = C.getRawName();
1449 outs() << RawName << "\n";
1453 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1454 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1456 if (std::error_code EC = I->getError())
1457 report_fatal_error(EC.message());
1458 const Archive::Child &C = **I;
1459 printArchiveChild(C, verbose, print_offset);
1463 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1464 // -arch flags selecting just those slices as specified by them and also parses
1465 // archive files. Then for each individual Mach-O file ProcessMachO() is
1466 // called to process the file based on the command line options.
1467 void llvm::ParseInputMachO(StringRef Filename) {
1468 // Check for -arch all and verifiy the -arch flags are valid.
1469 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1470 if (ArchFlags[i] == "all") {
1473 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1474 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1475 "'for the -arch option\n";
1481 // Attempt to open the binary.
1482 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1483 if (std::error_code EC = BinaryOrErr.getError()) {
1484 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
1487 Binary &Bin = *BinaryOrErr.get().getBinary();
1489 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1490 outs() << "Archive : " << Filename << "\n";
1492 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
1493 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1495 if (std::error_code EC = I->getError())
1496 report_error(Filename, EC);
1498 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1499 if (ChildOrErr.getError())
1501 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1502 if (!checkMachOAndArchFlags(O, Filename))
1504 ProcessMachO(Filename, O, O->getFileName());
1509 if (UniversalHeaders) {
1510 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1511 printMachOUniversalHeaders(UB, !NonVerbose);
1513 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1514 // If we have a list of architecture flags specified dump only those.
1515 if (!ArchAll && ArchFlags.size() != 0) {
1516 // Look for a slice in the universal binary that matches each ArchFlag.
1518 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1520 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1521 E = UB->end_objects();
1523 if (ArchFlags[i] == I->getArchTypeName()) {
1525 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1526 I->getAsObjectFile();
1527 std::string ArchitectureName = "";
1528 if (ArchFlags.size() > 1)
1529 ArchitectureName = I->getArchTypeName();
1531 ObjectFile &O = *ObjOrErr.get();
1532 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1533 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1534 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1535 I->getAsArchive()) {
1536 std::unique_ptr<Archive> &A = *AOrErr;
1537 outs() << "Archive : " << Filename;
1538 if (!ArchitectureName.empty())
1539 outs() << " (architecture " << ArchitectureName << ")";
1542 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1543 for (Archive::child_iterator AI = A->child_begin(),
1544 AE = A->child_end();
1546 if (std::error_code EC = AI->getError())
1547 report_error(Filename, EC);
1548 auto &C = AI->get();
1549 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1550 if (ChildOrErr.getError())
1552 if (MachOObjectFile *O =
1553 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1554 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1560 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1561 << "architecture: " + ArchFlags[i] + "\n";
1567 // No architecture flags were specified so if this contains a slice that
1568 // matches the host architecture dump only that.
1570 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1571 E = UB->end_objects();
1573 if (MachOObjectFile::getHostArch().getArchName() ==
1574 I->getArchTypeName()) {
1575 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1576 std::string ArchiveName;
1577 ArchiveName.clear();
1579 ObjectFile &O = *ObjOrErr.get();
1580 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1581 ProcessMachO(Filename, MachOOF);
1582 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1583 I->getAsArchive()) {
1584 std::unique_ptr<Archive> &A = *AOrErr;
1585 outs() << "Archive : " << Filename << "\n";
1587 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1588 for (Archive::child_iterator AI = A->child_begin(),
1589 AE = A->child_end();
1591 if (std::error_code EC = AI->getError())
1592 report_error(Filename, EC);
1593 auto &C = AI->get();
1594 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1595 if (ChildOrErr.getError())
1597 if (MachOObjectFile *O =
1598 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1599 ProcessMachO(Filename, O, O->getFileName());
1606 // Either all architectures have been specified or none have been specified
1607 // and this does not contain the host architecture so dump all the slices.
1608 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1609 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1610 E = UB->end_objects();
1612 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1613 std::string ArchitectureName = "";
1614 if (moreThanOneArch)
1615 ArchitectureName = I->getArchTypeName();
1617 ObjectFile &Obj = *ObjOrErr.get();
1618 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1619 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1620 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1621 std::unique_ptr<Archive> &A = *AOrErr;
1622 outs() << "Archive : " << Filename;
1623 if (!ArchitectureName.empty())
1624 outs() << " (architecture " << ArchitectureName << ")";
1627 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1628 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1630 if (std::error_code EC = AI->getError())
1631 report_error(Filename, EC);
1632 auto &C = AI->get();
1633 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1634 if (ChildOrErr.getError())
1636 if (MachOObjectFile *O =
1637 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1638 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1639 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1647 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1648 if (!checkMachOAndArchFlags(O, Filename))
1650 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1651 ProcessMachO(Filename, MachOOF);
1653 errs() << "llvm-objdump: '" << Filename << "': "
1654 << "Object is not a Mach-O file type.\n";
1656 errs() << "llvm-objdump: '" << Filename << "': "
1657 << "Unrecognized file type.\n";
1660 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1661 typedef std::vector<BindInfoEntry> BindTable;
1662 typedef BindTable::iterator bind_table_iterator;
1664 // The block of info used by the Symbolizer call backs.
1665 struct DisassembleInfo {
1669 SymbolAddressMap *AddrMap;
1670 std::vector<SectionRef> *Sections;
1671 const char *class_name;
1672 const char *selector_name;
1674 char *demangled_name;
1677 BindTable *bindtable;
1681 // SymbolizerGetOpInfo() is the operand information call back function.
1682 // This is called to get the symbolic information for operand(s) of an
1683 // instruction when it is being done. This routine does this from
1684 // the relocation information, symbol table, etc. That block of information
1685 // is a pointer to the struct DisassembleInfo that was passed when the
1686 // disassembler context was created and passed to back to here when
1687 // called back by the disassembler for instruction operands that could have
1688 // relocation information. The address of the instruction containing operand is
1689 // at the Pc parameter. The immediate value the operand has is passed in
1690 // op_info->Value and is at Offset past the start of the instruction and has a
1691 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1692 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1693 // names and addends of the symbolic expression to add for the operand. The
1694 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1695 // information is returned then this function returns 1 else it returns 0.
1696 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1697 uint64_t Size, int TagType, void *TagBuf) {
1698 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1699 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1700 uint64_t value = op_info->Value;
1702 // Make sure all fields returned are zero if we don't set them.
1703 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1704 op_info->Value = value;
1706 // If the TagType is not the value 1 which it code knows about or if no
1707 // verbose symbolic information is wanted then just return 0, indicating no
1708 // information is being returned.
1709 if (TagType != 1 || !info->verbose)
1712 unsigned int Arch = info->O->getArch();
1713 if (Arch == Triple::x86) {
1714 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1716 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1718 // Search the external relocation entries of a fully linked image
1719 // (if any) for an entry that matches this segment offset.
1720 // uint32_t seg_offset = (Pc + Offset);
1723 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1724 // for an entry for this section offset.
1725 uint32_t sect_addr = info->S.getAddress();
1726 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1727 bool reloc_found = false;
1729 MachO::any_relocation_info RE;
1730 bool isExtern = false;
1732 bool r_scattered = false;
1733 uint32_t r_value, pair_r_value, r_type;
1734 for (const RelocationRef &Reloc : info->S.relocations()) {
1735 uint64_t RelocOffset = Reloc.getOffset();
1736 if (RelocOffset == sect_offset) {
1737 Rel = Reloc.getRawDataRefImpl();
1738 RE = info->O->getRelocation(Rel);
1739 r_type = info->O->getAnyRelocationType(RE);
1740 r_scattered = info->O->isRelocationScattered(RE);
1742 r_value = info->O->getScatteredRelocationValue(RE);
1743 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1744 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1745 DataRefImpl RelNext = Rel;
1746 info->O->moveRelocationNext(RelNext);
1747 MachO::any_relocation_info RENext;
1748 RENext = info->O->getRelocation(RelNext);
1749 if (info->O->isRelocationScattered(RENext))
1750 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1755 isExtern = info->O->getPlainRelocationExternal(RE);
1757 symbol_iterator RelocSym = Reloc.getSymbol();
1765 if (reloc_found && isExtern) {
1766 ErrorOr<StringRef> SymName = Symbol.getName();
1767 if (std::error_code EC = SymName.getError())
1768 report_fatal_error(EC.message());
1769 const char *name = SymName->data();
1770 op_info->AddSymbol.Present = 1;
1771 op_info->AddSymbol.Name = name;
1772 // For i386 extern relocation entries the value in the instruction is
1773 // the offset from the symbol, and value is already set in op_info->Value.
1776 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1777 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1778 const char *add = GuessSymbolName(r_value, info->AddrMap);
1779 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1780 uint32_t offset = value - (r_value - pair_r_value);
1781 op_info->AddSymbol.Present = 1;
1783 op_info->AddSymbol.Name = add;
1785 op_info->AddSymbol.Value = r_value;
1786 op_info->SubtractSymbol.Present = 1;
1788 op_info->SubtractSymbol.Name = sub;
1790 op_info->SubtractSymbol.Value = pair_r_value;
1791 op_info->Value = offset;
1796 if (Arch == Triple::x86_64) {
1797 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1799 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1801 // Search the external relocation entries of a fully linked image
1802 // (if any) for an entry that matches this segment offset.
1803 // uint64_t seg_offset = (Pc + Offset);
1806 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1807 // for an entry for this section offset.
1808 uint64_t sect_addr = info->S.getAddress();
1809 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1810 bool reloc_found = false;
1812 MachO::any_relocation_info RE;
1813 bool isExtern = false;
1815 for (const RelocationRef &Reloc : info->S.relocations()) {
1816 uint64_t RelocOffset = Reloc.getOffset();
1817 if (RelocOffset == sect_offset) {
1818 Rel = Reloc.getRawDataRefImpl();
1819 RE = info->O->getRelocation(Rel);
1820 // NOTE: Scattered relocations don't exist on x86_64.
1821 isExtern = info->O->getPlainRelocationExternal(RE);
1823 symbol_iterator RelocSym = Reloc.getSymbol();
1830 if (reloc_found && isExtern) {
1831 // The Value passed in will be adjusted by the Pc if the instruction
1832 // adds the Pc. But for x86_64 external relocation entries the Value
1833 // is the offset from the external symbol.
1834 if (info->O->getAnyRelocationPCRel(RE))
1835 op_info->Value -= Pc + Offset + Size;
1836 ErrorOr<StringRef> SymName = Symbol.getName();
1837 if (std::error_code EC = SymName.getError())
1838 report_fatal_error(EC.message());
1839 const char *name = SymName->data();
1840 unsigned Type = info->O->getAnyRelocationType(RE);
1841 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1842 DataRefImpl RelNext = Rel;
1843 info->O->moveRelocationNext(RelNext);
1844 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1845 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1846 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1847 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1848 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1849 op_info->SubtractSymbol.Present = 1;
1850 op_info->SubtractSymbol.Name = name;
1851 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1852 Symbol = *RelocSymNext;
1853 ErrorOr<StringRef> SymNameNext = Symbol.getName();
1854 if (std::error_code EC = SymNameNext.getError())
1855 report_fatal_error(EC.message());
1856 name = SymNameNext->data();
1859 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1860 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1861 op_info->AddSymbol.Present = 1;
1862 op_info->AddSymbol.Name = name;
1867 if (Arch == Triple::arm) {
1868 if (Offset != 0 || (Size != 4 && Size != 2))
1870 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1872 // Search the external relocation entries of a fully linked image
1873 // (if any) for an entry that matches this segment offset.
1874 // uint32_t seg_offset = (Pc + Offset);
1877 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1878 // for an entry for this section offset.
1879 uint32_t sect_addr = info->S.getAddress();
1880 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1882 MachO::any_relocation_info RE;
1883 bool isExtern = false;
1885 bool r_scattered = false;
1886 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1888 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1889 [&](const RelocationRef &Reloc) {
1890 uint64_t RelocOffset = Reloc.getOffset();
1891 return RelocOffset == sect_offset;
1894 if (Reloc == info->S.relocations().end())
1897 Rel = Reloc->getRawDataRefImpl();
1898 RE = info->O->getRelocation(Rel);
1899 r_length = info->O->getAnyRelocationLength(RE);
1900 r_scattered = info->O->isRelocationScattered(RE);
1902 r_value = info->O->getScatteredRelocationValue(RE);
1903 r_type = info->O->getScatteredRelocationType(RE);
1905 r_type = info->O->getAnyRelocationType(RE);
1906 isExtern = info->O->getPlainRelocationExternal(RE);
1908 symbol_iterator RelocSym = Reloc->getSymbol();
1912 if (r_type == MachO::ARM_RELOC_HALF ||
1913 r_type == MachO::ARM_RELOC_SECTDIFF ||
1914 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1915 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1916 DataRefImpl RelNext = Rel;
1917 info->O->moveRelocationNext(RelNext);
1918 MachO::any_relocation_info RENext;
1919 RENext = info->O->getRelocation(RelNext);
1920 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1921 if (info->O->isRelocationScattered(RENext))
1922 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1926 ErrorOr<StringRef> SymName = Symbol.getName();
1927 if (std::error_code EC = SymName.getError())
1928 report_fatal_error(EC.message());
1929 const char *name = SymName->data();
1930 op_info->AddSymbol.Present = 1;
1931 op_info->AddSymbol.Name = name;
1933 case MachO::ARM_RELOC_HALF:
1934 if ((r_length & 0x1) == 1) {
1935 op_info->Value = value << 16 | other_half;
1936 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1938 op_info->Value = other_half << 16 | value;
1939 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1947 // If we have a branch that is not an external relocation entry then
1948 // return 0 so the code in tryAddingSymbolicOperand() can use the
1949 // SymbolLookUp call back with the branch target address to look up the
1950 // symbol and possiblity add an annotation for a symbol stub.
1951 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1952 r_type == MachO::ARM_THUMB_RELOC_BR22))
1955 uint32_t offset = 0;
1956 if (r_type == MachO::ARM_RELOC_HALF ||
1957 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1958 if ((r_length & 0x1) == 1)
1959 value = value << 16 | other_half;
1961 value = other_half << 16 | value;
1963 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1964 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1965 offset = value - r_value;
1969 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1970 if ((r_length & 0x1) == 1)
1971 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1973 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1974 const char *add = GuessSymbolName(r_value, info->AddrMap);
1975 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1976 int32_t offset = value - (r_value - pair_r_value);
1977 op_info->AddSymbol.Present = 1;
1979 op_info->AddSymbol.Name = add;
1981 op_info->AddSymbol.Value = r_value;
1982 op_info->SubtractSymbol.Present = 1;
1984 op_info->SubtractSymbol.Name = sub;
1986 op_info->SubtractSymbol.Value = pair_r_value;
1987 op_info->Value = offset;
1991 op_info->AddSymbol.Present = 1;
1992 op_info->Value = offset;
1993 if (r_type == MachO::ARM_RELOC_HALF) {
1994 if ((r_length & 0x1) == 1)
1995 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1997 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1999 const char *add = GuessSymbolName(value, info->AddrMap);
2000 if (add != nullptr) {
2001 op_info->AddSymbol.Name = add;
2004 op_info->AddSymbol.Value = value;
2007 if (Arch == Triple::aarch64) {
2008 if (Offset != 0 || Size != 4)
2010 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2012 // Search the external relocation entries of a fully linked image
2013 // (if any) for an entry that matches this segment offset.
2014 // uint64_t seg_offset = (Pc + Offset);
2017 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2018 // for an entry for this section offset.
2019 uint64_t sect_addr = info->S.getAddress();
2020 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2022 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2023 [&](const RelocationRef &Reloc) {
2024 uint64_t RelocOffset = Reloc.getOffset();
2025 return RelocOffset == sect_offset;
2028 if (Reloc == info->S.relocations().end())
2031 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2032 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2033 uint32_t r_type = info->O->getAnyRelocationType(RE);
2034 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2035 DataRefImpl RelNext = Rel;
2036 info->O->moveRelocationNext(RelNext);
2037 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2039 value = info->O->getPlainRelocationSymbolNum(RENext);
2040 op_info->Value = value;
2043 // NOTE: Scattered relocations don't exist on arm64.
2044 if (!info->O->getPlainRelocationExternal(RE))
2046 ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
2047 if (std::error_code EC = SymName.getError())
2048 report_fatal_error(EC.message());
2049 const char *name = SymName->data();
2050 op_info->AddSymbol.Present = 1;
2051 op_info->AddSymbol.Name = name;
2054 case MachO::ARM64_RELOC_PAGE21:
2056 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2058 case MachO::ARM64_RELOC_PAGEOFF12:
2060 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2062 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2064 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2066 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2068 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2070 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2071 /* @tvlppage is not implemented in llvm-mc */
2072 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2074 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2075 /* @tvlppageoff is not implemented in llvm-mc */
2076 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2079 case MachO::ARM64_RELOC_BRANCH26:
2080 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2088 // GuessCstringPointer is passed the address of what might be a pointer to a
2089 // literal string in a cstring section. If that address is in a cstring section
2090 // it returns a pointer to that string. Else it returns nullptr.
2091 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2092 struct DisassembleInfo *info) {
2093 for (const auto &Load : info->O->load_commands()) {
2094 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2095 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2096 for (unsigned J = 0; J < Seg.nsects; ++J) {
2097 MachO::section_64 Sec = info->O->getSection64(Load, J);
2098 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2099 if (section_type == MachO::S_CSTRING_LITERALS &&
2100 ReferenceValue >= Sec.addr &&
2101 ReferenceValue < Sec.addr + Sec.size) {
2102 uint64_t sect_offset = ReferenceValue - Sec.addr;
2103 uint64_t object_offset = Sec.offset + sect_offset;
2104 StringRef MachOContents = info->O->getData();
2105 uint64_t object_size = MachOContents.size();
2106 const char *object_addr = (const char *)MachOContents.data();
2107 if (object_offset < object_size) {
2108 const char *name = object_addr + object_offset;
2115 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2116 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2117 for (unsigned J = 0; J < Seg.nsects; ++J) {
2118 MachO::section Sec = info->O->getSection(Load, J);
2119 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2120 if (section_type == MachO::S_CSTRING_LITERALS &&
2121 ReferenceValue >= Sec.addr &&
2122 ReferenceValue < Sec.addr + Sec.size) {
2123 uint64_t sect_offset = ReferenceValue - Sec.addr;
2124 uint64_t object_offset = Sec.offset + sect_offset;
2125 StringRef MachOContents = info->O->getData();
2126 uint64_t object_size = MachOContents.size();
2127 const char *object_addr = (const char *)MachOContents.data();
2128 if (object_offset < object_size) {
2129 const char *name = object_addr + object_offset;
2141 // GuessIndirectSymbol returns the name of the indirect symbol for the
2142 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2143 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2144 // symbol name being referenced by the stub or pointer.
2145 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2146 struct DisassembleInfo *info) {
2147 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2148 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2149 for (const auto &Load : info->O->load_commands()) {
2150 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2151 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2152 for (unsigned J = 0; J < Seg.nsects; ++J) {
2153 MachO::section_64 Sec = info->O->getSection64(Load, J);
2154 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2155 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2156 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2157 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2158 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2159 section_type == MachO::S_SYMBOL_STUBS) &&
2160 ReferenceValue >= Sec.addr &&
2161 ReferenceValue < Sec.addr + Sec.size) {
2163 if (section_type == MachO::S_SYMBOL_STUBS)
2164 stride = Sec.reserved2;
2169 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2170 if (index < Dysymtab.nindirectsyms) {
2171 uint32_t indirect_symbol =
2172 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2173 if (indirect_symbol < Symtab.nsyms) {
2174 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2175 SymbolRef Symbol = *Sym;
2176 ErrorOr<StringRef> SymName = Symbol.getName();
2177 if (std::error_code EC = SymName.getError())
2178 report_fatal_error(EC.message());
2179 const char *name = SymName->data();
2185 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2186 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2187 for (unsigned J = 0; J < Seg.nsects; ++J) {
2188 MachO::section Sec = info->O->getSection(Load, J);
2189 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2190 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2191 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2192 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2193 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2194 section_type == MachO::S_SYMBOL_STUBS) &&
2195 ReferenceValue >= Sec.addr &&
2196 ReferenceValue < Sec.addr + Sec.size) {
2198 if (section_type == MachO::S_SYMBOL_STUBS)
2199 stride = Sec.reserved2;
2204 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2205 if (index < Dysymtab.nindirectsyms) {
2206 uint32_t indirect_symbol =
2207 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2208 if (indirect_symbol < Symtab.nsyms) {
2209 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2210 SymbolRef Symbol = *Sym;
2211 ErrorOr<StringRef> SymName = Symbol.getName();
2212 if (std::error_code EC = SymName.getError())
2213 report_fatal_error(EC.message());
2214 const char *name = SymName->data();
2225 // method_reference() is called passing it the ReferenceName that might be
2226 // a reference it to an Objective-C method call. If so then it allocates and
2227 // assembles a method call string with the values last seen and saved in
2228 // the DisassembleInfo's class_name and selector_name fields. This is saved
2229 // into the method field of the info and any previous string is free'ed.
2230 // Then the class_name field in the info is set to nullptr. The method call
2231 // string is set into ReferenceName and ReferenceType is set to
2232 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2233 // then both ReferenceType and ReferenceName are left unchanged.
2234 static void method_reference(struct DisassembleInfo *info,
2235 uint64_t *ReferenceType,
2236 const char **ReferenceName) {
2237 unsigned int Arch = info->O->getArch();
2238 if (*ReferenceName != nullptr) {
2239 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2240 if (info->selector_name != nullptr) {
2241 if (info->method != nullptr)
2243 if (info->class_name != nullptr) {
2244 info->method = (char *)malloc(5 + strlen(info->class_name) +
2245 strlen(info->selector_name));
2246 if (info->method != nullptr) {
2247 strcpy(info->method, "+[");
2248 strcat(info->method, info->class_name);
2249 strcat(info->method, " ");
2250 strcat(info->method, info->selector_name);
2251 strcat(info->method, "]");
2252 *ReferenceName = info->method;
2253 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2256 info->method = (char *)malloc(9 + strlen(info->selector_name));
2257 if (info->method != nullptr) {
2258 if (Arch == Triple::x86_64)
2259 strcpy(info->method, "-[%rdi ");
2260 else if (Arch == Triple::aarch64)
2261 strcpy(info->method, "-[x0 ");
2263 strcpy(info->method, "-[r? ");
2264 strcat(info->method, info->selector_name);
2265 strcat(info->method, "]");
2266 *ReferenceName = info->method;
2267 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2270 info->class_name = nullptr;
2272 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2273 if (info->selector_name != nullptr) {
2274 if (info->method != nullptr)
2276 info->method = (char *)malloc(17 + strlen(info->selector_name));
2277 if (info->method != nullptr) {
2278 if (Arch == Triple::x86_64)
2279 strcpy(info->method, "-[[%rdi super] ");
2280 else if (Arch == Triple::aarch64)
2281 strcpy(info->method, "-[[x0 super] ");
2283 strcpy(info->method, "-[[r? super] ");
2284 strcat(info->method, info->selector_name);
2285 strcat(info->method, "]");
2286 *ReferenceName = info->method;
2287 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2289 info->class_name = nullptr;
2295 // GuessPointerPointer() is passed the address of what might be a pointer to
2296 // a reference to an Objective-C class, selector, message ref or cfstring.
2297 // If so the value of the pointer is returned and one of the booleans are set
2298 // to true. If not zero is returned and all the booleans are set to false.
2299 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2300 struct DisassembleInfo *info,
2301 bool &classref, bool &selref, bool &msgref,
2307 for (const auto &Load : info->O->load_commands()) {
2308 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2309 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2310 for (unsigned J = 0; J < Seg.nsects; ++J) {
2311 MachO::section_64 Sec = info->O->getSection64(Load, J);
2312 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2313 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2314 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2315 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2316 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2317 ReferenceValue >= Sec.addr &&
2318 ReferenceValue < Sec.addr + Sec.size) {
2319 uint64_t sect_offset = ReferenceValue - Sec.addr;
2320 uint64_t object_offset = Sec.offset + sect_offset;
2321 StringRef MachOContents = info->O->getData();
2322 uint64_t object_size = MachOContents.size();
2323 const char *object_addr = (const char *)MachOContents.data();
2324 if (object_offset < object_size) {
2325 uint64_t pointer_value;
2326 memcpy(&pointer_value, object_addr + object_offset,
2328 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2329 sys::swapByteOrder(pointer_value);
2330 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2332 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2333 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2335 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2336 ReferenceValue + 8 < Sec.addr + Sec.size) {
2338 memcpy(&pointer_value, object_addr + object_offset + 8,
2340 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2341 sys::swapByteOrder(pointer_value);
2342 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2344 return pointer_value;
2351 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2356 // get_pointer_64 returns a pointer to the bytes in the object file at the
2357 // Address from a section in the Mach-O file. And indirectly returns the
2358 // offset into the section, number of bytes left in the section past the offset
2359 // and which section is was being referenced. If the Address is not in a
2360 // section nullptr is returned.
2361 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2362 uint32_t &left, SectionRef &S,
2363 DisassembleInfo *info,
2364 bool objc_only = false) {
2368 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2369 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2370 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2375 ((*(info->Sections))[SectIdx]).getName(SectName);
2376 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2377 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2378 if (SegName != "__OBJC" && SectName != "__cstring")
2381 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2382 S = (*(info->Sections))[SectIdx];
2383 offset = Address - SectAddress;
2384 left = SectSize - offset;
2385 StringRef SectContents;
2386 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2387 return SectContents.data() + offset;
2393 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2394 uint32_t &left, SectionRef &S,
2395 DisassembleInfo *info,
2396 bool objc_only = false) {
2397 return get_pointer_64(Address, offset, left, S, info, objc_only);
2400 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2401 // the symbol indirectly through n_value. Based on the relocation information
2402 // for the specified section offset in the specified section reference.
2403 // If no relocation information is found and a non-zero ReferenceValue for the
2404 // symbol is passed, look up that address in the info's AddrMap.
2405 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2406 DisassembleInfo *info, uint64_t &n_value,
2407 uint64_t ReferenceValue = 0) {
2412 // See if there is an external relocation entry at the sect_offset.
2413 bool reloc_found = false;
2415 MachO::any_relocation_info RE;
2416 bool isExtern = false;
2418 for (const RelocationRef &Reloc : S.relocations()) {
2419 uint64_t RelocOffset = Reloc.getOffset();
2420 if (RelocOffset == sect_offset) {
2421 Rel = Reloc.getRawDataRefImpl();
2422 RE = info->O->getRelocation(Rel);
2423 if (info->O->isRelocationScattered(RE))
2425 isExtern = info->O->getPlainRelocationExternal(RE);
2427 symbol_iterator RelocSym = Reloc.getSymbol();
2434 // If there is an external relocation entry for a symbol in this section
2435 // at this section_offset then use that symbol's value for the n_value
2436 // and return its name.
2437 const char *SymbolName = nullptr;
2438 if (reloc_found && isExtern) {
2439 n_value = Symbol.getValue();
2440 ErrorOr<StringRef> NameOrError = Symbol.getName();
2441 if (std::error_code EC = NameOrError.getError())
2442 report_fatal_error(EC.message());
2443 StringRef Name = *NameOrError;
2444 if (!Name.empty()) {
2445 SymbolName = Name.data();
2450 // TODO: For fully linked images, look through the external relocation
2451 // entries off the dynamic symtab command. For these the r_offset is from the
2452 // start of the first writeable segment in the Mach-O file. So the offset
2453 // to this section from that segment is passed to this routine by the caller,
2454 // as the database_offset. Which is the difference of the section's starting
2455 // address and the first writable segment.
2457 // NOTE: need add passing the database_offset to this routine.
2459 // We did not find an external relocation entry so look up the ReferenceValue
2460 // as an address of a symbol and if found return that symbol's name.
2461 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2466 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2467 DisassembleInfo *info,
2468 uint32_t ReferenceValue) {
2470 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2473 // These are structs in the Objective-C meta data and read to produce the
2474 // comments for disassembly. While these are part of the ABI they are no
2475 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2477 // The cfstring object in a 64-bit Mach-O file.
2478 struct cfstring64_t {
2479 uint64_t isa; // class64_t * (64-bit pointer)
2480 uint64_t flags; // flag bits
2481 uint64_t characters; // char * (64-bit pointer)
2482 uint64_t length; // number of non-NULL characters in above
2485 // The class object in a 64-bit Mach-O file.
2487 uint64_t isa; // class64_t * (64-bit pointer)
2488 uint64_t superclass; // class64_t * (64-bit pointer)
2489 uint64_t cache; // Cache (64-bit pointer)
2490 uint64_t vtable; // IMP * (64-bit pointer)
2491 uint64_t data; // class_ro64_t * (64-bit pointer)
2495 uint32_t isa; /* class32_t * (32-bit pointer) */
2496 uint32_t superclass; /* class32_t * (32-bit pointer) */
2497 uint32_t cache; /* Cache (32-bit pointer) */
2498 uint32_t vtable; /* IMP * (32-bit pointer) */
2499 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2502 struct class_ro64_t {
2504 uint32_t instanceStart;
2505 uint32_t instanceSize;
2507 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2508 uint64_t name; // const char * (64-bit pointer)
2509 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2510 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2511 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2512 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2513 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2516 struct class_ro32_t {
2518 uint32_t instanceStart;
2519 uint32_t instanceSize;
2520 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2521 uint32_t name; /* const char * (32-bit pointer) */
2522 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2523 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2524 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2525 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2526 uint32_t baseProperties; /* const struct objc_property_list *
2530 /* Values for class_ro{64,32}_t->flags */
2531 #define RO_META (1 << 0)
2532 #define RO_ROOT (1 << 1)
2533 #define RO_HAS_CXX_STRUCTORS (1 << 2)
2535 struct method_list64_t {
2538 /* struct method64_t first; These structures follow inline */
2541 struct method_list32_t {
2544 /* struct method32_t first; These structures follow inline */
2548 uint64_t name; /* SEL (64-bit pointer) */
2549 uint64_t types; /* const char * (64-bit pointer) */
2550 uint64_t imp; /* IMP (64-bit pointer) */
2554 uint32_t name; /* SEL (32-bit pointer) */
2555 uint32_t types; /* const char * (32-bit pointer) */
2556 uint32_t imp; /* IMP (32-bit pointer) */
2559 struct protocol_list64_t {
2560 uint64_t count; /* uintptr_t (a 64-bit value) */
2561 /* struct protocol64_t * list[0]; These pointers follow inline */
2564 struct protocol_list32_t {
2565 uint32_t count; /* uintptr_t (a 32-bit value) */
2566 /* struct protocol32_t * list[0]; These pointers follow inline */
2569 struct protocol64_t {
2570 uint64_t isa; /* id * (64-bit pointer) */
2571 uint64_t name; /* const char * (64-bit pointer) */
2572 uint64_t protocols; /* struct protocol_list64_t *
2574 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2575 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2576 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2577 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2578 uint64_t instanceProperties; /* struct objc_property_list *
2582 struct protocol32_t {
2583 uint32_t isa; /* id * (32-bit pointer) */
2584 uint32_t name; /* const char * (32-bit pointer) */
2585 uint32_t protocols; /* struct protocol_list_t *
2587 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2588 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2589 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2590 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2591 uint32_t instanceProperties; /* struct objc_property_list *
2595 struct ivar_list64_t {
2598 /* struct ivar64_t first; These structures follow inline */
2601 struct ivar_list32_t {
2604 /* struct ivar32_t first; These structures follow inline */
2608 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2609 uint64_t name; /* const char * (64-bit pointer) */
2610 uint64_t type; /* const char * (64-bit pointer) */
2616 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2617 uint32_t name; /* const char * (32-bit pointer) */
2618 uint32_t type; /* const char * (32-bit pointer) */
2623 struct objc_property_list64 {
2626 /* struct objc_property64 first; These structures follow inline */
2629 struct objc_property_list32 {
2632 /* struct objc_property32 first; These structures follow inline */
2635 struct objc_property64 {
2636 uint64_t name; /* const char * (64-bit pointer) */
2637 uint64_t attributes; /* const char * (64-bit pointer) */
2640 struct objc_property32 {
2641 uint32_t name; /* const char * (32-bit pointer) */
2642 uint32_t attributes; /* const char * (32-bit pointer) */
2645 struct category64_t {
2646 uint64_t name; /* const char * (64-bit pointer) */
2647 uint64_t cls; /* struct class_t * (64-bit pointer) */
2648 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2649 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2650 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2651 uint64_t instanceProperties; /* struct objc_property_list *
2655 struct category32_t {
2656 uint32_t name; /* const char * (32-bit pointer) */
2657 uint32_t cls; /* struct class_t * (32-bit pointer) */
2658 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2659 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2660 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2661 uint32_t instanceProperties; /* struct objc_property_list *
2665 struct objc_image_info64 {
2669 struct objc_image_info32 {
2673 struct imageInfo_t {
2677 /* masks for objc_image_info.flags */
2678 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2679 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2681 struct message_ref64 {
2682 uint64_t imp; /* IMP (64-bit pointer) */
2683 uint64_t sel; /* SEL (64-bit pointer) */
2686 struct message_ref32 {
2687 uint32_t imp; /* IMP (32-bit pointer) */
2688 uint32_t sel; /* SEL (32-bit pointer) */
2691 // Objective-C 1 (32-bit only) meta data structs.
2693 struct objc_module_t {
2696 uint32_t name; /* char * (32-bit pointer) */
2697 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2700 struct objc_symtab_t {
2701 uint32_t sel_ref_cnt;
2702 uint32_t refs; /* SEL * (32-bit pointer) */
2703 uint16_t cls_def_cnt;
2704 uint16_t cat_def_cnt;
2705 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2708 struct objc_class_t {
2709 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2710 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2711 uint32_t name; /* const char * (32-bit pointer) */
2714 int32_t instance_size;
2715 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2716 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2717 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2718 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2721 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2722 // class is not a metaclass
2723 #define CLS_CLASS 0x1
2724 // class is a metaclass
2725 #define CLS_META 0x2
2727 struct objc_category_t {
2728 uint32_t category_name; /* char * (32-bit pointer) */
2729 uint32_t class_name; /* char * (32-bit pointer) */
2730 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2731 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2732 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2735 struct objc_ivar_t {
2736 uint32_t ivar_name; /* char * (32-bit pointer) */
2737 uint32_t ivar_type; /* char * (32-bit pointer) */
2738 int32_t ivar_offset;
2741 struct objc_ivar_list_t {
2743 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2746 struct objc_method_list_t {
2747 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2748 int32_t method_count;
2749 // struct objc_method_t method_list[1]; /* variable length structure */
2752 struct objc_method_t {
2753 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2754 uint32_t method_types; /* char * (32-bit pointer) */
2755 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2759 struct objc_protocol_list_t {
2760 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2762 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2763 // (32-bit pointer) */
2766 struct objc_protocol_t {
2767 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2768 uint32_t protocol_name; /* char * (32-bit pointer) */
2769 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2770 uint32_t instance_methods; /* struct objc_method_description_list *
2772 uint32_t class_methods; /* struct objc_method_description_list *
2776 struct objc_method_description_list_t {
2778 // struct objc_method_description_t list[1];
2781 struct objc_method_description_t {
2782 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2783 uint32_t types; /* char * (32-bit pointer) */
2786 inline void swapStruct(struct cfstring64_t &cfs) {
2787 sys::swapByteOrder(cfs.isa);
2788 sys::swapByteOrder(cfs.flags);
2789 sys::swapByteOrder(cfs.characters);
2790 sys::swapByteOrder(cfs.length);
2793 inline void swapStruct(struct class64_t &c) {
2794 sys::swapByteOrder(c.isa);
2795 sys::swapByteOrder(c.superclass);
2796 sys::swapByteOrder(c.cache);
2797 sys::swapByteOrder(c.vtable);
2798 sys::swapByteOrder(c.data);
2801 inline void swapStruct(struct class32_t &c) {
2802 sys::swapByteOrder(c.isa);
2803 sys::swapByteOrder(c.superclass);
2804 sys::swapByteOrder(c.cache);
2805 sys::swapByteOrder(c.vtable);
2806 sys::swapByteOrder(c.data);
2809 inline void swapStruct(struct class_ro64_t &cro) {
2810 sys::swapByteOrder(cro.flags);
2811 sys::swapByteOrder(cro.instanceStart);
2812 sys::swapByteOrder(cro.instanceSize);
2813 sys::swapByteOrder(cro.reserved);
2814 sys::swapByteOrder(cro.ivarLayout);
2815 sys::swapByteOrder(cro.name);
2816 sys::swapByteOrder(cro.baseMethods);
2817 sys::swapByteOrder(cro.baseProtocols);
2818 sys::swapByteOrder(cro.ivars);
2819 sys::swapByteOrder(cro.weakIvarLayout);
2820 sys::swapByteOrder(cro.baseProperties);
2823 inline void swapStruct(struct class_ro32_t &cro) {
2824 sys::swapByteOrder(cro.flags);
2825 sys::swapByteOrder(cro.instanceStart);
2826 sys::swapByteOrder(cro.instanceSize);
2827 sys::swapByteOrder(cro.ivarLayout);
2828 sys::swapByteOrder(cro.name);
2829 sys::swapByteOrder(cro.baseMethods);
2830 sys::swapByteOrder(cro.baseProtocols);
2831 sys::swapByteOrder(cro.ivars);
2832 sys::swapByteOrder(cro.weakIvarLayout);
2833 sys::swapByteOrder(cro.baseProperties);
2836 inline void swapStruct(struct method_list64_t &ml) {
2837 sys::swapByteOrder(ml.entsize);
2838 sys::swapByteOrder(ml.count);
2841 inline void swapStruct(struct method_list32_t &ml) {
2842 sys::swapByteOrder(ml.entsize);
2843 sys::swapByteOrder(ml.count);
2846 inline void swapStruct(struct method64_t &m) {
2847 sys::swapByteOrder(m.name);
2848 sys::swapByteOrder(m.types);
2849 sys::swapByteOrder(m.imp);
2852 inline void swapStruct(struct method32_t &m) {
2853 sys::swapByteOrder(m.name);
2854 sys::swapByteOrder(m.types);
2855 sys::swapByteOrder(m.imp);
2858 inline void swapStruct(struct protocol_list64_t &pl) {
2859 sys::swapByteOrder(pl.count);
2862 inline void swapStruct(struct protocol_list32_t &pl) {
2863 sys::swapByteOrder(pl.count);
2866 inline void swapStruct(struct protocol64_t &p) {
2867 sys::swapByteOrder(p.isa);
2868 sys::swapByteOrder(p.name);
2869 sys::swapByteOrder(p.protocols);
2870 sys::swapByteOrder(p.instanceMethods);
2871 sys::swapByteOrder(p.classMethods);
2872 sys::swapByteOrder(p.optionalInstanceMethods);
2873 sys::swapByteOrder(p.optionalClassMethods);
2874 sys::swapByteOrder(p.instanceProperties);
2877 inline void swapStruct(struct protocol32_t &p) {
2878 sys::swapByteOrder(p.isa);
2879 sys::swapByteOrder(p.name);
2880 sys::swapByteOrder(p.protocols);
2881 sys::swapByteOrder(p.instanceMethods);
2882 sys::swapByteOrder(p.classMethods);
2883 sys::swapByteOrder(p.optionalInstanceMethods);
2884 sys::swapByteOrder(p.optionalClassMethods);
2885 sys::swapByteOrder(p.instanceProperties);
2888 inline void swapStruct(struct ivar_list64_t &il) {
2889 sys::swapByteOrder(il.entsize);
2890 sys::swapByteOrder(il.count);
2893 inline void swapStruct(struct ivar_list32_t &il) {
2894 sys::swapByteOrder(il.entsize);
2895 sys::swapByteOrder(il.count);
2898 inline void swapStruct(struct ivar64_t &i) {
2899 sys::swapByteOrder(i.offset);
2900 sys::swapByteOrder(i.name);
2901 sys::swapByteOrder(i.type);
2902 sys::swapByteOrder(i.alignment);
2903 sys::swapByteOrder(i.size);
2906 inline void swapStruct(struct ivar32_t &i) {
2907 sys::swapByteOrder(i.offset);
2908 sys::swapByteOrder(i.name);
2909 sys::swapByteOrder(i.type);
2910 sys::swapByteOrder(i.alignment);
2911 sys::swapByteOrder(i.size);
2914 inline void swapStruct(struct objc_property_list64 &pl) {
2915 sys::swapByteOrder(pl.entsize);
2916 sys::swapByteOrder(pl.count);
2919 inline void swapStruct(struct objc_property_list32 &pl) {
2920 sys::swapByteOrder(pl.entsize);
2921 sys::swapByteOrder(pl.count);
2924 inline void swapStruct(struct objc_property64 &op) {
2925 sys::swapByteOrder(op.name);
2926 sys::swapByteOrder(op.attributes);
2929 inline void swapStruct(struct objc_property32 &op) {
2930 sys::swapByteOrder(op.name);
2931 sys::swapByteOrder(op.attributes);
2934 inline void swapStruct(struct category64_t &c) {
2935 sys::swapByteOrder(c.name);
2936 sys::swapByteOrder(c.cls);
2937 sys::swapByteOrder(c.instanceMethods);
2938 sys::swapByteOrder(c.classMethods);
2939 sys::swapByteOrder(c.protocols);
2940 sys::swapByteOrder(c.instanceProperties);
2943 inline void swapStruct(struct category32_t &c) {
2944 sys::swapByteOrder(c.name);
2945 sys::swapByteOrder(c.cls);
2946 sys::swapByteOrder(c.instanceMethods);
2947 sys::swapByteOrder(c.classMethods);
2948 sys::swapByteOrder(c.protocols);
2949 sys::swapByteOrder(c.instanceProperties);
2952 inline void swapStruct(struct objc_image_info64 &o) {
2953 sys::swapByteOrder(o.version);
2954 sys::swapByteOrder(o.flags);
2957 inline void swapStruct(struct objc_image_info32 &o) {
2958 sys::swapByteOrder(o.version);
2959 sys::swapByteOrder(o.flags);
2962 inline void swapStruct(struct imageInfo_t &o) {
2963 sys::swapByteOrder(o.version);
2964 sys::swapByteOrder(o.flags);
2967 inline void swapStruct(struct message_ref64 &mr) {
2968 sys::swapByteOrder(mr.imp);
2969 sys::swapByteOrder(mr.sel);
2972 inline void swapStruct(struct message_ref32 &mr) {
2973 sys::swapByteOrder(mr.imp);
2974 sys::swapByteOrder(mr.sel);
2977 inline void swapStruct(struct objc_module_t &module) {
2978 sys::swapByteOrder(module.version);
2979 sys::swapByteOrder(module.size);
2980 sys::swapByteOrder(module.name);
2981 sys::swapByteOrder(module.symtab);
2984 inline void swapStruct(struct objc_symtab_t &symtab) {
2985 sys::swapByteOrder(symtab.sel_ref_cnt);
2986 sys::swapByteOrder(symtab.refs);
2987 sys::swapByteOrder(symtab.cls_def_cnt);
2988 sys::swapByteOrder(symtab.cat_def_cnt);
2991 inline void swapStruct(struct objc_class_t &objc_class) {
2992 sys::swapByteOrder(objc_class.isa);
2993 sys::swapByteOrder(objc_class.super_class);
2994 sys::swapByteOrder(objc_class.name);
2995 sys::swapByteOrder(objc_class.version);
2996 sys::swapByteOrder(objc_class.info);
2997 sys::swapByteOrder(objc_class.instance_size);
2998 sys::swapByteOrder(objc_class.ivars);
2999 sys::swapByteOrder(objc_class.methodLists);
3000 sys::swapByteOrder(objc_class.cache);
3001 sys::swapByteOrder(objc_class.protocols);
3004 inline void swapStruct(struct objc_category_t &objc_category) {
3005 sys::swapByteOrder(objc_category.category_name);
3006 sys::swapByteOrder(objc_category.class_name);
3007 sys::swapByteOrder(objc_category.instance_methods);
3008 sys::swapByteOrder(objc_category.class_methods);
3009 sys::swapByteOrder(objc_category.protocols);
3012 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3013 sys::swapByteOrder(objc_ivar_list.ivar_count);
3016 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3017 sys::swapByteOrder(objc_ivar.ivar_name);
3018 sys::swapByteOrder(objc_ivar.ivar_type);
3019 sys::swapByteOrder(objc_ivar.ivar_offset);
3022 inline void swapStruct(struct objc_method_list_t &method_list) {
3023 sys::swapByteOrder(method_list.obsolete);
3024 sys::swapByteOrder(method_list.method_count);
3027 inline void swapStruct(struct objc_method_t &method) {
3028 sys::swapByteOrder(method.method_name);
3029 sys::swapByteOrder(method.method_types);
3030 sys::swapByteOrder(method.method_imp);
3033 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3034 sys::swapByteOrder(protocol_list.next);
3035 sys::swapByteOrder(protocol_list.count);
3038 inline void swapStruct(struct objc_protocol_t &protocol) {
3039 sys::swapByteOrder(protocol.isa);
3040 sys::swapByteOrder(protocol.protocol_name);
3041 sys::swapByteOrder(protocol.protocol_list);
3042 sys::swapByteOrder(protocol.instance_methods);
3043 sys::swapByteOrder(protocol.class_methods);
3046 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3047 sys::swapByteOrder(mdl.count);
3050 inline void swapStruct(struct objc_method_description_t &md) {
3051 sys::swapByteOrder(md.name);
3052 sys::swapByteOrder(md.types);
3055 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3056 struct DisassembleInfo *info);
3058 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3059 // to an Objective-C class and returns the class name. It is also passed the
3060 // address of the pointer, so when the pointer is zero as it can be in an .o
3061 // file, that is used to look for an external relocation entry with a symbol
3063 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3064 uint64_t ReferenceValue,
3065 struct DisassembleInfo *info) {
3067 uint32_t offset, left;
3070 // The pointer_value can be 0 in an object file and have a relocation
3071 // entry for the class symbol at the ReferenceValue (the address of the
3073 if (pointer_value == 0) {
3074 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3075 if (r == nullptr || left < sizeof(uint64_t))
3078 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3079 if (symbol_name == nullptr)
3081 const char *class_name = strrchr(symbol_name, '$');
3082 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3083 return class_name + 2;
3088 // The case were the pointer_value is non-zero and points to a class defined
3089 // in this Mach-O file.
3090 r = get_pointer_64(pointer_value, offset, left, S, info);
3091 if (r == nullptr || left < sizeof(struct class64_t))
3094 memcpy(&c, r, sizeof(struct class64_t));
3095 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3099 r = get_pointer_64(c.data, offset, left, S, info);
3100 if (r == nullptr || left < sizeof(struct class_ro64_t))
3102 struct class_ro64_t cro;
3103 memcpy(&cro, r, sizeof(struct class_ro64_t));
3104 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3108 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3112 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3113 // pointer to a cfstring and returns its name or nullptr.
3114 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3115 struct DisassembleInfo *info) {
3116 const char *r, *name;
3117 uint32_t offset, left;
3119 struct cfstring64_t cfs;
3120 uint64_t cfs_characters;
3122 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3123 if (r == nullptr || left < sizeof(struct cfstring64_t))
3125 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3126 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3128 if (cfs.characters == 0) {
3130 const char *symbol_name = get_symbol_64(
3131 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3132 if (symbol_name == nullptr)
3134 cfs_characters = n_value;
3136 cfs_characters = cfs.characters;
3137 name = get_pointer_64(cfs_characters, offset, left, S, info);
3142 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
3143 // of a pointer to an Objective-C selector reference when the pointer value is
3144 // zero as in a .o file and is likely to have a external relocation entry with
3145 // who's symbol's n_value is the real pointer to the selector name. If that is
3146 // the case the real pointer to the selector name is returned else 0 is
3148 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3149 struct DisassembleInfo *info) {
3150 uint32_t offset, left;
3153 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3154 if (r == nullptr || left < sizeof(uint64_t))
3157 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3158 if (symbol_name == nullptr)
3163 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3164 const char *sectname) {
3165 for (const SectionRef &Section : O->sections()) {
3167 Section.getName(SectName);
3168 DataRefImpl Ref = Section.getRawDataRefImpl();
3169 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3170 if (SegName == segname && SectName == sectname)
3173 return SectionRef();
3177 walk_pointer_list_64(const char *listname, const SectionRef S,
3178 MachOObjectFile *O, struct DisassembleInfo *info,
3179 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3180 if (S == SectionRef())
3184 S.getName(SectName);
3185 DataRefImpl Ref = S.getRawDataRefImpl();
3186 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3187 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3190 S.getContents(BytesStr);
3191 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3193 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3194 uint32_t left = S.getSize() - i;
3195 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3197 memcpy(&p, Contents + i, size);
3198 if (i + sizeof(uint64_t) > S.getSize())
3199 outs() << listname << " list pointer extends past end of (" << SegName
3200 << "," << SectName << ") section\n";
3201 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3203 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3204 sys::swapByteOrder(p);
3206 uint64_t n_value = 0;
3207 const char *name = get_symbol_64(i, S, info, n_value, p);
3208 if (name == nullptr)
3209 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3212 outs() << format("0x%" PRIx64, n_value);
3214 outs() << " + " << format("0x%" PRIx64, p);
3216 outs() << format("0x%" PRIx64, p);
3217 if (name != nullptr)
3218 outs() << " " << name;
3228 walk_pointer_list_32(const char *listname, const SectionRef S,
3229 MachOObjectFile *O, struct DisassembleInfo *info,
3230 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3231 if (S == SectionRef())
3235 S.getName(SectName);
3236 DataRefImpl Ref = S.getRawDataRefImpl();
3237 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3238 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3241 S.getContents(BytesStr);
3242 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3244 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3245 uint32_t left = S.getSize() - i;
3246 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3248 memcpy(&p, Contents + i, size);
3249 if (i + sizeof(uint32_t) > S.getSize())
3250 outs() << listname << " list pointer extends past end of (" << SegName
3251 << "," << SectName << ") section\n";
3252 uint32_t Address = S.getAddress() + i;
3253 outs() << format("%08" PRIx32, Address) << " ";
3255 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3256 sys::swapByteOrder(p);
3257 outs() << format("0x%" PRIx32, p);
3259 const char *name = get_symbol_32(i, S, info, p);
3260 if (name != nullptr)
3261 outs() << " " << name;
3269 static void print_layout_map(const char *layout_map, uint32_t left) {
3270 if (layout_map == nullptr)
3272 outs() << " layout map: ";
3274 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3277 } while (*layout_map != '\0' && left != 0);
3281 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3282 uint32_t offset, left;
3284 const char *layout_map;
3288 layout_map = get_pointer_64(p, offset, left, S, info);
3289 print_layout_map(layout_map, left);
3292 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3293 uint32_t offset, left;
3295 const char *layout_map;
3299 layout_map = get_pointer_32(p, offset, left, S, info);
3300 print_layout_map(layout_map, left);
3303 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3304 const char *indent) {
3305 struct method_list64_t ml;
3306 struct method64_t m;
3308 uint32_t offset, xoffset, left, i;
3310 const char *name, *sym_name;
3313 r = get_pointer_64(p, offset, left, S, info);
3316 memset(&ml, '\0', sizeof(struct method_list64_t));
3317 if (left < sizeof(struct method_list64_t)) {
3318 memcpy(&ml, r, left);
3319 outs() << " (method_list_t entends past the end of the section)\n";
3321 memcpy(&ml, r, sizeof(struct method_list64_t));
3322 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3324 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3325 outs() << indent << "\t\t count " << ml.count << "\n";
3327 p += sizeof(struct method_list64_t);
3328 offset += sizeof(struct method_list64_t);
3329 for (i = 0; i < ml.count; i++) {
3330 r = get_pointer_64(p, offset, left, S, info);
3333 memset(&m, '\0', sizeof(struct method64_t));
3334 if (left < sizeof(struct method64_t)) {
3335 memcpy(&m, r, left);
3336 outs() << indent << " (method_t extends past the end of the section)\n";
3338 memcpy(&m, r, sizeof(struct method64_t));
3339 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3342 outs() << indent << "\t\t name ";
3343 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3344 info, n_value, m.name);
3346 if (info->verbose && sym_name != nullptr)
3349 outs() << format("0x%" PRIx64, n_value);
3351 outs() << " + " << format("0x%" PRIx64, m.name);
3353 outs() << format("0x%" PRIx64, m.name);
3354 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3355 if (name != nullptr)
3356 outs() << format(" %.*s", left, name);
3359 outs() << indent << "\t\t types ";
3360 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3361 info, n_value, m.types);
3363 if (info->verbose && sym_name != nullptr)
3366 outs() << format("0x%" PRIx64, n_value);
3368 outs() << " + " << format("0x%" PRIx64, m.types);
3370 outs() << format("0x%" PRIx64, m.types);
3371 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3372 if (name != nullptr)
3373 outs() << format(" %.*s", left, name);
3376 outs() << indent << "\t\t imp ";
3377 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3379 if (info->verbose && name == nullptr) {
3381 outs() << format("0x%" PRIx64, n_value) << " ";
3383 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3385 outs() << format("0x%" PRIx64, m.imp) << " ";
3387 if (name != nullptr)
3391 p += sizeof(struct method64_t);
3392 offset += sizeof(struct method64_t);
3396 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3397 const char *indent) {
3398 struct method_list32_t ml;
3399 struct method32_t m;
3400 const char *r, *name;
3401 uint32_t offset, xoffset, left, i;
3404 r = get_pointer_32(p, offset, left, S, info);
3407 memset(&ml, '\0', sizeof(struct method_list32_t));
3408 if (left < sizeof(struct method_list32_t)) {
3409 memcpy(&ml, r, left);
3410 outs() << " (method_list_t entends past the end of the section)\n";
3412 memcpy(&ml, r, sizeof(struct method_list32_t));
3413 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3415 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3416 outs() << indent << "\t\t count " << ml.count << "\n";
3418 p += sizeof(struct method_list32_t);
3419 offset += sizeof(struct method_list32_t);
3420 for (i = 0; i < ml.count; i++) {
3421 r = get_pointer_32(p, offset, left, S, info);
3424 memset(&m, '\0', sizeof(struct method32_t));
3425 if (left < sizeof(struct method32_t)) {
3426 memcpy(&ml, r, left);
3427 outs() << indent << " (method_t entends past the end of the section)\n";
3429 memcpy(&m, r, sizeof(struct method32_t));
3430 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3433 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3434 name = get_pointer_32(m.name, xoffset, left, xS, info);
3435 if (name != nullptr)
3436 outs() << format(" %.*s", left, name);
3439 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3440 name = get_pointer_32(m.types, xoffset, left, xS, info);
3441 if (name != nullptr)
3442 outs() << format(" %.*s", left, name);
3445 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3446 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3448 if (name != nullptr)
3449 outs() << " " << name;
3452 p += sizeof(struct method32_t);
3453 offset += sizeof(struct method32_t);
3457 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3458 uint32_t offset, left, xleft;
3460 struct objc_method_list_t method_list;
3461 struct objc_method_t method;
3462 const char *r, *methods, *name, *SymbolName;
3465 r = get_pointer_32(p, offset, left, S, info, true);
3470 if (left > sizeof(struct objc_method_list_t)) {
3471 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3473 outs() << "\t\t objc_method_list extends past end of the section\n";
3474 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3475 memcpy(&method_list, r, left);
3477 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3478 swapStruct(method_list);
3480 outs() << "\t\t obsolete "
3481 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3482 outs() << "\t\t method_count " << method_list.method_count << "\n";
3484 methods = r + sizeof(struct objc_method_list_t);
3485 for (i = 0; i < method_list.method_count; i++) {
3486 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3487 outs() << "\t\t remaining method's extend past the of the section\n";
3490 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3491 sizeof(struct objc_method_t));
3492 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3495 outs() << "\t\t method_name "
3496 << format("0x%08" PRIx32, method.method_name);
3497 if (info->verbose) {
3498 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3499 if (name != nullptr)
3500 outs() << format(" %.*s", xleft, name);
3502 outs() << " (not in an __OBJC section)";
3506 outs() << "\t\t method_types "
3507 << format("0x%08" PRIx32, method.method_types);
3508 if (info->verbose) {
3509 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3510 if (name != nullptr)
3511 outs() << format(" %.*s", xleft, name);
3513 outs() << " (not in an __OBJC section)";
3517 outs() << "\t\t method_imp "
3518 << format("0x%08" PRIx32, method.method_imp) << " ";
3519 if (info->verbose) {
3520 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3521 if (SymbolName != nullptr)
3522 outs() << SymbolName;
3529 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3530 struct protocol_list64_t pl;
3531 uint64_t q, n_value;
3532 struct protocol64_t pc;
3534 uint32_t offset, xoffset, left, i;
3536 const char *name, *sym_name;
3538 r = get_pointer_64(p, offset, left, S, info);
3541 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3542 if (left < sizeof(struct protocol_list64_t)) {
3543 memcpy(&pl, r, left);
3544 outs() << " (protocol_list_t entends past the end of the section)\n";
3546 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3547 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3549 outs() << " count " << pl.count << "\n";
3551 p += sizeof(struct protocol_list64_t);
3552 offset += sizeof(struct protocol_list64_t);
3553 for (i = 0; i < pl.count; i++) {
3554 r = get_pointer_64(p, offset, left, S, info);
3558 if (left < sizeof(uint64_t)) {
3559 memcpy(&q, r, left);
3560 outs() << " (protocol_t * entends past the end of the section)\n";
3562 memcpy(&q, r, sizeof(uint64_t));
3563 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3564 sys::swapByteOrder(q);
3566 outs() << "\t\t list[" << i << "] ";
3567 sym_name = get_symbol_64(offset, S, info, n_value, q);
3569 if (info->verbose && sym_name != nullptr)
3572 outs() << format("0x%" PRIx64, n_value);
3574 outs() << " + " << format("0x%" PRIx64, q);
3576 outs() << format("0x%" PRIx64, q);
3577 outs() << " (struct protocol_t *)\n";
3579 r = get_pointer_64(q + n_value, offset, left, S, info);
3582 memset(&pc, '\0', sizeof(struct protocol64_t));
3583 if (left < sizeof(struct protocol64_t)) {
3584 memcpy(&pc, r, left);
3585 outs() << " (protocol_t entends past the end of the section)\n";
3587 memcpy(&pc, r, sizeof(struct protocol64_t));
3588 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3591 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3593 outs() << "\t\t\t name ";
3594 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3595 info, n_value, pc.name);
3597 if (info->verbose && sym_name != nullptr)
3600 outs() << format("0x%" PRIx64, n_value);
3602 outs() << " + " << format("0x%" PRIx64, pc.name);
3604 outs() << format("0x%" PRIx64, pc.name);
3605 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3606 if (name != nullptr)
3607 outs() << format(" %.*s", left, name);
3610 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3612 outs() << "\t\t instanceMethods ";
3614 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3615 S, info, n_value, pc.instanceMethods);
3617 if (info->verbose && sym_name != nullptr)
3620 outs() << format("0x%" PRIx64, n_value);
3621 if (pc.instanceMethods != 0)
3622 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3624 outs() << format("0x%" PRIx64, pc.instanceMethods);
3625 outs() << " (struct method_list_t *)\n";
3626 if (pc.instanceMethods + n_value != 0)
3627 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3629 outs() << "\t\t classMethods ";
3631 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3632 info, n_value, pc.classMethods);
3634 if (info->verbose && sym_name != nullptr)
3637 outs() << format("0x%" PRIx64, n_value);
3638 if (pc.classMethods != 0)
3639 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3641 outs() << format("0x%" PRIx64, pc.classMethods);
3642 outs() << " (struct method_list_t *)\n";
3643 if (pc.classMethods + n_value != 0)
3644 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3646 outs() << "\t optionalInstanceMethods "
3647 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3648 outs() << "\t optionalClassMethods "
3649 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3650 outs() << "\t instanceProperties "
3651 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3653 p += sizeof(uint64_t);
3654 offset += sizeof(uint64_t);
3658 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3659 struct protocol_list32_t pl;
3661 struct protocol32_t pc;
3663 uint32_t offset, xoffset, left, i;
3667 r = get_pointer_32(p, offset, left, S, info);
3670 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3671 if (left < sizeof(struct protocol_list32_t)) {
3672 memcpy(&pl, r, left);
3673 outs() << " (protocol_list_t entends past the end of the section)\n";
3675 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3676 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3678 outs() << " count " << pl.count << "\n";
3680 p += sizeof(struct protocol_list32_t);
3681 offset += sizeof(struct protocol_list32_t);
3682 for (i = 0; i < pl.count; i++) {
3683 r = get_pointer_32(p, offset, left, S, info);
3687 if (left < sizeof(uint32_t)) {
3688 memcpy(&q, r, left);
3689 outs() << " (protocol_t * entends past the end of the section)\n";
3691 memcpy(&q, r, sizeof(uint32_t));
3692 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3693 sys::swapByteOrder(q);
3694 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3695 << " (struct protocol_t *)\n";
3696 r = get_pointer_32(q, offset, left, S, info);
3699 memset(&pc, '\0', sizeof(struct protocol32_t));
3700 if (left < sizeof(struct protocol32_t)) {
3701 memcpy(&pc, r, left);
3702 outs() << " (protocol_t entends past the end of the section)\n";
3704 memcpy(&pc, r, sizeof(struct protocol32_t));
3705 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3707 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3708 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3709 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3710 if (name != nullptr)
3711 outs() << format(" %.*s", left, name);
3713 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3714 outs() << "\t\t instanceMethods "
3715 << format("0x%" PRIx32, pc.instanceMethods)
3716 << " (struct method_list_t *)\n";
3717 if (pc.instanceMethods != 0)
3718 print_method_list32_t(pc.instanceMethods, info, "\t");
3719 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3720 << " (struct method_list_t *)\n";
3721 if (pc.classMethods != 0)
3722 print_method_list32_t(pc.classMethods, info, "\t");
3723 outs() << "\t optionalInstanceMethods "
3724 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3725 outs() << "\t optionalClassMethods "
3726 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3727 outs() << "\t instanceProperties "
3728 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3729 p += sizeof(uint32_t);
3730 offset += sizeof(uint32_t);
3734 static void print_indent(uint32_t indent) {
3735 for (uint32_t i = 0; i < indent;) {
3736 if (indent - i >= 8) {
3740 for (uint32_t j = i; j < indent; j++)
3747 static bool print_method_description_list(uint32_t p, uint32_t indent,
3748 struct DisassembleInfo *info) {
3749 uint32_t offset, left, xleft;
3751 struct objc_method_description_list_t mdl;
3752 struct objc_method_description_t md;
3753 const char *r, *list, *name;
3756 r = get_pointer_32(p, offset, left, S, info, true);
3761 if (left > sizeof(struct objc_method_description_list_t)) {
3762 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3764 print_indent(indent);
3765 outs() << " objc_method_description_list extends past end of the section\n";
3766 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3767 memcpy(&mdl, r, left);
3769 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3772 print_indent(indent);
3773 outs() << " count " << mdl.count << "\n";
3775 list = r + sizeof(struct objc_method_description_list_t);
3776 for (i = 0; i < mdl.count; i++) {
3777 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3778 print_indent(indent);
3779 outs() << " remaining list entries extend past the of the section\n";
3782 print_indent(indent);
3783 outs() << " list[" << i << "]\n";
3784 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3785 sizeof(struct objc_method_description_t));
3786 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3789 print_indent(indent);
3790 outs() << " name " << format("0x%08" PRIx32, md.name);
3791 if (info->verbose) {
3792 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3793 if (name != nullptr)
3794 outs() << format(" %.*s", xleft, name);
3796 outs() << " (not in an __OBJC section)";
3800 print_indent(indent);
3801 outs() << " types " << format("0x%08" PRIx32, md.types);
3802 if (info->verbose) {
3803 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3804 if (name != nullptr)
3805 outs() << format(" %.*s", xleft, name);
3807 outs() << " (not in an __OBJC section)";
3814 static bool print_protocol_list(uint32_t p, uint32_t indent,
3815 struct DisassembleInfo *info);
3817 static bool print_protocol(uint32_t p, uint32_t indent,
3818 struct DisassembleInfo *info) {
3819 uint32_t offset, left;
3821 struct objc_protocol_t protocol;
3822 const char *r, *name;
3824 r = get_pointer_32(p, offset, left, S, info, true);
3829 if (left >= sizeof(struct objc_protocol_t)) {
3830 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3832 print_indent(indent);
3833 outs() << " Protocol extends past end of the section\n";
3834 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3835 memcpy(&protocol, r, left);
3837 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3838 swapStruct(protocol);
3840 print_indent(indent);
3841 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3844 print_indent(indent);
3845 outs() << " protocol_name "
3846 << format("0x%08" PRIx32, protocol.protocol_name);
3847 if (info->verbose) {
3848 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3849 if (name != nullptr)
3850 outs() << format(" %.*s", left, name);
3852 outs() << " (not in an __OBJC section)";
3856 print_indent(indent);
3857 outs() << " protocol_list "
3858 << format("0x%08" PRIx32, protocol.protocol_list);
3859 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3860 outs() << " (not in an __OBJC section)\n";
3862 print_indent(indent);
3863 outs() << " instance_methods "
3864 << format("0x%08" PRIx32, protocol.instance_methods);
3865 if (print_method_description_list(protocol.instance_methods, indent, info))
3866 outs() << " (not in an __OBJC section)\n";
3868 print_indent(indent);
3869 outs() << " class_methods "
3870 << format("0x%08" PRIx32, protocol.class_methods);
3871 if (print_method_description_list(protocol.class_methods, indent, info))
3872 outs() << " (not in an __OBJC section)\n";
3877 static bool print_protocol_list(uint32_t p, uint32_t indent,
3878 struct DisassembleInfo *info) {
3879 uint32_t offset, left, l;
3881 struct objc_protocol_list_t protocol_list;
3882 const char *r, *list;
3885 r = get_pointer_32(p, offset, left, S, info, true);
3890 if (left > sizeof(struct objc_protocol_list_t)) {
3891 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3893 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3894 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3895 memcpy(&protocol_list, r, left);
3897 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3898 swapStruct(protocol_list);
3900 print_indent(indent);
3901 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3903 print_indent(indent);
3904 outs() << " count " << protocol_list.count << "\n";
3906 list = r + sizeof(struct objc_protocol_list_t);
3907 for (i = 0; i < protocol_list.count; i++) {
3908 if ((i + 1) * sizeof(uint32_t) > left) {
3909 outs() << "\t\t remaining list entries extend past the of the section\n";
3912 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3913 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3914 sys::swapByteOrder(l);
3916 print_indent(indent);
3917 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3918 if (print_protocol(l, indent, info))
3919 outs() << "(not in an __OBJC section)\n";
3924 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3925 struct ivar_list64_t il;
3928 uint32_t offset, xoffset, left, j;
3930 const char *name, *sym_name, *ivar_offset_p;
3931 uint64_t ivar_offset, n_value;
3933 r = get_pointer_64(p, offset, left, S, info);
3936 memset(&il, '\0', sizeof(struct ivar_list64_t));
3937 if (left < sizeof(struct ivar_list64_t)) {
3938 memcpy(&il, r, left);
3939 outs() << " (ivar_list_t entends past the end of the section)\n";
3941 memcpy(&il, r, sizeof(struct ivar_list64_t));
3942 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3944 outs() << " entsize " << il.entsize << "\n";
3945 outs() << " count " << il.count << "\n";
3947 p += sizeof(struct ivar_list64_t);
3948 offset += sizeof(struct ivar_list64_t);
3949 for (j = 0; j < il.count; j++) {
3950 r = get_pointer_64(p, offset, left, S, info);
3953 memset(&i, '\0', sizeof(struct ivar64_t));
3954 if (left < sizeof(struct ivar64_t)) {
3955 memcpy(&i, r, left);
3956 outs() << " (ivar_t entends past the end of the section)\n";
3958 memcpy(&i, r, sizeof(struct ivar64_t));
3959 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3962 outs() << "\t\t\t offset ";
3963 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3964 info, n_value, i.offset);
3966 if (info->verbose && sym_name != nullptr)
3969 outs() << format("0x%" PRIx64, n_value);
3971 outs() << " + " << format("0x%" PRIx64, i.offset);
3973 outs() << format("0x%" PRIx64, i.offset);
3974 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3975 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3976 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3977 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3978 sys::swapByteOrder(ivar_offset);
3979 outs() << " " << ivar_offset << "\n";
3983 outs() << "\t\t\t name ";
3984 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
3987 if (info->verbose && sym_name != nullptr)
3990 outs() << format("0x%" PRIx64, n_value);
3992 outs() << " + " << format("0x%" PRIx64, i.name);
3994 outs() << format("0x%" PRIx64, i.name);
3995 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
3996 if (name != nullptr)
3997 outs() << format(" %.*s", left, name);
4000 outs() << "\t\t\t type ";
4001 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4003 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4005 if (info->verbose && sym_name != nullptr)
4008 outs() << format("0x%" PRIx64, n_value);
4010 outs() << " + " << format("0x%" PRIx64, i.type);
4012 outs() << format("0x%" PRIx64, i.type);
4013 if (name != nullptr)
4014 outs() << format(" %.*s", left, name);
4017 outs() << "\t\t\talignment " << i.alignment << "\n";
4018 outs() << "\t\t\t size " << i.size << "\n";
4020 p += sizeof(struct ivar64_t);
4021 offset += sizeof(struct ivar64_t);
4025 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4026 struct ivar_list32_t il;
4029 uint32_t offset, xoffset, left, j;
4031 const char *name, *ivar_offset_p;
4032 uint32_t ivar_offset;
4034 r = get_pointer_32(p, offset, left, S, info);
4037 memset(&il, '\0', sizeof(struct ivar_list32_t));
4038 if (left < sizeof(struct ivar_list32_t)) {
4039 memcpy(&il, r, left);
4040 outs() << " (ivar_list_t entends past the end of the section)\n";
4042 memcpy(&il, r, sizeof(struct ivar_list32_t));
4043 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4045 outs() << " entsize " << il.entsize << "\n";
4046 outs() << " count " << il.count << "\n";
4048 p += sizeof(struct ivar_list32_t);
4049 offset += sizeof(struct ivar_list32_t);
4050 for (j = 0; j < il.count; j++) {
4051 r = get_pointer_32(p, offset, left, S, info);
4054 memset(&i, '\0', sizeof(struct ivar32_t));
4055 if (left < sizeof(struct ivar32_t)) {
4056 memcpy(&i, r, left);
4057 outs() << " (ivar_t entends past the end of the section)\n";
4059 memcpy(&i, r, sizeof(struct ivar32_t));
4060 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4063 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4064 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4065 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4066 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4067 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4068 sys::swapByteOrder(ivar_offset);
4069 outs() << " " << ivar_offset << "\n";
4073 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4074 name = get_pointer_32(i.name, xoffset, left, xS, info);
4075 if (name != nullptr)
4076 outs() << format(" %.*s", left, name);
4079 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4080 name = get_pointer_32(i.type, xoffset, left, xS, info);
4081 if (name != nullptr)
4082 outs() << format(" %.*s", left, name);
4085 outs() << "\t\t\talignment " << i.alignment << "\n";
4086 outs() << "\t\t\t size " << i.size << "\n";
4088 p += sizeof(struct ivar32_t);
4089 offset += sizeof(struct ivar32_t);
4093 static void print_objc_property_list64(uint64_t p,
4094 struct DisassembleInfo *info) {
4095 struct objc_property_list64 opl;
4096 struct objc_property64 op;
4098 uint32_t offset, xoffset, left, j;
4100 const char *name, *sym_name;
4103 r = get_pointer_64(p, offset, left, S, info);
4106 memset(&opl, '\0', sizeof(struct objc_property_list64));
4107 if (left < sizeof(struct objc_property_list64)) {
4108 memcpy(&opl, r, left);
4109 outs() << " (objc_property_list entends past the end of the section)\n";
4111 memcpy(&opl, r, sizeof(struct objc_property_list64));
4112 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4114 outs() << " entsize " << opl.entsize << "\n";
4115 outs() << " count " << opl.count << "\n";
4117 p += sizeof(struct objc_property_list64);
4118 offset += sizeof(struct objc_property_list64);
4119 for (j = 0; j < opl.count; j++) {
4120 r = get_pointer_64(p, offset, left, S, info);
4123 memset(&op, '\0', sizeof(struct objc_property64));
4124 if (left < sizeof(struct objc_property64)) {
4125 memcpy(&op, r, left);
4126 outs() << " (objc_property entends past the end of the section)\n";
4128 memcpy(&op, r, sizeof(struct objc_property64));
4129 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4132 outs() << "\t\t\t name ";
4133 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4134 info, n_value, op.name);
4136 if (info->verbose && sym_name != nullptr)
4139 outs() << format("0x%" PRIx64, n_value);
4141 outs() << " + " << format("0x%" PRIx64, op.name);
4143 outs() << format("0x%" PRIx64, op.name);
4144 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4145 if (name != nullptr)
4146 outs() << format(" %.*s", left, name);
4149 outs() << "\t\t\tattributes ";
4151 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4152 info, n_value, op.attributes);
4154 if (info->verbose && sym_name != nullptr)
4157 outs() << format("0x%" PRIx64, n_value);
4158 if (op.attributes != 0)
4159 outs() << " + " << format("0x%" PRIx64, op.attributes);
4161 outs() << format("0x%" PRIx64, op.attributes);
4162 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4163 if (name != nullptr)
4164 outs() << format(" %.*s", left, name);
4167 p += sizeof(struct objc_property64);
4168 offset += sizeof(struct objc_property64);
4172 static void print_objc_property_list32(uint32_t p,
4173 struct DisassembleInfo *info) {
4174 struct objc_property_list32 opl;
4175 struct objc_property32 op;
4177 uint32_t offset, xoffset, left, j;
4181 r = get_pointer_32(p, offset, left, S, info);
4184 memset(&opl, '\0', sizeof(struct objc_property_list32));
4185 if (left < sizeof(struct objc_property_list32)) {
4186 memcpy(&opl, r, left);
4187 outs() << " (objc_property_list entends past the end of the section)\n";
4189 memcpy(&opl, r, sizeof(struct objc_property_list32));
4190 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4192 outs() << " entsize " << opl.entsize << "\n";
4193 outs() << " count " << opl.count << "\n";
4195 p += sizeof(struct objc_property_list32);
4196 offset += sizeof(struct objc_property_list32);
4197 for (j = 0; j < opl.count; j++) {
4198 r = get_pointer_32(p, offset, left, S, info);
4201 memset(&op, '\0', sizeof(struct objc_property32));
4202 if (left < sizeof(struct objc_property32)) {
4203 memcpy(&op, r, left);
4204 outs() << " (objc_property entends past the end of the section)\n";
4206 memcpy(&op, r, sizeof(struct objc_property32));
4207 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4210 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4211 name = get_pointer_32(op.name, xoffset, left, xS, info);
4212 if (name != nullptr)
4213 outs() << format(" %.*s", left, name);
4216 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4217 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4218 if (name != nullptr)
4219 outs() << format(" %.*s", left, name);
4222 p += sizeof(struct objc_property32);
4223 offset += sizeof(struct objc_property32);
4227 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
4228 bool &is_meta_class) {
4229 struct class_ro64_t cro;
4231 uint32_t offset, xoffset, left;
4233 const char *name, *sym_name;
4236 r = get_pointer_64(p, offset, left, S, info);
4237 if (r == nullptr || left < sizeof(struct class_ro64_t))
4239 memset(&cro, '\0', sizeof(struct class_ro64_t));
4240 if (left < sizeof(struct class_ro64_t)) {
4241 memcpy(&cro, r, left);
4242 outs() << " (class_ro_t entends past the end of the section)\n";
4244 memcpy(&cro, r, sizeof(struct class_ro64_t));
4245 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4247 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4248 if (cro.flags & RO_META)
4249 outs() << " RO_META";
4250 if (cro.flags & RO_ROOT)
4251 outs() << " RO_ROOT";
4252 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4253 outs() << " RO_HAS_CXX_STRUCTORS";
4255 outs() << " instanceStart " << cro.instanceStart << "\n";
4256 outs() << " instanceSize " << cro.instanceSize << "\n";
4257 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4259 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4261 print_layout_map64(cro.ivarLayout, info);
4264 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4265 info, n_value, cro.name);
4267 if (info->verbose && sym_name != nullptr)
4270 outs() << format("0x%" PRIx64, n_value);
4272 outs() << " + " << format("0x%" PRIx64, cro.name);
4274 outs() << format("0x%" PRIx64, cro.name);
4275 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4276 if (name != nullptr)
4277 outs() << format(" %.*s", left, name);
4280 outs() << " baseMethods ";
4281 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4282 S, info, n_value, cro.baseMethods);
4284 if (info->verbose && sym_name != nullptr)
4287 outs() << format("0x%" PRIx64, n_value);
4288 if (cro.baseMethods != 0)
4289 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4291 outs() << format("0x%" PRIx64, cro.baseMethods);
4292 outs() << " (struct method_list_t *)\n";
4293 if (cro.baseMethods + n_value != 0)
4294 print_method_list64_t(cro.baseMethods + n_value, info, "");
4296 outs() << " baseProtocols ";
4298 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4299 info, n_value, cro.baseProtocols);
4301 if (info->verbose && sym_name != nullptr)
4304 outs() << format("0x%" PRIx64, n_value);
4305 if (cro.baseProtocols != 0)
4306 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4308 outs() << format("0x%" PRIx64, cro.baseProtocols);
4310 if (cro.baseProtocols + n_value != 0)
4311 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4313 outs() << " ivars ";
4314 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
4315 info, n_value, cro.ivars);
4317 if (info->verbose && sym_name != nullptr)
4320 outs() << format("0x%" PRIx64, n_value);
4322 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4324 outs() << format("0x%" PRIx64, cro.ivars);
4326 if (cro.ivars + n_value != 0)
4327 print_ivar_list64_t(cro.ivars + n_value, info);
4329 outs() << " weakIvarLayout ";
4331 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4332 info, n_value, cro.weakIvarLayout);
4334 if (info->verbose && sym_name != nullptr)
4337 outs() << format("0x%" PRIx64, n_value);
4338 if (cro.weakIvarLayout != 0)
4339 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4341 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4343 print_layout_map64(cro.weakIvarLayout + n_value, info);
4345 outs() << " baseProperties ";
4347 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4348 info, n_value, cro.baseProperties);
4350 if (info->verbose && sym_name != nullptr)
4353 outs() << format("0x%" PRIx64, n_value);
4354 if (cro.baseProperties != 0)
4355 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4357 outs() << format("0x%" PRIx64, cro.baseProperties);
4359 if (cro.baseProperties + n_value != 0)
4360 print_objc_property_list64(cro.baseProperties + n_value, info);
4362 is_meta_class = (cro.flags & RO_META) != 0;
4366 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
4367 bool &is_meta_class) {
4368 struct class_ro32_t cro;
4370 uint32_t offset, xoffset, left;
4374 r = get_pointer_32(p, offset, left, S, info);
4377 memset(&cro, '\0', sizeof(struct class_ro32_t));
4378 if (left < sizeof(struct class_ro32_t)) {
4379 memcpy(&cro, r, left);
4380 outs() << " (class_ro_t entends past the end of the section)\n";
4382 memcpy(&cro, r, sizeof(struct class_ro32_t));
4383 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4385 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4386 if (cro.flags & RO_META)
4387 outs() << " RO_META";
4388 if (cro.flags & RO_ROOT)
4389 outs() << " RO_ROOT";
4390 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4391 outs() << " RO_HAS_CXX_STRUCTORS";
4393 outs() << " instanceStart " << cro.instanceStart << "\n";
4394 outs() << " instanceSize " << cro.instanceSize << "\n";
4395 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4397 print_layout_map32(cro.ivarLayout, info);
4399 outs() << " name " << format("0x%" PRIx32, cro.name);
4400 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4401 if (name != nullptr)
4402 outs() << format(" %.*s", left, name);
4405 outs() << " baseMethods "
4406 << format("0x%" PRIx32, cro.baseMethods)
4407 << " (struct method_list_t *)\n";
4408 if (cro.baseMethods != 0)
4409 print_method_list32_t(cro.baseMethods, info, "");
4411 outs() << " baseProtocols "
4412 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4413 if (cro.baseProtocols != 0)
4414 print_protocol_list32_t(cro.baseProtocols, info);
4415 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4418 print_ivar_list32_t(cro.ivars, info);
4419 outs() << " weakIvarLayout "
4420 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4421 print_layout_map32(cro.weakIvarLayout, info);
4422 outs() << " baseProperties "
4423 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4424 if (cro.baseProperties != 0)
4425 print_objc_property_list32(cro.baseProperties, info);
4426 is_meta_class = (cro.flags & RO_META) != 0;
4430 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4433 uint32_t offset, left;
4436 uint64_t isa_n_value, n_value;
4438 r = get_pointer_64(p, offset, left, S, info);
4439 if (r == nullptr || left < sizeof(struct class64_t))
4441 memset(&c, '\0', sizeof(struct class64_t));
4442 if (left < sizeof(struct class64_t)) {
4443 memcpy(&c, r, left);
4444 outs() << " (class_t entends past the end of the section)\n";
4446 memcpy(&c, r, sizeof(struct class64_t));
4447 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4450 outs() << " isa " << format("0x%" PRIx64, c.isa);
4451 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4452 isa_n_value, c.isa);
4453 if (name != nullptr)
4454 outs() << " " << name;
4457 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4458 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4459 n_value, c.superclass);
4460 if (name != nullptr)
4461 outs() << " " << name;
4464 outs() << " cache " << format("0x%" PRIx64, c.cache);
4465 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4467 if (name != nullptr)
4468 outs() << " " << name;
4471 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4472 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4474 if (name != nullptr)
4475 outs() << " " << name;
4478 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4482 if (info->verbose && name != nullptr)
4485 outs() << format("0x%" PRIx64, n_value);
4487 outs() << " + " << format("0x%" PRIx64, c.data);
4489 outs() << format("0x%" PRIx64, c.data);
4490 outs() << " (struct class_ro_t *)";
4492 // This is a Swift class if some of the low bits of the pointer are set.
4493 if ((c.data + n_value) & 0x7)
4494 outs() << " Swift class";
4497 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4500 if (!is_meta_class &&
4501 c.isa + isa_n_value != p &&
4502 c.isa + isa_n_value != 0 &&
4503 info->depth < 100) {
4505 outs() << "Meta Class\n";
4506 print_class64_t(c.isa + isa_n_value, info);
4510 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4513 uint32_t offset, left;
4517 r = get_pointer_32(p, offset, left, S, info);
4520 memset(&c, '\0', sizeof(struct class32_t));
4521 if (left < sizeof(struct class32_t)) {
4522 memcpy(&c, r, left);
4523 outs() << " (class_t entends past the end of the section)\n";
4525 memcpy(&c, r, sizeof(struct class32_t));
4526 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4529 outs() << " isa " << format("0x%" PRIx32, c.isa);
4531 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4532 if (name != nullptr)
4533 outs() << " " << name;
4536 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4537 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4539 if (name != nullptr)
4540 outs() << " " << name;
4543 outs() << " cache " << format("0x%" PRIx32, c.cache);
4544 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4546 if (name != nullptr)
4547 outs() << " " << name;
4550 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4551 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4553 if (name != nullptr)
4554 outs() << " " << name;
4558 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4559 outs() << " data " << format("0x%" PRIx32, c.data)
4560 << " (struct class_ro_t *)";
4562 // This is a Swift class if some of the low bits of the pointer are set.
4564 outs() << " Swift class";
4567 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4570 if (!is_meta_class) {
4571 outs() << "Meta Class\n";
4572 print_class32_t(c.isa, info);
4576 static void print_objc_class_t(struct objc_class_t *objc_class,
4577 struct DisassembleInfo *info) {
4578 uint32_t offset, left, xleft;
4579 const char *name, *p, *ivar_list;
4582 struct objc_ivar_list_t objc_ivar_list;
4583 struct objc_ivar_t ivar;
4585 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4586 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4587 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4588 if (name != nullptr)
4589 outs() << format(" %.*s", left, name);
4591 outs() << " (not in an __OBJC section)";
4595 outs() << "\t super_class "
4596 << format("0x%08" PRIx32, objc_class->super_class);
4597 if (info->verbose) {
4598 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4599 if (name != nullptr)
4600 outs() << format(" %.*s", left, name);
4602 outs() << " (not in an __OBJC section)";
4606 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4607 if (info->verbose) {
4608 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4609 if (name != nullptr)
4610 outs() << format(" %.*s", left, name);
4612 outs() << " (not in an __OBJC section)";
4616 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4619 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4620 if (info->verbose) {
4621 if (CLS_GETINFO(objc_class, CLS_CLASS))
4622 outs() << " CLS_CLASS";
4623 else if (CLS_GETINFO(objc_class, CLS_META))
4624 outs() << " CLS_META";
4628 outs() << "\t instance_size "
4629 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4631 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4632 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4634 if (left > sizeof(struct objc_ivar_list_t)) {
4636 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4638 outs() << " (entends past the end of the section)\n";
4639 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4640 memcpy(&objc_ivar_list, p, left);
4642 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4643 swapStruct(objc_ivar_list);
4644 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4645 ivar_list = p + sizeof(struct objc_ivar_list_t);
4646 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4647 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4648 outs() << "\t\t remaining ivar's extend past the of the section\n";
4651 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4652 sizeof(struct objc_ivar_t));
4653 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4656 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4657 if (info->verbose) {
4658 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4659 if (name != nullptr)
4660 outs() << format(" %.*s", xleft, name);
4662 outs() << " (not in an __OBJC section)";
4666 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4667 if (info->verbose) {
4668 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4669 if (name != nullptr)
4670 outs() << format(" %.*s", xleft, name);
4672 outs() << " (not in an __OBJC section)";
4676 outs() << "\t\t ivar_offset "
4677 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4680 outs() << " (not in an __OBJC section)\n";
4683 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4684 if (print_method_list(objc_class->methodLists, info))
4685 outs() << " (not in an __OBJC section)\n";
4687 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4690 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4691 if (print_protocol_list(objc_class->protocols, 16, info))
4692 outs() << " (not in an __OBJC section)\n";
4695 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4696 struct DisassembleInfo *info) {
4697 uint32_t offset, left;
4701 outs() << "\t category name "
4702 << format("0x%08" PRIx32, objc_category->category_name);
4703 if (info->verbose) {
4704 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4706 if (name != nullptr)
4707 outs() << format(" %.*s", left, name);
4709 outs() << " (not in an __OBJC section)";
4713 outs() << "\t\t class name "
4714 << format("0x%08" PRIx32, objc_category->class_name);
4715 if (info->verbose) {
4717 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4718 if (name != nullptr)
4719 outs() << format(" %.*s", left, name);
4721 outs() << " (not in an __OBJC section)";
4725 outs() << "\t instance methods "
4726 << format("0x%08" PRIx32, objc_category->instance_methods);
4727 if (print_method_list(objc_category->instance_methods, info))
4728 outs() << " (not in an __OBJC section)\n";
4730 outs() << "\t class methods "
4731 << format("0x%08" PRIx32, objc_category->class_methods);
4732 if (print_method_list(objc_category->class_methods, info))
4733 outs() << " (not in an __OBJC section)\n";
4736 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4737 struct category64_t c;
4739 uint32_t offset, xoffset, left;
4741 const char *name, *sym_name;
4744 r = get_pointer_64(p, offset, left, S, info);
4747 memset(&c, '\0', sizeof(struct category64_t));
4748 if (left < sizeof(struct category64_t)) {
4749 memcpy(&c, r, left);
4750 outs() << " (category_t entends past the end of the section)\n";
4752 memcpy(&c, r, sizeof(struct category64_t));
4753 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4757 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4758 info, n_value, c.name);
4760 if (info->verbose && sym_name != nullptr)
4763 outs() << format("0x%" PRIx64, n_value);
4765 outs() << " + " << format("0x%" PRIx64, c.name);
4767 outs() << format("0x%" PRIx64, c.name);
4768 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4769 if (name != nullptr)
4770 outs() << format(" %.*s", left, name);
4774 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4777 if (info->verbose && sym_name != nullptr)
4780 outs() << format("0x%" PRIx64, n_value);
4782 outs() << " + " << format("0x%" PRIx64, c.cls);
4784 outs() << format("0x%" PRIx64, c.cls);
4786 if (c.cls + n_value != 0)
4787 print_class64_t(c.cls + n_value, info);
4789 outs() << " instanceMethods ";
4791 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4792 info, n_value, c.instanceMethods);
4794 if (info->verbose && sym_name != nullptr)
4797 outs() << format("0x%" PRIx64, n_value);
4798 if (c.instanceMethods != 0)
4799 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4801 outs() << format("0x%" PRIx64, c.instanceMethods);
4803 if (c.instanceMethods + n_value != 0)
4804 print_method_list64_t(c.instanceMethods + n_value, info, "");
4806 outs() << " classMethods ";
4807 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4808 S, info, n_value, c.classMethods);
4810 if (info->verbose && sym_name != nullptr)
4813 outs() << format("0x%" PRIx64, n_value);
4814 if (c.classMethods != 0)
4815 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4817 outs() << format("0x%" PRIx64, c.classMethods);
4819 if (c.classMethods + n_value != 0)
4820 print_method_list64_t(c.classMethods + n_value, info, "");
4822 outs() << " protocols ";
4823 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4824 info, n_value, c.protocols);
4826 if (info->verbose && sym_name != nullptr)
4829 outs() << format("0x%" PRIx64, n_value);
4830 if (c.protocols != 0)
4831 outs() << " + " << format("0x%" PRIx64, c.protocols);
4833 outs() << format("0x%" PRIx64, c.protocols);
4835 if (c.protocols + n_value != 0)
4836 print_protocol_list64_t(c.protocols + n_value, info);
4838 outs() << "instanceProperties ";
4840 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4841 S, info, n_value, c.instanceProperties);
4843 if (info->verbose && sym_name != nullptr)
4846 outs() << format("0x%" PRIx64, n_value);
4847 if (c.instanceProperties != 0)
4848 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4850 outs() << format("0x%" PRIx64, c.instanceProperties);
4852 if (c.instanceProperties + n_value != 0)
4853 print_objc_property_list64(c.instanceProperties + n_value, info);
4856 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4857 struct category32_t c;
4859 uint32_t offset, left;
4863 r = get_pointer_32(p, offset, left, S, info);
4866 memset(&c, '\0', sizeof(struct category32_t));
4867 if (left < sizeof(struct category32_t)) {
4868 memcpy(&c, r, left);
4869 outs() << " (category_t entends past the end of the section)\n";
4871 memcpy(&c, r, sizeof(struct category32_t));
4872 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4875 outs() << " name " << format("0x%" PRIx32, c.name);
4876 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4879 outs() << " " << name;
4882 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4884 print_class32_t(c.cls, info);
4885 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4887 if (c.instanceMethods != 0)
4888 print_method_list32_t(c.instanceMethods, info, "");
4889 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4891 if (c.classMethods != 0)
4892 print_method_list32_t(c.classMethods, info, "");
4893 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4894 if (c.protocols != 0)
4895 print_protocol_list32_t(c.protocols, info);
4896 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4898 if (c.instanceProperties != 0)
4899 print_objc_property_list32(c.instanceProperties, info);
4902 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4903 uint32_t i, left, offset, xoffset;
4904 uint64_t p, n_value;
4905 struct message_ref64 mr;
4906 const char *name, *sym_name;
4910 if (S == SectionRef())
4914 S.getName(SectName);
4915 DataRefImpl Ref = S.getRawDataRefImpl();
4916 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4917 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4919 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4920 p = S.getAddress() + i;
4921 r = get_pointer_64(p, offset, left, S, info);
4924 memset(&mr, '\0', sizeof(struct message_ref64));
4925 if (left < sizeof(struct message_ref64)) {
4926 memcpy(&mr, r, left);
4927 outs() << " (message_ref entends past the end of the section)\n";
4929 memcpy(&mr, r, sizeof(struct message_ref64));
4930 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4934 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4937 outs() << format("0x%" PRIx64, n_value) << " ";
4939 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4941 outs() << format("0x%" PRIx64, mr.imp) << " ";
4942 if (name != nullptr)
4943 outs() << " " << name;
4947 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4948 info, n_value, mr.sel);
4950 if (info->verbose && sym_name != nullptr)
4953 outs() << format("0x%" PRIx64, n_value);
4955 outs() << " + " << format("0x%" PRIx64, mr.sel);
4957 outs() << format("0x%" PRIx64, mr.sel);
4958 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4959 if (name != nullptr)
4960 outs() << format(" %.*s", left, name);
4963 offset += sizeof(struct message_ref64);
4967 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
4968 uint32_t i, left, offset, xoffset, p;
4969 struct message_ref32 mr;
4970 const char *name, *r;
4973 if (S == SectionRef())
4977 S.getName(SectName);
4978 DataRefImpl Ref = S.getRawDataRefImpl();
4979 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4980 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4982 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4983 p = S.getAddress() + i;
4984 r = get_pointer_32(p, offset, left, S, info);
4987 memset(&mr, '\0', sizeof(struct message_ref32));
4988 if (left < sizeof(struct message_ref32)) {
4989 memcpy(&mr, r, left);
4990 outs() << " (message_ref entends past the end of the section)\n";
4992 memcpy(&mr, r, sizeof(struct message_ref32));
4993 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4996 outs() << " imp " << format("0x%" PRIx32, mr.imp);
4997 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
4999 if (name != nullptr)
5000 outs() << " " << name;
5003 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5004 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5005 if (name != nullptr)
5006 outs() << " " << name;
5009 offset += sizeof(struct message_ref32);
5013 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5014 uint32_t left, offset, swift_version;
5016 struct objc_image_info64 o;
5019 if (S == SectionRef())
5023 S.getName(SectName);
5024 DataRefImpl Ref = S.getRawDataRefImpl();
5025 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5026 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5028 r = get_pointer_64(p, offset, left, S, info);
5031 memset(&o, '\0', sizeof(struct objc_image_info64));
5032 if (left < sizeof(struct objc_image_info64)) {
5033 memcpy(&o, r, left);
5034 outs() << " (objc_image_info entends past the end of the section)\n";
5036 memcpy(&o, r, sizeof(struct objc_image_info64));
5037 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5039 outs() << " version " << o.version << "\n";
5040 outs() << " flags " << format("0x%" PRIx32, o.flags);
5041 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5042 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5043 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5044 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5045 swift_version = (o.flags >> 8) & 0xff;
5046 if (swift_version != 0) {
5047 if (swift_version == 1)
5048 outs() << " Swift 1.0";
5049 else if (swift_version == 2)
5050 outs() << " Swift 1.1";
5052 outs() << " unknown future Swift version (" << swift_version << ")";
5057 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5058 uint32_t left, offset, swift_version, p;
5059 struct objc_image_info32 o;
5063 S.getName(SectName);
5064 DataRefImpl Ref = S.getRawDataRefImpl();
5065 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5066 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5068 r = get_pointer_32(p, offset, left, S, info);
5071 memset(&o, '\0', sizeof(struct objc_image_info32));
5072 if (left < sizeof(struct objc_image_info32)) {
5073 memcpy(&o, r, left);
5074 outs() << " (objc_image_info entends past the end of the section)\n";
5076 memcpy(&o, r, sizeof(struct objc_image_info32));
5077 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5079 outs() << " version " << o.version << "\n";
5080 outs() << " flags " << format("0x%" PRIx32, o.flags);
5081 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5082 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5083 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5084 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5085 swift_version = (o.flags >> 8) & 0xff;
5086 if (swift_version != 0) {
5087 if (swift_version == 1)
5088 outs() << " Swift 1.0";
5089 else if (swift_version == 2)
5090 outs() << " Swift 1.1";
5092 outs() << " unknown future Swift version (" << swift_version << ")";
5097 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5098 uint32_t left, offset, p;
5099 struct imageInfo_t o;
5103 S.getName(SectName);
5104 DataRefImpl Ref = S.getRawDataRefImpl();
5105 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5106 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5108 r = get_pointer_32(p, offset, left, S, info);
5111 memset(&o, '\0', sizeof(struct imageInfo_t));
5112 if (left < sizeof(struct imageInfo_t)) {
5113 memcpy(&o, r, left);
5114 outs() << " (imageInfo entends past the end of the section)\n";
5116 memcpy(&o, r, sizeof(struct imageInfo_t));
5117 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5119 outs() << " version " << o.version << "\n";
5120 outs() << " flags " << format("0x%" PRIx32, o.flags);
5126 outs() << " GC-only";
5132 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5133 SymbolAddressMap AddrMap;
5135 CreateSymbolAddressMap(O, &AddrMap);
5137 std::vector<SectionRef> Sections;
5138 for (const SectionRef &Section : O->sections()) {
5140 Section.getName(SectName);
5141 Sections.push_back(Section);
5144 struct DisassembleInfo info;
5145 // Set up the block of info used by the Symbolizer call backs.
5146 info.verbose = verbose;
5148 info.AddrMap = &AddrMap;
5149 info.Sections = &Sections;
5150 info.class_name = nullptr;
5151 info.selector_name = nullptr;
5152 info.method = nullptr;
5153 info.demangled_name = nullptr;
5154 info.bindtable = nullptr;
5159 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5160 if (CL == SectionRef())
5161 CL = get_section(O, "__DATA", "__objc_classlist");
5163 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5165 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5166 if (CR == SectionRef())
5167 CR = get_section(O, "__DATA", "__objc_classrefs");
5169 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5171 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5172 if (SR == SectionRef())
5173 SR = get_section(O, "__DATA", "__objc_superrefs");
5175 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5177 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5178 if (CA == SectionRef())
5179 CA = get_section(O, "__DATA", "__objc_catlist");
5181 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5183 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5184 if (PL == SectionRef())
5185 PL = get_section(O, "__DATA", "__objc_protolist");
5187 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5189 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5190 if (MR == SectionRef())
5191 MR = get_section(O, "__DATA", "__objc_msgrefs");
5193 print_message_refs64(MR, &info);
5195 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5196 if (II == SectionRef())
5197 II = get_section(O, "__DATA", "__objc_imageinfo");
5199 print_image_info64(II, &info);
5201 if (info.bindtable != nullptr)
5202 delete info.bindtable;
5205 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5206 SymbolAddressMap AddrMap;
5208 CreateSymbolAddressMap(O, &AddrMap);
5210 std::vector<SectionRef> Sections;
5211 for (const SectionRef &Section : O->sections()) {
5213 Section.getName(SectName);
5214 Sections.push_back(Section);
5217 struct DisassembleInfo info;
5218 // Set up the block of info used by the Symbolizer call backs.
5219 info.verbose = verbose;
5221 info.AddrMap = &AddrMap;
5222 info.Sections = &Sections;
5223 info.class_name = nullptr;
5224 info.selector_name = nullptr;
5225 info.method = nullptr;
5226 info.demangled_name = nullptr;
5227 info.bindtable = nullptr;
5231 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5232 if (CL != SectionRef()) {
5234 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5236 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5238 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5241 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5242 if (CR != SectionRef()) {
5244 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5246 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5248 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5251 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5252 if (SR != SectionRef()) {
5254 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5256 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5258 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5261 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5262 if (CA != SectionRef()) {
5264 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5266 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5268 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5271 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5272 if (PL != SectionRef()) {
5274 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5276 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5278 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5281 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5282 if (MR != SectionRef()) {
5284 print_message_refs32(MR, &info);
5286 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5288 print_message_refs32(MR, &info);
5291 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5292 if (II != SectionRef()) {
5294 print_image_info32(II, &info);
5296 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5298 print_image_info32(II, &info);
5302 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5303 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5304 const char *r, *name, *defs;
5305 struct objc_module_t module;
5307 struct objc_symtab_t symtab;
5308 struct objc_class_t objc_class;
5309 struct objc_category_t objc_category;
5311 outs() << "Objective-C segment\n";
5312 S = get_section(O, "__OBJC", "__module_info");
5313 if (S == SectionRef())
5316 SymbolAddressMap AddrMap;
5318 CreateSymbolAddressMap(O, &AddrMap);
5320 std::vector<SectionRef> Sections;
5321 for (const SectionRef &Section : O->sections()) {
5323 Section.getName(SectName);
5324 Sections.push_back(Section);
5327 struct DisassembleInfo info;
5328 // Set up the block of info used by the Symbolizer call backs.
5329 info.verbose = verbose;
5331 info.AddrMap = &AddrMap;
5332 info.Sections = &Sections;
5333 info.class_name = nullptr;
5334 info.selector_name = nullptr;
5335 info.method = nullptr;
5336 info.demangled_name = nullptr;
5337 info.bindtable = nullptr;
5341 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5342 p = S.getAddress() + i;
5343 r = get_pointer_32(p, offset, left, S, &info, true);
5346 memset(&module, '\0', sizeof(struct objc_module_t));
5347 if (left < sizeof(struct objc_module_t)) {
5348 memcpy(&module, r, left);
5349 outs() << " (module extends past end of __module_info section)\n";
5351 memcpy(&module, r, sizeof(struct objc_module_t));
5352 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5355 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5356 outs() << " version " << module.version << "\n";
5357 outs() << " size " << module.size << "\n";
5359 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5360 if (name != nullptr)
5361 outs() << format("%.*s", left, name);
5363 outs() << format("0x%08" PRIx32, module.name)
5364 << "(not in an __OBJC section)";
5367 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5368 if (module.symtab == 0 || r == nullptr) {
5369 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5370 << " (not in an __OBJC section)\n";
5373 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5374 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5377 if (left < sizeof(struct objc_symtab_t)) {
5378 memcpy(&symtab, r, left);
5379 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5381 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5382 if (left > sizeof(struct objc_symtab_t)) {
5383 defs_left = left - sizeof(struct objc_symtab_t);
5384 defs = r + sizeof(struct objc_symtab_t);
5387 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5390 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5391 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5392 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5394 outs() << " (not in an __OBJC section)";
5396 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5397 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5398 if (symtab.cls_def_cnt > 0)
5399 outs() << "\tClass Definitions\n";
5400 for (j = 0; j < symtab.cls_def_cnt; j++) {
5401 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5402 outs() << "\t(remaining class defs entries entends past the end of the "
5406 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5407 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5408 sys::swapByteOrder(def);
5410 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5411 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5413 if (left > sizeof(struct objc_class_t)) {
5415 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5417 outs() << " (entends past the end of the section)\n";
5418 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5419 memcpy(&objc_class, r, left);
5421 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5422 swapStruct(objc_class);
5423 print_objc_class_t(&objc_class, &info);
5425 outs() << "(not in an __OBJC section)\n";
5428 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5429 outs() << "\tMeta Class";
5430 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5432 if (left > sizeof(struct objc_class_t)) {
5434 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5436 outs() << " (entends past the end of the section)\n";
5437 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5438 memcpy(&objc_class, r, left);
5440 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5441 swapStruct(objc_class);
5442 print_objc_class_t(&objc_class, &info);
5444 outs() << "(not in an __OBJC section)\n";
5448 if (symtab.cat_def_cnt > 0)
5449 outs() << "\tCategory Definitions\n";
5450 for (j = 0; j < symtab.cat_def_cnt; j++) {
5451 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5452 outs() << "\t(remaining category defs entries entends past the end of "
5453 << "the section)\n";
5456 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5458 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5459 sys::swapByteOrder(def);
5461 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5462 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5463 << format("0x%08" PRIx32, def);
5465 if (left > sizeof(struct objc_category_t)) {
5467 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5469 outs() << " (entends past the end of the section)\n";
5470 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5471 memcpy(&objc_category, r, left);
5473 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5474 swapStruct(objc_category);
5475 print_objc_objc_category_t(&objc_category, &info);
5477 outs() << "(not in an __OBJC section)\n";
5481 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5482 if (II != SectionRef())
5483 print_image_info(II, &info);
5488 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5489 uint32_t size, uint32_t addr) {
5490 SymbolAddressMap AddrMap;
5491 CreateSymbolAddressMap(O, &AddrMap);
5493 std::vector<SectionRef> Sections;
5494 for (const SectionRef &Section : O->sections()) {
5496 Section.getName(SectName);
5497 Sections.push_back(Section);
5500 struct DisassembleInfo info;
5501 // Set up the block of info used by the Symbolizer call backs.
5502 info.verbose = true;
5504 info.AddrMap = &AddrMap;
5505 info.Sections = &Sections;
5506 info.class_name = nullptr;
5507 info.selector_name = nullptr;
5508 info.method = nullptr;
5509 info.demangled_name = nullptr;
5510 info.bindtable = nullptr;
5515 struct objc_protocol_t protocol;
5516 uint32_t left, paddr;
5517 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5518 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5519 left = size - (p - sect);
5520 if (left < sizeof(struct objc_protocol_t)) {
5521 outs() << "Protocol extends past end of __protocol section\n";
5522 memcpy(&protocol, p, left);
5524 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5525 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5526 swapStruct(protocol);
5527 paddr = addr + (p - sect);
5528 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5529 if (print_protocol(paddr, 0, &info))
5530 outs() << "(not in an __OBJC section)\n";
5534 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5536 printObjc2_64bit_MetaData(O, verbose);
5538 MachO::mach_header H;
5540 if (H.cputype == MachO::CPU_TYPE_ARM)
5541 printObjc2_32bit_MetaData(O, verbose);
5543 // This is the 32-bit non-arm cputype case. Which is normally
5544 // the first Objective-C ABI. But it may be the case of a
5545 // binary for the iOS simulator which is the second Objective-C
5546 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5547 // and return false.
5548 if (!printObjc1_32bit_MetaData(O, verbose))
5549 printObjc2_32bit_MetaData(O, verbose);
5554 // GuessLiteralPointer returns a string which for the item in the Mach-O file
5555 // for the address passed in as ReferenceValue for printing as a comment with
5556 // the instruction and also returns the corresponding type of that item
5557 // indirectly through ReferenceType.
5559 // If ReferenceValue is an address of literal cstring then a pointer to the
5560 // cstring is returned and ReferenceType is set to
5561 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5563 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5564 // Class ref that name is returned and the ReferenceType is set accordingly.
5566 // Lastly, literals which are Symbol address in a literal pool are looked for
5567 // and if found the symbol name is returned and ReferenceType is set to
5568 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5570 // If there is no item in the Mach-O file for the address passed in as
5571 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
5572 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5573 uint64_t ReferencePC,
5574 uint64_t *ReferenceType,
5575 struct DisassembleInfo *info) {
5576 // First see if there is an external relocation entry at the ReferencePC.
5577 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
5578 uint64_t sect_addr = info->S.getAddress();
5579 uint64_t sect_offset = ReferencePC - sect_addr;
5580 bool reloc_found = false;
5582 MachO::any_relocation_info RE;
5583 bool isExtern = false;
5585 for (const RelocationRef &Reloc : info->S.relocations()) {
5586 uint64_t RelocOffset = Reloc.getOffset();
5587 if (RelocOffset == sect_offset) {
5588 Rel = Reloc.getRawDataRefImpl();
5589 RE = info->O->getRelocation(Rel);
5590 if (info->O->isRelocationScattered(RE))
5592 isExtern = info->O->getPlainRelocationExternal(RE);
5594 symbol_iterator RelocSym = Reloc.getSymbol();
5601 // If there is an external relocation entry for a symbol in a section
5602 // then used that symbol's value for the value of the reference.
5603 if (reloc_found && isExtern) {
5604 if (info->O->getAnyRelocationPCRel(RE)) {
5605 unsigned Type = info->O->getAnyRelocationType(RE);
5606 if (Type == MachO::X86_64_RELOC_SIGNED) {
5607 ReferenceValue = Symbol.getValue();
5613 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5614 // Message refs and Class refs.
5615 bool classref, selref, msgref, cfstring;
5616 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5617 selref, msgref, cfstring);
5618 if (classref && pointer_value == 0) {
5619 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5620 // And the pointer_value in that section is typically zero as it will be
5621 // set by dyld as part of the "bind information".
5622 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5623 if (name != nullptr) {
5624 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5625 const char *class_name = strrchr(name, '$');
5626 if (class_name != nullptr && class_name[1] == '_' &&
5627 class_name[2] != '\0') {
5628 info->class_name = class_name + 2;
5635 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5637 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5638 if (name != nullptr)
5639 info->class_name = name;
5641 name = "bad class ref";
5646 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5647 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5651 if (selref && pointer_value == 0)
5652 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5654 if (pointer_value != 0)
5655 ReferenceValue = pointer_value;
5657 const char *name = GuessCstringPointer(ReferenceValue, info);
5659 if (pointer_value != 0 && selref) {
5660 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5661 info->selector_name = name;
5662 } else if (pointer_value != 0 && msgref) {
5663 info->class_name = nullptr;
5664 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5665 info->selector_name = name;
5667 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5671 // Lastly look for an indirect symbol with this ReferenceValue which is in
5672 // a literal pool. If found return that symbol name.
5673 name = GuessIndirectSymbol(ReferenceValue, info);
5675 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5682 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
5683 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
5684 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5685 // is created and returns the symbol name that matches the ReferenceValue or
5686 // nullptr if none. The ReferenceType is passed in for the IN type of
5687 // reference the instruction is making from the values in defined in the header
5688 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5689 // Out type and the ReferenceName will also be set which is added as a comment
5690 // to the disassembled instruction.
5693 // If the symbol name is a C++ mangled name then the demangled name is
5694 // returned through ReferenceName and ReferenceType is set to
5695 // LLVMDisassembler_ReferenceType_DeMangled_Name .
5698 // When this is called to get a symbol name for a branch target then the
5699 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5700 // SymbolValue will be looked for in the indirect symbol table to determine if
5701 // it is an address for a symbol stub. If so then the symbol name for that
5702 // stub is returned indirectly through ReferenceName and then ReferenceType is
5703 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5705 // When this is called with an value loaded via a PC relative load then
5706 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5707 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
5708 // or an Objective-C meta data reference. If so the output ReferenceType is
5709 // set to correspond to that as well as setting the ReferenceName.
5710 static const char *SymbolizerSymbolLookUp(void *DisInfo,
5711 uint64_t ReferenceValue,
5712 uint64_t *ReferenceType,
5713 uint64_t ReferencePC,
5714 const char **ReferenceName) {
5715 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
5716 // If no verbose symbolic information is wanted then just return nullptr.
5717 if (!info->verbose) {
5718 *ReferenceName = nullptr;
5719 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5723 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
5725 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5726 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
5727 if (*ReferenceName != nullptr) {
5728 method_reference(info, ReferenceType, ReferenceName);
5729 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5730 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5733 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5734 if (info->demangled_name != nullptr)
5735 free(info->demangled_name);
5737 info->demangled_name =
5738 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5739 if (info->demangled_name != nullptr) {
5740 *ReferenceName = info->demangled_name;
5741 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5743 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5746 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5747 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5749 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5751 method_reference(info, ReferenceType, ReferenceName);
5753 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5754 // If this is arm64 and the reference is an adrp instruction save the
5755 // instruction, passed in ReferenceValue and the address of the instruction
5756 // for use later if we see and add immediate instruction.
5757 } else if (info->O->getArch() == Triple::aarch64 &&
5758 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5759 info->adrp_inst = ReferenceValue;
5760 info->adrp_addr = ReferencePC;
5761 SymbolName = nullptr;
5762 *ReferenceName = nullptr;
5763 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5764 // If this is arm64 and reference is an add immediate instruction and we
5766 // seen an adrp instruction just before it and the adrp's Xd register
5768 // this add's Xn register reconstruct the value being referenced and look to
5769 // see if it is a literal pointer. Note the add immediate instruction is
5770 // passed in ReferenceValue.
5771 } else if (info->O->getArch() == Triple::aarch64 &&
5772 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5773 ReferencePC - 4 == info->adrp_addr &&
5774 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5775 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5776 uint32_t addxri_inst;
5777 uint64_t adrp_imm, addxri_imm;
5780 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5781 if (info->adrp_inst & 0x0200000)
5782 adrp_imm |= 0xfffffffffc000000LL;
5784 addxri_inst = ReferenceValue;
5785 addxri_imm = (addxri_inst >> 10) & 0xfff;
5786 if (((addxri_inst >> 22) & 0x3) == 1)
5789 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5790 (adrp_imm << 12) + addxri_imm;
5793 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5794 if (*ReferenceName == nullptr)
5795 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5796 // If this is arm64 and the reference is a load register instruction and we
5797 // have seen an adrp instruction just before it and the adrp's Xd register
5798 // matches this add's Xn register reconstruct the value being referenced and
5799 // look to see if it is a literal pointer. Note the load register
5800 // instruction is passed in ReferenceValue.
5801 } else if (info->O->getArch() == Triple::aarch64 &&
5802 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5803 ReferencePC - 4 == info->adrp_addr &&
5804 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5805 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5806 uint32_t ldrxui_inst;
5807 uint64_t adrp_imm, ldrxui_imm;
5810 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5811 if (info->adrp_inst & 0x0200000)
5812 adrp_imm |= 0xfffffffffc000000LL;
5814 ldrxui_inst = ReferenceValue;
5815 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5817 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5818 (adrp_imm << 12) + (ldrxui_imm << 3);
5821 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5822 if (*ReferenceName == nullptr)
5823 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5825 // If this arm64 and is an load register (PC-relative) instruction the
5826 // ReferenceValue is the PC plus the immediate value.
5827 else if (info->O->getArch() == Triple::aarch64 &&
5828 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5829 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5831 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5832 if (*ReferenceName == nullptr)
5833 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5836 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5837 if (info->demangled_name != nullptr)
5838 free(info->demangled_name);
5840 info->demangled_name =
5841 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5842 if (info->demangled_name != nullptr) {
5843 *ReferenceName = info->demangled_name;
5844 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5849 *ReferenceName = nullptr;
5850 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5856 /// \brief Emits the comments that are stored in the CommentStream.
5857 /// Each comment in the CommentStream must end with a newline.
5858 static void emitComments(raw_svector_ostream &CommentStream,
5859 SmallString<128> &CommentsToEmit,
5860 formatted_raw_ostream &FormattedOS,
5861 const MCAsmInfo &MAI) {
5862 // Flush the stream before taking its content.
5863 StringRef Comments = CommentsToEmit.str();
5864 // Get the default information for printing a comment.
5865 const char *CommentBegin = MAI.getCommentString();
5866 unsigned CommentColumn = MAI.getCommentColumn();
5867 bool IsFirst = true;
5868 while (!Comments.empty()) {
5870 FormattedOS << '\n';
5871 // Emit a line of comments.
5872 FormattedOS.PadToColumn(CommentColumn);
5873 size_t Position = Comments.find('\n');
5874 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5875 // Move after the newline character.
5876 Comments = Comments.substr(Position + 1);
5879 FormattedOS.flush();
5881 // Tell the comment stream that the vector changed underneath it.
5882 CommentsToEmit.clear();
5885 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5886 StringRef DisSegName, StringRef DisSectName) {
5887 const char *McpuDefault = nullptr;
5888 const Target *ThumbTarget = nullptr;
5889 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
5891 // GetTarget prints out stuff.
5894 if (MCPU.empty() && McpuDefault)
5897 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
5898 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
5900 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
5902 // Package up features to be passed to target/subtarget
5903 std::string FeaturesStr;
5904 if (MAttrs.size()) {
5905 SubtargetFeatures Features;
5906 for (unsigned i = 0; i != MAttrs.size(); ++i)
5907 Features.AddFeature(MAttrs[i]);
5908 FeaturesStr = Features.getString();
5911 // Set up disassembler.
5912 std::unique_ptr<const MCRegisterInfo> MRI(
5913 TheTarget->createMCRegInfo(TripleName));
5914 std::unique_ptr<const MCAsmInfo> AsmInfo(
5915 TheTarget->createMCAsmInfo(*MRI, TripleName));
5916 std::unique_ptr<const MCSubtargetInfo> STI(
5917 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
5918 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
5919 std::unique_ptr<MCDisassembler> DisAsm(
5920 TheTarget->createMCDisassembler(*STI, Ctx));
5921 std::unique_ptr<MCSymbolizer> Symbolizer;
5922 struct DisassembleInfo SymbolizerInfo;
5923 std::unique_ptr<MCRelocationInfo> RelInfo(
5924 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5926 Symbolizer.reset(TheTarget->createMCSymbolizer(
5927 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5928 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
5929 DisAsm->setSymbolizer(std::move(Symbolizer));
5931 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
5932 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
5933 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
5934 // Set the display preference for hex vs. decimal immediates.
5935 IP->setPrintImmHex(PrintImmHex);
5936 // Comment stream and backing vector.
5937 SmallString<128> CommentsToEmit;
5938 raw_svector_ostream CommentStream(CommentsToEmit);
5939 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5940 // if it is done then arm64 comments for string literals don't get printed
5941 // and some constant get printed instead and not setting it causes intel
5942 // (32-bit and 64-bit) comments printed with different spacing before the
5943 // comment causing different diffs with the 'C' disassembler library API.
5944 // IP->setCommentStream(CommentStream);
5946 if (!AsmInfo || !STI || !DisAsm || !IP) {
5947 errs() << "error: couldn't initialize disassembler for target "
5948 << TripleName << '\n';
5952 // Set up thumb disassembler.
5953 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5954 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5955 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
5956 std::unique_ptr<MCDisassembler> ThumbDisAsm;
5957 std::unique_ptr<MCInstPrinter> ThumbIP;
5958 std::unique_ptr<MCContext> ThumbCtx;
5959 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5960 struct DisassembleInfo ThumbSymbolizerInfo;
5961 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
5963 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
5965 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
5967 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
5968 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
5969 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
5970 MCContext *PtrThumbCtx = ThumbCtx.get();
5972 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
5974 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
5975 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5976 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
5977 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
5979 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
5980 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
5981 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
5982 *ThumbInstrInfo, *ThumbMRI));
5983 // Set the display preference for hex vs. decimal immediates.
5984 ThumbIP->setPrintImmHex(PrintImmHex);
5987 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
5988 errs() << "error: couldn't initialize disassembler for target "
5989 << ThumbTripleName << '\n';
5993 MachO::mach_header Header = MachOOF->getHeader();
5995 // FIXME: Using the -cfg command line option, this code used to be able to
5996 // annotate relocations with the referenced symbol's name, and if this was
5997 // inside a __[cf]string section, the data it points to. This is now replaced
5998 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
5999 std::vector<SectionRef> Sections;
6000 std::vector<SymbolRef> Symbols;
6001 SmallVector<uint64_t, 8> FoundFns;
6002 uint64_t BaseSegmentAddress;
6004 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
6005 BaseSegmentAddress);
6007 // Sort the symbols by address, just in case they didn't come in that way.
6008 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
6010 // Build a data in code table that is sorted on by the address of each entry.
6011 uint64_t BaseAddress = 0;
6012 if (Header.filetype == MachO::MH_OBJECT)
6013 BaseAddress = Sections[0].getAddress();
6015 BaseAddress = BaseSegmentAddress;
6017 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
6020 DI->getOffset(Offset);
6021 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6023 array_pod_sort(Dices.begin(), Dices.end());
6026 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6028 raw_ostream &DebugOut = nulls();
6031 std::unique_ptr<DIContext> diContext;
6032 ObjectFile *DbgObj = MachOOF;
6033 // Try to find debug info and set up the DIContext for it.
6035 // A separate DSym file path was specified, parse it as a macho file,
6036 // get the sections and supply it to the section name parsing machinery.
6037 if (!DSYMFile.empty()) {
6038 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
6039 MemoryBuffer::getFileOrSTDIN(DSYMFile);
6040 if (std::error_code EC = BufOrErr.getError()) {
6041 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
6045 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6050 // Setup the DIContext
6051 diContext.reset(new DWARFContextInMemory(*DbgObj));
6054 if (FilterSections.size() == 0)
6055 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
6057 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
6059 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6062 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
6064 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
6065 if (SegmentName != DisSegName)
6069 Sections[SectIdx].getContents(BytesStr);
6070 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6072 uint64_t SectAddress = Sections[SectIdx].getAddress();
6074 bool symbolTableWorked = false;
6076 // Create a map of symbol addresses to symbol names for use by
6077 // the SymbolizerSymbolLookUp() routine.
6078 SymbolAddressMap AddrMap;
6079 bool DisSymNameFound = false;
6080 for (const SymbolRef &Symbol : MachOOF->symbols()) {
6081 SymbolRef::Type ST = Symbol.getType();
6082 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6083 ST == SymbolRef::ST_Other) {
6084 uint64_t Address = Symbol.getValue();
6085 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6086 if (std::error_code EC = SymNameOrErr.getError())
6087 report_fatal_error(EC.message());
6088 StringRef SymName = *SymNameOrErr;
6089 AddrMap[Address] = SymName;
6090 if (!DisSymName.empty() && DisSymName == SymName)
6091 DisSymNameFound = true;
6094 if (!DisSymName.empty() && !DisSymNameFound) {
6095 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6098 // Set up the block of info used by the Symbolizer call backs.
6099 SymbolizerInfo.verbose = !NoSymbolicOperands;
6100 SymbolizerInfo.O = MachOOF;
6101 SymbolizerInfo.S = Sections[SectIdx];
6102 SymbolizerInfo.AddrMap = &AddrMap;
6103 SymbolizerInfo.Sections = &Sections;
6104 SymbolizerInfo.class_name = nullptr;
6105 SymbolizerInfo.selector_name = nullptr;
6106 SymbolizerInfo.method = nullptr;
6107 SymbolizerInfo.demangled_name = nullptr;
6108 SymbolizerInfo.bindtable = nullptr;
6109 SymbolizerInfo.adrp_addr = 0;
6110 SymbolizerInfo.adrp_inst = 0;
6111 // Same for the ThumbSymbolizer
6112 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
6113 ThumbSymbolizerInfo.O = MachOOF;
6114 ThumbSymbolizerInfo.S = Sections[SectIdx];
6115 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6116 ThumbSymbolizerInfo.Sections = &Sections;
6117 ThumbSymbolizerInfo.class_name = nullptr;
6118 ThumbSymbolizerInfo.selector_name = nullptr;
6119 ThumbSymbolizerInfo.method = nullptr;
6120 ThumbSymbolizerInfo.demangled_name = nullptr;
6121 ThumbSymbolizerInfo.bindtable = nullptr;
6122 ThumbSymbolizerInfo.adrp_addr = 0;
6123 ThumbSymbolizerInfo.adrp_inst = 0;
6125 // Disassemble symbol by symbol.
6126 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
6127 ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6128 if (std::error_code EC = SymNameOrErr.getError())
6129 report_fatal_error(EC.message());
6130 StringRef SymName = *SymNameOrErr;
6132 SymbolRef::Type ST = Symbols[SymIdx].getType();
6133 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
6136 // Make sure the symbol is defined in this section.
6137 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
6141 // If we are only disassembling one symbol see if this is that symbol.
6142 if (!DisSymName.empty() && DisSymName != SymName)
6145 // Start at the address of the symbol relative to the section's address.
6146 uint64_t Start = Symbols[SymIdx].getValue();
6147 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6148 Start -= SectionAddress;
6150 // Stop disassembling either at the beginning of the next symbol or at
6151 // the end of the section.
6152 bool containsNextSym = false;
6153 uint64_t NextSym = 0;
6154 uint64_t NextSymIdx = SymIdx + 1;
6155 while (Symbols.size() > NextSymIdx) {
6156 SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
6157 if (NextSymType == SymbolRef::ST_Function) {
6159 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
6160 NextSym = Symbols[NextSymIdx].getValue();
6161 NextSym -= SectionAddress;
6167 uint64_t SectSize = Sections[SectIdx].getSize();
6168 uint64_t End = containsNextSym ? NextSym : SectSize;
6171 symbolTableWorked = true;
6173 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6175 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6177 outs() << SymName << ":\n";
6178 DILineInfo lastLine;
6179 for (uint64_t Index = Start; Index < End; Index += Size) {
6182 uint64_t PC = SectAddress + Index;
6183 if (!NoLeadingAddr) {
6184 if (FullLeadingAddr) {
6185 if (MachOOF->is64Bit())
6186 outs() << format("%016" PRIx64, PC);
6188 outs() << format("%08" PRIx64, PC);
6190 outs() << format("%8" PRIx64 ":", PC);
6196 // Check the data in code table here to see if this is data not an
6197 // instruction to be disassembled.
6199 Dice.push_back(std::make_pair(PC, DiceRef()));
6200 dice_table_iterator DTI =
6201 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6202 compareDiceTableEntries);
6203 if (DTI != Dices.end()) {
6205 DTI->second.getLength(Length);
6207 DTI->second.getKind(Kind);
6208 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
6209 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6210 (PC == (DTI->first + Length - 1)) && (Length & 1))
6215 SmallVector<char, 64> AnnotationsBytes;
6216 raw_svector_ostream Annotations(AnnotationsBytes);
6220 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
6221 PC, DebugOut, Annotations);
6223 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
6224 DebugOut, Annotations);
6226 if (!NoShowRawInsn) {
6227 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
6229 formatted_raw_ostream FormattedOS(outs());
6230 StringRef AnnotationsStr = Annotations.str();
6232 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
6234 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
6235 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
6237 // Print debug info.
6239 DILineInfo dli = diContext->getLineInfoForAddress(PC);
6240 // Print valid line info if it changed.
6241 if (dli != lastLine && dli.Line != 0)
6242 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6248 unsigned int Arch = MachOOF->getArch();
6249 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6250 outs() << format("\t.byte 0x%02x #bad opcode\n",
6251 *(Bytes.data() + Index) & 0xff);
6252 Size = 1; // skip exactly one illegible byte and move on.
6253 } else if (Arch == Triple::aarch64) {
6254 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6255 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6256 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6257 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6258 outs() << format("\t.long\t0x%08x\n", opcode);
6261 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6263 Size = 1; // skip illegible bytes
6268 if (!symbolTableWorked) {
6269 // Reading the symbol table didn't work, disassemble the whole section.
6270 uint64_t SectAddress = Sections[SectIdx].getAddress();
6271 uint64_t SectSize = Sections[SectIdx].getSize();
6273 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
6276 uint64_t PC = SectAddress + Index;
6277 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6278 DebugOut, nulls())) {
6279 if (!NoLeadingAddr) {
6280 if (FullLeadingAddr) {
6281 if (MachOOF->is64Bit())
6282 outs() << format("%016" PRIx64, PC);
6284 outs() << format("%08" PRIx64, PC);
6286 outs() << format("%8" PRIx64 ":", PC);
6289 if (!NoShowRawInsn) {
6291 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
6293 IP->printInst(&Inst, outs(), "", *STI);
6296 unsigned int Arch = MachOOF->getArch();
6297 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6298 outs() << format("\t.byte 0x%02x #bad opcode\n",
6299 *(Bytes.data() + Index) & 0xff);
6300 InstSize = 1; // skip exactly one illegible byte and move on.
6302 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6304 InstSize = 1; // skip illegible bytes
6309 // The TripleName's need to be reset if we are called again for a different
6312 ThumbTripleName = "";
6314 if (SymbolizerInfo.method != nullptr)
6315 free(SymbolizerInfo.method);
6316 if (SymbolizerInfo.demangled_name != nullptr)
6317 free(SymbolizerInfo.demangled_name);
6318 if (SymbolizerInfo.bindtable != nullptr)
6319 delete SymbolizerInfo.bindtable;
6320 if (ThumbSymbolizerInfo.method != nullptr)
6321 free(ThumbSymbolizerInfo.method);
6322 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6323 free(ThumbSymbolizerInfo.demangled_name);
6324 if (ThumbSymbolizerInfo.bindtable != nullptr)
6325 delete ThumbSymbolizerInfo.bindtable;
6329 //===----------------------------------------------------------------------===//
6330 // __compact_unwind section dumping
6331 //===----------------------------------------------------------------------===//
6335 template <typename T> static uint64_t readNext(const char *&Buf) {
6336 using llvm::support::little;
6337 using llvm::support::unaligned;
6339 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6344 struct CompactUnwindEntry {
6345 uint32_t OffsetInSection;
6347 uint64_t FunctionAddr;
6349 uint32_t CompactEncoding;
6350 uint64_t PersonalityAddr;
6353 RelocationRef FunctionReloc;
6354 RelocationRef PersonalityReloc;
6355 RelocationRef LSDAReloc;
6357 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
6358 : OffsetInSection(Offset) {
6360 read<uint64_t>(Contents.data() + Offset);
6362 read<uint32_t>(Contents.data() + Offset);
6366 template <typename UIntPtr> void read(const char *Buf) {
6367 FunctionAddr = readNext<UIntPtr>(Buf);
6368 Length = readNext<uint32_t>(Buf);
6369 CompactEncoding = readNext<uint32_t>(Buf);
6370 PersonalityAddr = readNext<UIntPtr>(Buf);
6371 LSDAAddr = readNext<UIntPtr>(Buf);
6376 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
6377 /// and data being relocated, determine the best base Name and Addend to use for
6378 /// display purposes.
6380 /// 1. An Extern relocation will directly reference a symbol (and the data is
6381 /// then already an addend), so use that.
6382 /// 2. Otherwise the data is an offset in the object file's layout; try to find
6383 // a symbol before it in the same section, and use the offset from there.
6384 /// 3. Finally, if all that fails, fall back to an offset from the start of the
6385 /// referenced section.
6386 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6387 std::map<uint64_t, SymbolRef> &Symbols,
6388 const RelocationRef &Reloc, uint64_t Addr,
6389 StringRef &Name, uint64_t &Addend) {
6390 if (Reloc.getSymbol() != Obj->symbol_end()) {
6391 ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6392 if (std::error_code EC = NameOrErr.getError())
6393 report_fatal_error(EC.message());
6399 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
6400 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
6402 uint64_t SectionAddr = RelocSection.getAddress();
6404 auto Sym = Symbols.upper_bound(Addr);
6405 if (Sym == Symbols.begin()) {
6406 // The first symbol in the object is after this reference, the best we can
6407 // do is section-relative notation.
6408 RelocSection.getName(Name);
6409 Addend = Addr - SectionAddr;
6413 // Go back one so that SymbolAddress <= Addr.
6416 section_iterator SymSection = *Sym->second.getSection();
6417 if (RelocSection == *SymSection) {
6418 // There's a valid symbol in the same section before this reference.
6419 ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6420 if (std::error_code EC = NameOrErr.getError())
6421 report_fatal_error(EC.message());
6423 Addend = Addr - Sym->first;
6427 // There is a symbol before this reference, but it's in a different
6428 // section. Probably not helpful to mention it, so use the section name.
6429 RelocSection.getName(Name);
6430 Addend = Addr - SectionAddr;
6433 static void printUnwindRelocDest(const MachOObjectFile *Obj,
6434 std::map<uint64_t, SymbolRef> &Symbols,
6435 const RelocationRef &Reloc, uint64_t Addr) {
6439 if (!Reloc.getObject())
6442 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6446 outs() << " + " << format("0x%" PRIx64, Addend);
6450 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6451 std::map<uint64_t, SymbolRef> &Symbols,
6452 const SectionRef &CompactUnwind) {
6454 assert(Obj->isLittleEndian() &&
6455 "There should not be a big-endian .o with __compact_unwind");
6457 bool Is64 = Obj->is64Bit();
6458 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6459 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6462 CompactUnwind.getContents(Contents);
6464 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6466 // First populate the initial raw offsets, encodings and so on from the entry.
6467 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6468 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6469 CompactUnwinds.push_back(Entry);
6472 // Next we need to look at the relocations to find out what objects are
6473 // actually being referred to.
6474 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
6475 uint64_t RelocAddress = Reloc.getOffset();
6477 uint32_t EntryIdx = RelocAddress / EntrySize;
6478 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6479 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6481 if (OffsetInEntry == 0)
6482 Entry.FunctionReloc = Reloc;
6483 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6484 Entry.PersonalityReloc = Reloc;
6485 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6486 Entry.LSDAReloc = Reloc;
6488 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6491 // Finally, we're ready to print the data we've gathered.
6492 outs() << "Contents of __compact_unwind section:\n";
6493 for (auto &Entry : CompactUnwinds) {
6494 outs() << " Entry at offset "
6495 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
6497 // 1. Start of the region this entry applies to.
6498 outs() << " start: " << format("0x%" PRIx64,
6499 Entry.FunctionAddr) << ' ';
6500 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
6503 // 2. Length of the region this entry applies to.
6504 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6506 // 3. The 32-bit compact encoding.
6507 outs() << " compact encoding: "
6508 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
6510 // 4. The personality function, if present.
6511 if (Entry.PersonalityReloc.getObject()) {
6512 outs() << " personality function: "
6513 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
6514 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6515 Entry.PersonalityAddr);
6519 // 5. This entry's language-specific data area.
6520 if (Entry.LSDAReloc.getObject()) {
6521 outs() << " LSDA: " << format("0x%" PRIx64,
6522 Entry.LSDAAddr) << ' ';
6523 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6529 //===----------------------------------------------------------------------===//
6530 // __unwind_info section dumping
6531 //===----------------------------------------------------------------------===//
6533 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6534 const char *Pos = PageStart;
6535 uint32_t Kind = readNext<uint32_t>(Pos);
6537 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6539 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6540 uint16_t NumEntries = readNext<uint16_t>(Pos);
6542 Pos = PageStart + EntriesStart;
6543 for (unsigned i = 0; i < NumEntries; ++i) {
6544 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6545 uint32_t Encoding = readNext<uint32_t>(Pos);
6547 outs() << " [" << i << "]: "
6548 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6550 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
6554 static void printCompressedSecondLevelUnwindPage(
6555 const char *PageStart, uint32_t FunctionBase,
6556 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6557 const char *Pos = PageStart;
6558 uint32_t Kind = readNext<uint32_t>(Pos);
6560 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6562 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6563 uint16_t NumEntries = readNext<uint16_t>(Pos);
6565 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6566 readNext<uint16_t>(Pos);
6567 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6568 PageStart + EncodingsStart);
6570 Pos = PageStart + EntriesStart;
6571 for (unsigned i = 0; i < NumEntries; ++i) {
6572 uint32_t Entry = readNext<uint32_t>(Pos);
6573 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6574 uint32_t EncodingIdx = Entry >> 24;
6577 if (EncodingIdx < CommonEncodings.size())
6578 Encoding = CommonEncodings[EncodingIdx];
6580 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6582 outs() << " [" << i << "]: "
6583 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6585 << "encoding[" << EncodingIdx
6586 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
6590 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6591 std::map<uint64_t, SymbolRef> &Symbols,
6592 const SectionRef &UnwindInfo) {
6594 assert(Obj->isLittleEndian() &&
6595 "There should not be a big-endian .o with __unwind_info");
6597 outs() << "Contents of __unwind_info section:\n";
6600 UnwindInfo.getContents(Contents);
6601 const char *Pos = Contents.data();
6603 //===----------------------------------
6605 //===----------------------------------
6607 uint32_t Version = readNext<uint32_t>(Pos);
6608 outs() << " Version: "
6609 << format("0x%" PRIx32, Version) << '\n';
6610 assert(Version == 1 && "only understand version 1");
6612 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6613 outs() << " Common encodings array section offset: "
6614 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6615 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6616 outs() << " Number of common encodings in array: "
6617 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6619 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6620 outs() << " Personality function array section offset: "
6621 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6622 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6623 outs() << " Number of personality functions in array: "
6624 << format("0x%" PRIx32, NumPersonalities) << '\n';
6626 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6627 outs() << " Index array section offset: "
6628 << format("0x%" PRIx32, IndicesStart) << '\n';
6629 uint32_t NumIndices = readNext<uint32_t>(Pos);
6630 outs() << " Number of indices in array: "
6631 << format("0x%" PRIx32, NumIndices) << '\n';
6633 //===----------------------------------
6634 // A shared list of common encodings
6635 //===----------------------------------
6637 // These occupy indices in the range [0, N] whenever an encoding is referenced
6638 // from a compressed 2nd level index table. In practice the linker only
6639 // creates ~128 of these, so that indices are available to embed encodings in
6640 // the 2nd level index.
6642 SmallVector<uint32_t, 64> CommonEncodings;
6643 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6644 Pos = Contents.data() + CommonEncodingsStart;
6645 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6646 uint32_t Encoding = readNext<uint32_t>(Pos);
6647 CommonEncodings.push_back(Encoding);
6649 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6653 //===----------------------------------
6654 // Personality functions used in this executable
6655 //===----------------------------------
6657 // There should be only a handful of these (one per source language,
6658 // roughly). Particularly since they only get 2 bits in the compact encoding.
6660 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6661 Pos = Contents.data() + PersonalitiesStart;
6662 for (unsigned i = 0; i < NumPersonalities; ++i) {
6663 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6664 outs() << " personality[" << i + 1
6665 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6668 //===----------------------------------
6669 // The level 1 index entries
6670 //===----------------------------------
6672 // These specify an approximate place to start searching for the more detailed
6673 // information, sorted by PC.
6676 uint32_t FunctionOffset;
6677 uint32_t SecondLevelPageStart;
6681 SmallVector<IndexEntry, 4> IndexEntries;
6683 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6684 Pos = Contents.data() + IndicesStart;
6685 for (unsigned i = 0; i < NumIndices; ++i) {
6688 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6689 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6690 Entry.LSDAStart = readNext<uint32_t>(Pos);
6691 IndexEntries.push_back(Entry);
6693 outs() << " [" << i << "]: "
6694 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6696 << "2nd level page offset="
6697 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
6698 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
6701 //===----------------------------------
6702 // Next come the LSDA tables
6703 //===----------------------------------
6705 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6706 // the first top-level index's LSDAOffset to the last (sentinel).
6708 outs() << " LSDA descriptors:\n";
6709 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6710 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6711 (2 * sizeof(uint32_t));
6712 for (int i = 0; i < NumLSDAs; ++i) {
6713 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6714 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6715 outs() << " [" << i << "]: "
6716 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6718 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
6721 //===----------------------------------
6722 // Finally, the 2nd level indices
6723 //===----------------------------------
6725 // Generally these are 4K in size, and have 2 possible forms:
6726 // + Regular stores up to 511 entries with disparate encodings
6727 // + Compressed stores up to 1021 entries if few enough compact encoding
6729 outs() << " Second level indices:\n";
6730 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6731 // The final sentinel top-level index has no associated 2nd level page
6732 if (IndexEntries[i].SecondLevelPageStart == 0)
6735 outs() << " Second level index[" << i << "]: "
6736 << "offset in section="
6737 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6739 << "base function offset="
6740 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6742 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
6743 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
6745 printRegularSecondLevelUnwindPage(Pos);
6747 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6750 llvm_unreachable("Do not know how to print this kind of 2nd level page");
6754 static unsigned getSizeForEncoding(bool is64Bit,
6755 unsigned symbolEncoding) {
6756 unsigned format = symbolEncoding & 0x0f;
6758 default: llvm_unreachable("Unknown Encoding");
6759 case dwarf::DW_EH_PE_absptr:
6760 case dwarf::DW_EH_PE_signed:
6761 return is64Bit ? 8 : 4;
6762 case dwarf::DW_EH_PE_udata2:
6763 case dwarf::DW_EH_PE_sdata2:
6765 case dwarf::DW_EH_PE_udata4:
6766 case dwarf::DW_EH_PE_sdata4:
6768 case dwarf::DW_EH_PE_udata8:
6769 case dwarf::DW_EH_PE_sdata8:
6774 static uint64_t readPointer(const char *&Pos, bool is64Bit, unsigned Encoding) {
6775 switch (getSizeForEncoding(is64Bit, Encoding)) {
6777 return readNext<uint16_t>(Pos);
6780 return readNext<uint32_t>(Pos);
6783 return readNext<uint64_t>(Pos);
6786 llvm_unreachable("Illegal data size");
6790 static void printMachOEHFrameSection(const MachOObjectFile *Obj,
6791 std::map<uint64_t, SymbolRef> &Symbols,
6792 const SectionRef &EHFrame) {
6793 if (!Obj->isLittleEndian()) {
6794 outs() << "warning: cannot handle big endian __eh_frame section\n";
6798 bool is64Bit = Obj->is64Bit();
6800 outs() << "Contents of __eh_frame section:\n";
6803 EHFrame.getContents(Contents);
6805 /// A few fields of the CIE are used when decoding the FDE's. This struct
6806 /// will cache those fields we need so that we don't have to decode it
6807 /// repeatedly for each FDE that references it.
6809 Optional<uint32_t> FDEPointerEncoding;
6810 Optional<uint32_t> LSDAPointerEncoding;
6811 bool hasAugmentationLength;
6814 // Map from the start offset of the CIE to the cached data for that CIE.
6815 DenseMap<uint64_t, DecodedCIE> CachedCIEs;
6817 for (const char *Pos = Contents.data(), *End = Contents.end(); Pos != End; ) {
6819 const char *EntryStartPos = Pos;
6821 uint64_t Length = readNext<uint32_t>(Pos);
6822 if (Length == 0xffffffff)
6823 Length = readNext<uint64_t>(Pos);
6825 // Save the Pos so that we can check the length we encoded against what we
6827 const char *PosAfterLength = Pos;
6828 const char *EntryEndPos = PosAfterLength + Length;
6830 assert(EntryEndPos <= End &&
6831 "__eh_frame entry length exceeds section size");
6833 uint32_t ID = readNext<uint32_t>(Pos);
6837 uint32_t Version = readNext<uint8_t>(Pos);
6839 // Parse a null terminated augmentation string
6840 SmallString<8> AugmentationString;
6841 for (uint8_t Char = readNext<uint8_t>(Pos); Char;
6842 Char = readNext<uint8_t>(Pos))
6843 AugmentationString.push_back(Char);
6845 // Optionally parse the EH data if the augmentation string says it's there.
6846 Optional<uint64_t> EHData;
6847 if (StringRef(AugmentationString).count("eh"))
6848 EHData = is64Bit ? readNext<uint64_t>(Pos) : readNext<uint32_t>(Pos);
6850 unsigned ULEBByteCount;
6851 uint64_t CodeAlignmentFactor = decodeULEB128((const uint8_t *)Pos,
6853 Pos += ULEBByteCount;
6855 int64_t DataAlignmentFactor = decodeSLEB128((const uint8_t *)Pos,
6857 Pos += ULEBByteCount;
6859 uint32_t ReturnAddressRegister = readNext<uint8_t>(Pos);
6861 Optional<uint64_t> AugmentationLength;
6862 Optional<uint32_t> LSDAPointerEncoding;
6863 Optional<uint32_t> PersonalityEncoding;
6864 Optional<uint64_t> Personality;
6865 Optional<uint32_t> FDEPointerEncoding;
6866 if (!AugmentationString.empty() && AugmentationString.front() == 'z') {
6867 AugmentationLength = decodeULEB128((const uint8_t *)Pos,
6869 Pos += ULEBByteCount;
6871 // Walk the augmentation string to get all the augmentation data.
6872 for (unsigned i = 1, e = AugmentationString.size(); i != e; ++i) {
6873 char Char = AugmentationString[i];
6876 assert((i + 1) != e && AugmentationString[i + 1] == 'h' &&
6877 "Expected 'eh' in augmentation string");
6880 assert(!LSDAPointerEncoding && "Duplicate LSDA encoding");
6881 LSDAPointerEncoding = readNext<uint8_t>(Pos);
6884 assert(!Personality && "Duplicate personality");
6885 PersonalityEncoding = readNext<uint8_t>(Pos);
6886 Personality = readPointer(Pos, is64Bit, *PersonalityEncoding);
6890 assert(!FDEPointerEncoding && "Duplicate FDE encoding");
6891 FDEPointerEncoding = readNext<uint8_t>(Pos);
6894 llvm_unreachable("'z' must be first in the augmentation string");
6900 outs() << " Length: " << Length << "\n";
6901 outs() << " CIE ID: " << ID << "\n";
6902 outs() << " Version: " << Version << "\n";
6903 outs() << " Augmentation String: " << AugmentationString << "\n";
6905 outs() << " EHData: " << *EHData << "\n";
6906 outs() << " Code Alignment Factor: " << CodeAlignmentFactor << "\n";
6907 outs() << " Data Alignment Factor: " << DataAlignmentFactor << "\n";
6908 outs() << " Return Address Register: " << ReturnAddressRegister << "\n";
6909 if (AugmentationLength) {
6910 outs() << " Augmentation Data Length: " << *AugmentationLength << "\n";
6911 if (LSDAPointerEncoding) {
6912 outs() << " FDE LSDA Pointer Encoding: "
6913 << *LSDAPointerEncoding << "\n";
6916 outs() << " Personality Encoding: " << *PersonalityEncoding << "\n";
6917 outs() << " Personality: " << *Personality << "\n";
6919 if (FDEPointerEncoding) {
6920 outs() << " FDE Address Pointer Encoding: "
6921 << *FDEPointerEncoding << "\n";
6924 // FIXME: Handle instructions.
6925 // For now just emit some bytes
6926 outs() << " Instructions:\n ";
6927 dumpBytes(makeArrayRef((const uint8_t*)Pos, (const uint8_t*)EntryEndPos),
6932 // Cache this entry.
6933 uint64_t Offset = EntryStartPos - Contents.data();
6934 CachedCIEs[Offset] = { FDEPointerEncoding, LSDAPointerEncoding,
6935 AugmentationLength.hasValue() };
6940 // The CIE pointer for an FDE is the same location as the ID which we
6942 uint32_t CIEPointer = ID;
6944 const char *CIEStart = PosAfterLength - CIEPointer;
6945 assert(CIEStart >= Contents.data() &&
6946 "FDE points to CIE before the __eh_frame start");
6948 uint64_t CIEOffset = CIEStart - Contents.data();
6949 auto CIEIt = CachedCIEs.find(CIEOffset);
6950 if (CIEIt == CachedCIEs.end())
6951 llvm_unreachable("Couldn't find CIE at offset in to __eh_frame section");
6953 const DecodedCIE &CIE = CIEIt->getSecond();
6954 assert(CIE.FDEPointerEncoding &&
6955 "FDE references CIE which did not set pointer encoding");
6957 uint64_t PCPointerSize = getSizeForEncoding(is64Bit,
6958 *CIE.FDEPointerEncoding);
6960 uint64_t PCBegin = readPointer(Pos, is64Bit, *CIE.FDEPointerEncoding);
6961 uint64_t PCRange = readPointer(Pos, is64Bit, *CIE.FDEPointerEncoding);
6963 Optional<uint64_t> AugmentationLength;
6964 uint32_t LSDAPointerSize;
6965 Optional<uint64_t> LSDAPointer;
6966 if (CIE.hasAugmentationLength) {
6967 unsigned ULEBByteCount;
6968 AugmentationLength = decodeULEB128((const uint8_t *)Pos,
6970 Pos += ULEBByteCount;
6972 // Decode the LSDA if the CIE augmentation string said we should.
6973 if (CIE.LSDAPointerEncoding) {
6974 LSDAPointerSize = getSizeForEncoding(is64Bit, *CIE.LSDAPointerEncoding);
6975 LSDAPointer = readPointer(Pos, is64Bit, *CIE.LSDAPointerEncoding);
6980 outs() << " Length: " << Length << "\n";
6981 outs() << " CIE Offset: " << CIEOffset << "\n";
6983 if (PCPointerSize == 8) {
6984 outs() << format(" PC Begin: %016" PRIx64, PCBegin) << "\n";
6985 outs() << format(" PC Range: %016" PRIx64, PCRange) << "\n";
6987 outs() << format(" PC Begin: %08" PRIx64, PCBegin) << "\n";
6988 outs() << format(" PC Range: %08" PRIx64, PCRange) << "\n";
6990 if (AugmentationLength) {
6991 outs() << " Augmentation Data Length: " << *AugmentationLength << "\n";
6993 if (LSDAPointerSize == 8)
6994 outs() << format(" LSDA Pointer: %016\n" PRIx64, *LSDAPointer);
6996 outs() << format(" LSDA Pointer: %08\n" PRIx64, *LSDAPointer);
7000 // FIXME: Handle instructions.
7001 // For now just emit some bytes
7002 outs() << " Instructions:\n ";
7003 dumpBytes(makeArrayRef((const uint8_t*)Pos, (const uint8_t*)EntryEndPos),
7010 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7011 std::map<uint64_t, SymbolRef> Symbols;
7012 for (const SymbolRef &SymRef : Obj->symbols()) {
7013 // Discard any undefined or absolute symbols. They're not going to take part
7014 // in the convenience lookup for unwind info and just take up resources.
7015 section_iterator Section = *SymRef.getSection();
7016 if (Section == Obj->section_end())
7019 uint64_t Addr = SymRef.getValue();
7020 Symbols.insert(std::make_pair(Addr, SymRef));
7023 for (const SectionRef &Section : Obj->sections()) {
7025 Section.getName(SectName);
7026 if (SectName == "__compact_unwind")
7027 printMachOCompactUnwindSection(Obj, Symbols, Section);
7028 else if (SectName == "__unwind_info")
7029 printMachOUnwindInfoSection(Obj, Symbols, Section);
7030 else if (SectName == "__eh_frame")
7031 printMachOEHFrameSection(Obj, Symbols, Section);
7035 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7036 uint32_t cpusubtype, uint32_t filetype,
7037 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7039 outs() << "Mach header\n";
7040 outs() << " magic cputype cpusubtype caps filetype ncmds "
7041 "sizeofcmds flags\n";
7043 if (magic == MachO::MH_MAGIC)
7044 outs() << " MH_MAGIC";
7045 else if (magic == MachO::MH_MAGIC_64)
7046 outs() << "MH_MAGIC_64";
7048 outs() << format(" 0x%08" PRIx32, magic);
7050 case MachO::CPU_TYPE_I386:
7052 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7053 case MachO::CPU_SUBTYPE_I386_ALL:
7057 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7061 case MachO::CPU_TYPE_X86_64:
7062 outs() << " X86_64";
7063 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7064 case MachO::CPU_SUBTYPE_X86_64_ALL:
7067 case MachO::CPU_SUBTYPE_X86_64_H:
7068 outs() << " Haswell";
7071 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7075 case MachO::CPU_TYPE_ARM:
7077 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7078 case MachO::CPU_SUBTYPE_ARM_ALL:
7081 case MachO::CPU_SUBTYPE_ARM_V4T:
7084 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7087 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7088 outs() << " XSCALE";
7090 case MachO::CPU_SUBTYPE_ARM_V6:
7093 case MachO::CPU_SUBTYPE_ARM_V6M:
7096 case MachO::CPU_SUBTYPE_ARM_V7:
7099 case MachO::CPU_SUBTYPE_ARM_V7EM:
7102 case MachO::CPU_SUBTYPE_ARM_V7K:
7105 case MachO::CPU_SUBTYPE_ARM_V7M:
7108 case MachO::CPU_SUBTYPE_ARM_V7S:
7112 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7116 case MachO::CPU_TYPE_ARM64:
7118 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7119 case MachO::CPU_SUBTYPE_ARM64_ALL:
7123 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7127 case MachO::CPU_TYPE_POWERPC:
7129 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7130 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7134 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7138 case MachO::CPU_TYPE_POWERPC64:
7140 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7141 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7145 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7150 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
7153 outs() << format(" 0x%02" PRIx32,
7154 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7157 case MachO::MH_OBJECT:
7158 outs() << " OBJECT";
7160 case MachO::MH_EXECUTE:
7161 outs() << " EXECUTE";
7163 case MachO::MH_FVMLIB:
7164 outs() << " FVMLIB";
7166 case MachO::MH_CORE:
7169 case MachO::MH_PRELOAD:
7170 outs() << " PRELOAD";
7172 case MachO::MH_DYLIB:
7175 case MachO::MH_DYLIB_STUB:
7176 outs() << " DYLIB_STUB";
7178 case MachO::MH_DYLINKER:
7179 outs() << " DYLINKER";
7181 case MachO::MH_BUNDLE:
7182 outs() << " BUNDLE";
7184 case MachO::MH_DSYM:
7187 case MachO::MH_KEXT_BUNDLE:
7188 outs() << " KEXTBUNDLE";
7191 outs() << format(" %10u", filetype);
7194 outs() << format(" %5u", ncmds);
7195 outs() << format(" %10u", sizeofcmds);
7197 if (f & MachO::MH_NOUNDEFS) {
7198 outs() << " NOUNDEFS";
7199 f &= ~MachO::MH_NOUNDEFS;
7201 if (f & MachO::MH_INCRLINK) {
7202 outs() << " INCRLINK";
7203 f &= ~MachO::MH_INCRLINK;
7205 if (f & MachO::MH_DYLDLINK) {
7206 outs() << " DYLDLINK";
7207 f &= ~MachO::MH_DYLDLINK;
7209 if (f & MachO::MH_BINDATLOAD) {
7210 outs() << " BINDATLOAD";
7211 f &= ~MachO::MH_BINDATLOAD;
7213 if (f & MachO::MH_PREBOUND) {
7214 outs() << " PREBOUND";
7215 f &= ~MachO::MH_PREBOUND;
7217 if (f & MachO::MH_SPLIT_SEGS) {
7218 outs() << " SPLIT_SEGS";
7219 f &= ~MachO::MH_SPLIT_SEGS;
7221 if (f & MachO::MH_LAZY_INIT) {
7222 outs() << " LAZY_INIT";
7223 f &= ~MachO::MH_LAZY_INIT;
7225 if (f & MachO::MH_TWOLEVEL) {
7226 outs() << " TWOLEVEL";
7227 f &= ~MachO::MH_TWOLEVEL;
7229 if (f & MachO::MH_FORCE_FLAT) {
7230 outs() << " FORCE_FLAT";
7231 f &= ~MachO::MH_FORCE_FLAT;
7233 if (f & MachO::MH_NOMULTIDEFS) {
7234 outs() << " NOMULTIDEFS";
7235 f &= ~MachO::MH_NOMULTIDEFS;
7237 if (f & MachO::MH_NOFIXPREBINDING) {
7238 outs() << " NOFIXPREBINDING";
7239 f &= ~MachO::MH_NOFIXPREBINDING;
7241 if (f & MachO::MH_PREBINDABLE) {
7242 outs() << " PREBINDABLE";
7243 f &= ~MachO::MH_PREBINDABLE;
7245 if (f & MachO::MH_ALLMODSBOUND) {
7246 outs() << " ALLMODSBOUND";
7247 f &= ~MachO::MH_ALLMODSBOUND;
7249 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7250 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7251 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7253 if (f & MachO::MH_CANONICAL) {
7254 outs() << " CANONICAL";
7255 f &= ~MachO::MH_CANONICAL;
7257 if (f & MachO::MH_WEAK_DEFINES) {
7258 outs() << " WEAK_DEFINES";
7259 f &= ~MachO::MH_WEAK_DEFINES;
7261 if (f & MachO::MH_BINDS_TO_WEAK) {
7262 outs() << " BINDS_TO_WEAK";
7263 f &= ~MachO::MH_BINDS_TO_WEAK;
7265 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7266 outs() << " ALLOW_STACK_EXECUTION";
7267 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7269 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7270 outs() << " DEAD_STRIPPABLE_DYLIB";
7271 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7273 if (f & MachO::MH_PIE) {
7275 f &= ~MachO::MH_PIE;
7277 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7278 outs() << " NO_REEXPORTED_DYLIBS";
7279 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7281 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7282 outs() << " MH_HAS_TLV_DESCRIPTORS";
7283 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7285 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7286 outs() << " MH_NO_HEAP_EXECUTION";
7287 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7289 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7290 outs() << " APP_EXTENSION_SAFE";
7291 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7293 if (f != 0 || flags == 0)
7294 outs() << format(" 0x%08" PRIx32, f);
7296 outs() << format(" 0x%08" PRIx32, magic);
7297 outs() << format(" %7d", cputype);
7298 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7299 outs() << format(" 0x%02" PRIx32,
7300 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7301 outs() << format(" %10u", filetype);
7302 outs() << format(" %5u", ncmds);
7303 outs() << format(" %10u", sizeofcmds);
7304 outs() << format(" 0x%08" PRIx32, flags);
7309 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7310 StringRef SegName, uint64_t vmaddr,
7311 uint64_t vmsize, uint64_t fileoff,
7312 uint64_t filesize, uint32_t maxprot,
7313 uint32_t initprot, uint32_t nsects,
7314 uint32_t flags, uint32_t object_size,
7316 uint64_t expected_cmdsize;
7317 if (cmd == MachO::LC_SEGMENT) {
7318 outs() << " cmd LC_SEGMENT\n";
7319 expected_cmdsize = nsects;
7320 expected_cmdsize *= sizeof(struct MachO::section);
7321 expected_cmdsize += sizeof(struct MachO::segment_command);
7323 outs() << " cmd LC_SEGMENT_64\n";
7324 expected_cmdsize = nsects;
7325 expected_cmdsize *= sizeof(struct MachO::section_64);
7326 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7328 outs() << " cmdsize " << cmdsize;
7329 if (cmdsize != expected_cmdsize)
7330 outs() << " Inconsistent size\n";
7333 outs() << " segname " << SegName << "\n";
7334 if (cmd == MachO::LC_SEGMENT_64) {
7335 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7336 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7338 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7339 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
7341 outs() << " fileoff " << fileoff;
7342 if (fileoff > object_size)
7343 outs() << " (past end of file)\n";
7346 outs() << " filesize " << filesize;
7347 if (fileoff + filesize > object_size)
7348 outs() << " (past end of file)\n";
7353 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7354 MachO::VM_PROT_EXECUTE)) != 0)
7355 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7357 outs() << " maxprot ";
7358 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7359 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7360 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7363 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7364 MachO::VM_PROT_EXECUTE)) != 0)
7365 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7367 outs() << " initprot ";
7368 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7369 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7370 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7373 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7374 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7376 outs() << " nsects " << nsects << "\n";
7380 outs() << " (none)\n";
7382 if (flags & MachO::SG_HIGHVM) {
7383 outs() << " HIGHVM";
7384 flags &= ~MachO::SG_HIGHVM;
7386 if (flags & MachO::SG_FVMLIB) {
7387 outs() << " FVMLIB";
7388 flags &= ~MachO::SG_FVMLIB;
7390 if (flags & MachO::SG_NORELOC) {
7391 outs() << " NORELOC";
7392 flags &= ~MachO::SG_NORELOC;
7394 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7395 outs() << " PROTECTED_VERSION_1";
7396 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7399 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7404 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7408 static void PrintSection(const char *sectname, const char *segname,
7409 uint64_t addr, uint64_t size, uint32_t offset,
7410 uint32_t align, uint32_t reloff, uint32_t nreloc,
7411 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7412 uint32_t cmd, const char *sg_segname,
7413 uint32_t filetype, uint32_t object_size,
7415 outs() << "Section\n";
7416 outs() << " sectname " << format("%.16s\n", sectname);
7417 outs() << " segname " << format("%.16s", segname);
7418 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7419 outs() << " (does not match segment)\n";
7422 if (cmd == MachO::LC_SEGMENT_64) {
7423 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7424 outs() << " size " << format("0x%016" PRIx64, size);
7426 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7427 outs() << " size " << format("0x%08" PRIx64, size);
7429 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7430 outs() << " (past end of file)\n";
7433 outs() << " offset " << offset;
7434 if (offset > object_size)
7435 outs() << " (past end of file)\n";
7438 uint32_t align_shifted = 1 << align;
7439 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7440 outs() << " reloff " << reloff;
7441 if (reloff > object_size)
7442 outs() << " (past end of file)\n";
7445 outs() << " nreloc " << nreloc;
7446 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7447 outs() << " (past end of file)\n";
7450 uint32_t section_type = flags & MachO::SECTION_TYPE;
7453 if (section_type == MachO::S_REGULAR)
7454 outs() << " S_REGULAR\n";
7455 else if (section_type == MachO::S_ZEROFILL)
7456 outs() << " S_ZEROFILL\n";
7457 else if (section_type == MachO::S_CSTRING_LITERALS)
7458 outs() << " S_CSTRING_LITERALS\n";
7459 else if (section_type == MachO::S_4BYTE_LITERALS)
7460 outs() << " S_4BYTE_LITERALS\n";
7461 else if (section_type == MachO::S_8BYTE_LITERALS)
7462 outs() << " S_8BYTE_LITERALS\n";
7463 else if (section_type == MachO::S_16BYTE_LITERALS)
7464 outs() << " S_16BYTE_LITERALS\n";
7465 else if (section_type == MachO::S_LITERAL_POINTERS)
7466 outs() << " S_LITERAL_POINTERS\n";
7467 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7468 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7469 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7470 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7471 else if (section_type == MachO::S_SYMBOL_STUBS)
7472 outs() << " S_SYMBOL_STUBS\n";
7473 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7474 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7475 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7476 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7477 else if (section_type == MachO::S_COALESCED)
7478 outs() << " S_COALESCED\n";
7479 else if (section_type == MachO::S_INTERPOSING)
7480 outs() << " S_INTERPOSING\n";
7481 else if (section_type == MachO::S_DTRACE_DOF)
7482 outs() << " S_DTRACE_DOF\n";
7483 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7484 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7485 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7486 outs() << " S_THREAD_LOCAL_REGULAR\n";
7487 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7488 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7489 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7490 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7491 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7492 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7493 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7494 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7496 outs() << format("0x%08" PRIx32, section_type) << "\n";
7497 outs() << "attributes";
7498 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7499 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7500 outs() << " PURE_INSTRUCTIONS";
7501 if (section_attributes & MachO::S_ATTR_NO_TOC)
7502 outs() << " NO_TOC";
7503 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7504 outs() << " STRIP_STATIC_SYMS";
7505 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7506 outs() << " NO_DEAD_STRIP";
7507 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7508 outs() << " LIVE_SUPPORT";
7509 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7510 outs() << " SELF_MODIFYING_CODE";
7511 if (section_attributes & MachO::S_ATTR_DEBUG)
7513 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7514 outs() << " SOME_INSTRUCTIONS";
7515 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7516 outs() << " EXT_RELOC";
7517 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7518 outs() << " LOC_RELOC";
7519 if (section_attributes == 0)
7520 outs() << " (none)";
7523 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7524 outs() << " reserved1 " << reserved1;
7525 if (section_type == MachO::S_SYMBOL_STUBS ||
7526 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7527 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7528 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7529 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7530 outs() << " (index into indirect symbol table)\n";
7533 outs() << " reserved2 " << reserved2;
7534 if (section_type == MachO::S_SYMBOL_STUBS)
7535 outs() << " (size of stubs)\n";
7540 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
7541 uint32_t object_size) {
7542 outs() << " cmd LC_SYMTAB\n";
7543 outs() << " cmdsize " << st.cmdsize;
7544 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7545 outs() << " Incorrect size\n";
7548 outs() << " symoff " << st.symoff;
7549 if (st.symoff > object_size)
7550 outs() << " (past end of file)\n";
7553 outs() << " nsyms " << st.nsyms;
7556 big_size = st.nsyms;
7557 big_size *= sizeof(struct MachO::nlist_64);
7558 big_size += st.symoff;
7559 if (big_size > object_size)
7560 outs() << " (past end of file)\n";
7564 big_size = st.nsyms;
7565 big_size *= sizeof(struct MachO::nlist);
7566 big_size += st.symoff;
7567 if (big_size > object_size)
7568 outs() << " (past end of file)\n";
7572 outs() << " stroff " << st.stroff;
7573 if (st.stroff > object_size)
7574 outs() << " (past end of file)\n";
7577 outs() << " strsize " << st.strsize;
7578 big_size = st.stroff;
7579 big_size += st.strsize;
7580 if (big_size > object_size)
7581 outs() << " (past end of file)\n";
7586 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7587 uint32_t nsyms, uint32_t object_size,
7589 outs() << " cmd LC_DYSYMTAB\n";
7590 outs() << " cmdsize " << dyst.cmdsize;
7591 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7592 outs() << " Incorrect size\n";
7595 outs() << " ilocalsym " << dyst.ilocalsym;
7596 if (dyst.ilocalsym > nsyms)
7597 outs() << " (greater than the number of symbols)\n";
7600 outs() << " nlocalsym " << dyst.nlocalsym;
7602 big_size = dyst.ilocalsym;
7603 big_size += dyst.nlocalsym;
7604 if (big_size > nsyms)
7605 outs() << " (past the end of the symbol table)\n";
7608 outs() << " iextdefsym " << dyst.iextdefsym;
7609 if (dyst.iextdefsym > nsyms)
7610 outs() << " (greater than the number of symbols)\n";
7613 outs() << " nextdefsym " << dyst.nextdefsym;
7614 big_size = dyst.iextdefsym;
7615 big_size += dyst.nextdefsym;
7616 if (big_size > nsyms)
7617 outs() << " (past the end of the symbol table)\n";
7620 outs() << " iundefsym " << dyst.iundefsym;
7621 if (dyst.iundefsym > nsyms)
7622 outs() << " (greater than the number of symbols)\n";
7625 outs() << " nundefsym " << dyst.nundefsym;
7626 big_size = dyst.iundefsym;
7627 big_size += dyst.nundefsym;
7628 if (big_size > nsyms)
7629 outs() << " (past the end of the symbol table)\n";
7632 outs() << " tocoff " << dyst.tocoff;
7633 if (dyst.tocoff > object_size)
7634 outs() << " (past end of file)\n";
7637 outs() << " ntoc " << dyst.ntoc;
7638 big_size = dyst.ntoc;
7639 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7640 big_size += dyst.tocoff;
7641 if (big_size > object_size)
7642 outs() << " (past end of file)\n";
7645 outs() << " modtaboff " << dyst.modtaboff;
7646 if (dyst.modtaboff > object_size)
7647 outs() << " (past end of file)\n";
7650 outs() << " nmodtab " << dyst.nmodtab;
7653 modtabend = dyst.nmodtab;
7654 modtabend *= sizeof(struct MachO::dylib_module_64);
7655 modtabend += dyst.modtaboff;
7657 modtabend = dyst.nmodtab;
7658 modtabend *= sizeof(struct MachO::dylib_module);
7659 modtabend += dyst.modtaboff;
7661 if (modtabend > object_size)
7662 outs() << " (past end of file)\n";
7665 outs() << " extrefsymoff " << dyst.extrefsymoff;
7666 if (dyst.extrefsymoff > object_size)
7667 outs() << " (past end of file)\n";
7670 outs() << " nextrefsyms " << dyst.nextrefsyms;
7671 big_size = dyst.nextrefsyms;
7672 big_size *= sizeof(struct MachO::dylib_reference);
7673 big_size += dyst.extrefsymoff;
7674 if (big_size > object_size)
7675 outs() << " (past end of file)\n";
7678 outs() << " indirectsymoff " << dyst.indirectsymoff;
7679 if (dyst.indirectsymoff > object_size)
7680 outs() << " (past end of file)\n";
7683 outs() << " nindirectsyms " << dyst.nindirectsyms;
7684 big_size = dyst.nindirectsyms;
7685 big_size *= sizeof(uint32_t);
7686 big_size += dyst.indirectsymoff;
7687 if (big_size > object_size)
7688 outs() << " (past end of file)\n";
7691 outs() << " extreloff " << dyst.extreloff;
7692 if (dyst.extreloff > object_size)
7693 outs() << " (past end of file)\n";
7696 outs() << " nextrel " << dyst.nextrel;
7697 big_size = dyst.nextrel;
7698 big_size *= sizeof(struct MachO::relocation_info);
7699 big_size += dyst.extreloff;
7700 if (big_size > object_size)
7701 outs() << " (past end of file)\n";
7704 outs() << " locreloff " << dyst.locreloff;
7705 if (dyst.locreloff > object_size)
7706 outs() << " (past end of file)\n";
7709 outs() << " nlocrel " << dyst.nlocrel;
7710 big_size = dyst.nlocrel;
7711 big_size *= sizeof(struct MachO::relocation_info);
7712 big_size += dyst.locreloff;
7713 if (big_size > object_size)
7714 outs() << " (past end of file)\n";
7719 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7720 uint32_t object_size) {
7721 if (dc.cmd == MachO::LC_DYLD_INFO)
7722 outs() << " cmd LC_DYLD_INFO\n";
7724 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7725 outs() << " cmdsize " << dc.cmdsize;
7726 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7727 outs() << " Incorrect size\n";
7730 outs() << " rebase_off " << dc.rebase_off;
7731 if (dc.rebase_off > object_size)
7732 outs() << " (past end of file)\n";
7735 outs() << " rebase_size " << dc.rebase_size;
7737 big_size = dc.rebase_off;
7738 big_size += dc.rebase_size;
7739 if (big_size > object_size)
7740 outs() << " (past end of file)\n";
7743 outs() << " bind_off " << dc.bind_off;
7744 if (dc.bind_off > object_size)
7745 outs() << " (past end of file)\n";
7748 outs() << " bind_size " << dc.bind_size;
7749 big_size = dc.bind_off;
7750 big_size += dc.bind_size;
7751 if (big_size > object_size)
7752 outs() << " (past end of file)\n";
7755 outs() << " weak_bind_off " << dc.weak_bind_off;
7756 if (dc.weak_bind_off > object_size)
7757 outs() << " (past end of file)\n";
7760 outs() << " weak_bind_size " << dc.weak_bind_size;
7761 big_size = dc.weak_bind_off;
7762 big_size += dc.weak_bind_size;
7763 if (big_size > object_size)
7764 outs() << " (past end of file)\n";
7767 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7768 if (dc.lazy_bind_off > object_size)
7769 outs() << " (past end of file)\n";
7772 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7773 big_size = dc.lazy_bind_off;
7774 big_size += dc.lazy_bind_size;
7775 if (big_size > object_size)
7776 outs() << " (past end of file)\n";
7779 outs() << " export_off " << dc.export_off;
7780 if (dc.export_off > object_size)
7781 outs() << " (past end of file)\n";
7784 outs() << " export_size " << dc.export_size;
7785 big_size = dc.export_off;
7786 big_size += dc.export_size;
7787 if (big_size > object_size)
7788 outs() << " (past end of file)\n";
7793 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7795 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7796 outs() << " cmd LC_ID_DYLINKER\n";
7797 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7798 outs() << " cmd LC_LOAD_DYLINKER\n";
7799 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7800 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7802 outs() << " cmd ?(" << dyld.cmd << ")\n";
7803 outs() << " cmdsize " << dyld.cmdsize;
7804 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7805 outs() << " Incorrect size\n";
7808 if (dyld.name >= dyld.cmdsize)
7809 outs() << " name ?(bad offset " << dyld.name << ")\n";
7811 const char *P = (const char *)(Ptr) + dyld.name;
7812 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7816 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7817 outs() << " cmd LC_UUID\n";
7818 outs() << " cmdsize " << uuid.cmdsize;
7819 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7820 outs() << " Incorrect size\n";
7824 for (int i = 0; i < 16; ++i) {
7825 outs() << format("%02" PRIX32, uuid.uuid[i]);
7826 if (i == 3 || i == 5 || i == 7 || i == 9)
7832 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
7833 outs() << " cmd LC_RPATH\n";
7834 outs() << " cmdsize " << rpath.cmdsize;
7835 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7836 outs() << " Incorrect size\n";
7839 if (rpath.path >= rpath.cmdsize)
7840 outs() << " path ?(bad offset " << rpath.path << ")\n";
7842 const char *P = (const char *)(Ptr) + rpath.path;
7843 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7847 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
7848 StringRef LoadCmdName;
7850 case MachO::LC_VERSION_MIN_MACOSX:
7851 LoadCmdName = "LC_VERSION_MIN_MACOSX";
7853 case MachO::LC_VERSION_MIN_IPHONEOS:
7854 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
7856 case MachO::LC_VERSION_MIN_TVOS:
7857 LoadCmdName = "LC_VERSION_MIN_TVOS";
7859 case MachO::LC_VERSION_MIN_WATCHOS:
7860 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
7863 llvm_unreachable("Unknown version min load command");
7866 outs() << " cmd " << LoadCmdName << '\n';
7867 outs() << " cmdsize " << vd.cmdsize;
7868 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7869 outs() << " Incorrect size\n";
7872 outs() << " version "
7873 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7874 << MachOObjectFile::getVersionMinMinor(vd, false);
7875 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7877 outs() << "." << Update;
7880 outs() << " sdk n/a";
7883 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7884 << MachOObjectFile::getVersionMinMinor(vd, true);
7886 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7888 outs() << "." << Update;
7892 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7893 outs() << " cmd LC_SOURCE_VERSION\n";
7894 outs() << " cmdsize " << sd.cmdsize;
7895 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7896 outs() << " Incorrect size\n";
7899 uint64_t a = (sd.version >> 40) & 0xffffff;
7900 uint64_t b = (sd.version >> 30) & 0x3ff;
7901 uint64_t c = (sd.version >> 20) & 0x3ff;
7902 uint64_t d = (sd.version >> 10) & 0x3ff;
7903 uint64_t e = sd.version & 0x3ff;
7904 outs() << " version " << a << "." << b;
7906 outs() << "." << c << "." << d << "." << e;
7908 outs() << "." << c << "." << d;
7914 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7915 outs() << " cmd LC_MAIN\n";
7916 outs() << " cmdsize " << ep.cmdsize;
7917 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7918 outs() << " Incorrect size\n";
7921 outs() << " entryoff " << ep.entryoff << "\n";
7922 outs() << " stacksize " << ep.stacksize << "\n";
7925 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7926 uint32_t object_size) {
7927 outs() << " cmd LC_ENCRYPTION_INFO\n";
7928 outs() << " cmdsize " << ec.cmdsize;
7929 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7930 outs() << " Incorrect size\n";
7933 outs() << " cryptoff " << ec.cryptoff;
7934 if (ec.cryptoff > object_size)
7935 outs() << " (past end of file)\n";
7938 outs() << " cryptsize " << ec.cryptsize;
7939 if (ec.cryptsize > object_size)
7940 outs() << " (past end of file)\n";
7943 outs() << " cryptid " << ec.cryptid << "\n";
7946 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
7947 uint32_t object_size) {
7948 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7949 outs() << " cmdsize " << ec.cmdsize;
7950 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7951 outs() << " Incorrect size\n";
7954 outs() << " cryptoff " << ec.cryptoff;
7955 if (ec.cryptoff > object_size)
7956 outs() << " (past end of file)\n";
7959 outs() << " cryptsize " << ec.cryptsize;
7960 if (ec.cryptsize > object_size)
7961 outs() << " (past end of file)\n";
7964 outs() << " cryptid " << ec.cryptid << "\n";
7965 outs() << " pad " << ec.pad << "\n";
7968 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7970 outs() << " cmd LC_LINKER_OPTION\n";
7971 outs() << " cmdsize " << lo.cmdsize;
7972 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7973 outs() << " Incorrect size\n";
7976 outs() << " count " << lo.count << "\n";
7977 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7978 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7981 while (*string == '\0' && left > 0) {
7987 outs() << " string #" << i << " " << format("%.*s\n", left, string);
7988 uint32_t NullPos = StringRef(string, left).find('\0');
7989 uint32_t len = std::min(NullPos, left) + 1;
7995 outs() << " count " << lo.count << " does not match number of strings "
7999 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8001 outs() << " cmd LC_SUB_FRAMEWORK\n";
8002 outs() << " cmdsize " << sub.cmdsize;
8003 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8004 outs() << " Incorrect size\n";
8007 if (sub.umbrella < sub.cmdsize) {
8008 const char *P = Ptr + sub.umbrella;
8009 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8011 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8015 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8017 outs() << " cmd LC_SUB_UMBRELLA\n";
8018 outs() << " cmdsize " << sub.cmdsize;
8019 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8020 outs() << " Incorrect size\n";
8023 if (sub.sub_umbrella < sub.cmdsize) {
8024 const char *P = Ptr + sub.sub_umbrella;
8025 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8027 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8031 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
8033 outs() << " cmd LC_SUB_LIBRARY\n";
8034 outs() << " cmdsize " << sub.cmdsize;
8035 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8036 outs() << " Incorrect size\n";
8039 if (sub.sub_library < sub.cmdsize) {
8040 const char *P = Ptr + sub.sub_library;
8041 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8043 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8047 static void PrintSubClientCommand(MachO::sub_client_command sub,
8049 outs() << " cmd LC_SUB_CLIENT\n";
8050 outs() << " cmdsize " << sub.cmdsize;
8051 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8052 outs() << " Incorrect size\n";
8055 if (sub.client < sub.cmdsize) {
8056 const char *P = Ptr + sub.client;
8057 outs() << " client " << P << " (offset " << sub.client << ")\n";
8059 outs() << " client ?(bad offset " << sub.client << ")\n";
8063 static void PrintRoutinesCommand(MachO::routines_command r) {
8064 outs() << " cmd LC_ROUTINES\n";
8065 outs() << " cmdsize " << r.cmdsize;
8066 if (r.cmdsize != sizeof(struct MachO::routines_command))
8067 outs() << " Incorrect size\n";
8070 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8071 outs() << " init_module " << r.init_module << "\n";
8072 outs() << " reserved1 " << r.reserved1 << "\n";
8073 outs() << " reserved2 " << r.reserved2 << "\n";
8074 outs() << " reserved3 " << r.reserved3 << "\n";
8075 outs() << " reserved4 " << r.reserved4 << "\n";
8076 outs() << " reserved5 " << r.reserved5 << "\n";
8077 outs() << " reserved6 " << r.reserved6 << "\n";
8080 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8081 outs() << " cmd LC_ROUTINES_64\n";
8082 outs() << " cmdsize " << r.cmdsize;
8083 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8084 outs() << " Incorrect size\n";
8087 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8088 outs() << " init_module " << r.init_module << "\n";
8089 outs() << " reserved1 " << r.reserved1 << "\n";
8090 outs() << " reserved2 " << r.reserved2 << "\n";
8091 outs() << " reserved3 " << r.reserved3 << "\n";
8092 outs() << " reserved4 " << r.reserved4 << "\n";
8093 outs() << " reserved5 " << r.reserved5 << "\n";
8094 outs() << " reserved6 " << r.reserved6 << "\n";
8097 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8098 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8099 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8100 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8101 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8102 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8103 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8104 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8105 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8106 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8107 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8108 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8109 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8110 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8111 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8112 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8113 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8114 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8115 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8116 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8117 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8118 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8121 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
8123 outs() << "\t mmst_reg ";
8124 for (f = 0; f < 10; f++)
8125 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8127 outs() << "\t mmst_rsrv ";
8128 for (f = 0; f < 6; f++)
8129 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8133 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
8135 outs() << "\t xmm_reg ";
8136 for (f = 0; f < 16; f++)
8137 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8141 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8142 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8143 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8144 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8145 outs() << " denorm " << fpu.fpu_fcw.denorm;
8146 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8147 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8148 outs() << " undfl " << fpu.fpu_fcw.undfl;
8149 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8150 outs() << "\t\t pc ";
8151 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8152 outs() << "FP_PREC_24B ";
8153 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8154 outs() << "FP_PREC_53B ";
8155 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8156 outs() << "FP_PREC_64B ";
8158 outs() << fpu.fpu_fcw.pc << " ";
8160 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8161 outs() << "FP_RND_NEAR ";
8162 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8163 outs() << "FP_RND_DOWN ";
8164 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8165 outs() << "FP_RND_UP ";
8166 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
8167 outs() << "FP_CHOP ";
8169 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8170 outs() << " denorm " << fpu.fpu_fsw.denorm;
8171 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8172 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8173 outs() << " undfl " << fpu.fpu_fsw.undfl;
8174 outs() << " precis " << fpu.fpu_fsw.precis;
8175 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8176 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8177 outs() << " c0 " << fpu.fpu_fsw.c0;
8178 outs() << " c1 " << fpu.fpu_fsw.c1;
8179 outs() << " c2 " << fpu.fpu_fsw.c2;
8180 outs() << " tos " << fpu.fpu_fsw.tos;
8181 outs() << " c3 " << fpu.fpu_fsw.c3;
8182 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8183 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8184 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8185 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8186 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8187 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8188 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8189 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8190 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8191 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8192 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8193 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8195 outs() << "\t fpu_stmm0:\n";
8196 Print_mmst_reg(fpu.fpu_stmm0);
8197 outs() << "\t fpu_stmm1:\n";
8198 Print_mmst_reg(fpu.fpu_stmm1);
8199 outs() << "\t fpu_stmm2:\n";
8200 Print_mmst_reg(fpu.fpu_stmm2);
8201 outs() << "\t fpu_stmm3:\n";
8202 Print_mmst_reg(fpu.fpu_stmm3);
8203 outs() << "\t fpu_stmm4:\n";
8204 Print_mmst_reg(fpu.fpu_stmm4);
8205 outs() << "\t fpu_stmm5:\n";
8206 Print_mmst_reg(fpu.fpu_stmm5);
8207 outs() << "\t fpu_stmm6:\n";
8208 Print_mmst_reg(fpu.fpu_stmm6);
8209 outs() << "\t fpu_stmm7:\n";
8210 Print_mmst_reg(fpu.fpu_stmm7);
8211 outs() << "\t fpu_xmm0:\n";
8212 Print_xmm_reg(fpu.fpu_xmm0);
8213 outs() << "\t fpu_xmm1:\n";
8214 Print_xmm_reg(fpu.fpu_xmm1);
8215 outs() << "\t fpu_xmm2:\n";
8216 Print_xmm_reg(fpu.fpu_xmm2);
8217 outs() << "\t fpu_xmm3:\n";
8218 Print_xmm_reg(fpu.fpu_xmm3);
8219 outs() << "\t fpu_xmm4:\n";
8220 Print_xmm_reg(fpu.fpu_xmm4);
8221 outs() << "\t fpu_xmm5:\n";
8222 Print_xmm_reg(fpu.fpu_xmm5);
8223 outs() << "\t fpu_xmm6:\n";
8224 Print_xmm_reg(fpu.fpu_xmm6);
8225 outs() << "\t fpu_xmm7:\n";
8226 Print_xmm_reg(fpu.fpu_xmm7);
8227 outs() << "\t fpu_xmm8:\n";
8228 Print_xmm_reg(fpu.fpu_xmm8);
8229 outs() << "\t fpu_xmm9:\n";
8230 Print_xmm_reg(fpu.fpu_xmm9);
8231 outs() << "\t fpu_xmm10:\n";
8232 Print_xmm_reg(fpu.fpu_xmm10);
8233 outs() << "\t fpu_xmm11:\n";
8234 Print_xmm_reg(fpu.fpu_xmm11);
8235 outs() << "\t fpu_xmm12:\n";
8236 Print_xmm_reg(fpu.fpu_xmm12);
8237 outs() << "\t fpu_xmm13:\n";
8238 Print_xmm_reg(fpu.fpu_xmm13);
8239 outs() << "\t fpu_xmm14:\n";
8240 Print_xmm_reg(fpu.fpu_xmm14);
8241 outs() << "\t fpu_xmm15:\n";
8242 Print_xmm_reg(fpu.fpu_xmm15);
8243 outs() << "\t fpu_rsrv4:\n";
8244 for (uint32_t f = 0; f < 6; f++) {
8246 for (uint32_t g = 0; g < 16; g++)
8247 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
8250 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8254 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8255 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8256 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8257 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8260 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8261 bool isLittleEndian, uint32_t cputype) {
8262 if (t.cmd == MachO::LC_THREAD)
8263 outs() << " cmd LC_THREAD\n";
8264 else if (t.cmd == MachO::LC_UNIXTHREAD)
8265 outs() << " cmd LC_UNIXTHREAD\n";
8267 outs() << " cmd " << t.cmd << " (unknown)\n";
8268 outs() << " cmdsize " << t.cmdsize;
8269 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8270 outs() << " Incorrect size\n";
8274 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8275 const char *end = Ptr + t.cmdsize;
8276 uint32_t flavor, count, left;
8277 if (cputype == MachO::CPU_TYPE_X86_64) {
8278 while (begin < end) {
8279 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8280 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8281 begin += sizeof(uint32_t);
8286 if (isLittleEndian != sys::IsLittleEndianHost)
8287 sys::swapByteOrder(flavor);
8288 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8289 memcpy((char *)&count, begin, sizeof(uint32_t));
8290 begin += sizeof(uint32_t);
8295 if (isLittleEndian != sys::IsLittleEndianHost)
8296 sys::swapByteOrder(count);
8297 if (flavor == MachO::x86_THREAD_STATE64) {
8298 outs() << " flavor x86_THREAD_STATE64\n";
8299 if (count == MachO::x86_THREAD_STATE64_COUNT)
8300 outs() << " count x86_THREAD_STATE64_COUNT\n";
8302 outs() << " count " << count
8303 << " (not x86_THREAD_STATE64_COUNT)\n";
8304 MachO::x86_thread_state64_t cpu64;
8306 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8307 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8308 begin += sizeof(MachO::x86_thread_state64_t);
8310 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8311 memcpy(&cpu64, begin, left);
8314 if (isLittleEndian != sys::IsLittleEndianHost)
8316 Print_x86_thread_state64_t(cpu64);
8317 } else if (flavor == MachO::x86_THREAD_STATE) {
8318 outs() << " flavor x86_THREAD_STATE\n";
8319 if (count == MachO::x86_THREAD_STATE_COUNT)
8320 outs() << " count x86_THREAD_STATE_COUNT\n";
8322 outs() << " count " << count
8323 << " (not x86_THREAD_STATE_COUNT)\n";
8324 struct MachO::x86_thread_state_t ts;
8326 if (left >= sizeof(MachO::x86_thread_state_t)) {
8327 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8328 begin += sizeof(MachO::x86_thread_state_t);
8330 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8331 memcpy(&ts, begin, left);
8334 if (isLittleEndian != sys::IsLittleEndianHost)
8336 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8337 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8338 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8339 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8341 outs() << "tsh.count " << ts.tsh.count
8342 << " (not x86_THREAD_STATE64_COUNT\n";
8343 Print_x86_thread_state64_t(ts.uts.ts64);
8345 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8346 << ts.tsh.count << "\n";
8348 } else if (flavor == MachO::x86_FLOAT_STATE) {
8349 outs() << " flavor x86_FLOAT_STATE\n";
8350 if (count == MachO::x86_FLOAT_STATE_COUNT)
8351 outs() << " count x86_FLOAT_STATE_COUNT\n";
8353 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
8354 struct MachO::x86_float_state_t fs;
8356 if (left >= sizeof(MachO::x86_float_state_t)) {
8357 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8358 begin += sizeof(MachO::x86_float_state_t);
8360 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8361 memcpy(&fs, begin, left);
8364 if (isLittleEndian != sys::IsLittleEndianHost)
8366 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8367 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
8368 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
8369 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8371 outs() << "fsh.count " << fs.fsh.count
8372 << " (not x86_FLOAT_STATE64_COUNT\n";
8373 Print_x86_float_state_t(fs.ufs.fs64);
8375 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8376 << fs.fsh.count << "\n";
8378 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8379 outs() << " flavor x86_EXCEPTION_STATE\n";
8380 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8381 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8383 outs() << " count " << count
8384 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8385 struct MachO::x86_exception_state_t es;
8387 if (left >= sizeof(MachO::x86_exception_state_t)) {
8388 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8389 begin += sizeof(MachO::x86_exception_state_t);
8391 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8392 memcpy(&es, begin, left);
8395 if (isLittleEndian != sys::IsLittleEndianHost)
8397 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8398 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
8399 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
8400 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8402 outs() << "\t esh.count " << es.esh.count
8403 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8404 Print_x86_exception_state_t(es.ues.es64);
8406 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8407 << es.esh.count << "\n";
8410 outs() << " flavor " << flavor << " (unknown)\n";
8411 outs() << " count " << count << "\n";
8412 outs() << " state (unknown)\n";
8413 begin += count * sizeof(uint32_t);
8417 while (begin < end) {
8418 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8419 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8420 begin += sizeof(uint32_t);
8425 if (isLittleEndian != sys::IsLittleEndianHost)
8426 sys::swapByteOrder(flavor);
8427 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8428 memcpy((char *)&count, begin, sizeof(uint32_t));
8429 begin += sizeof(uint32_t);
8434 if (isLittleEndian != sys::IsLittleEndianHost)
8435 sys::swapByteOrder(count);
8436 outs() << " flavor " << flavor << "\n";
8437 outs() << " count " << count << "\n";
8438 outs() << " state (Unknown cputype/cpusubtype)\n";
8439 begin += count * sizeof(uint32_t);
8444 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8445 if (dl.cmd == MachO::LC_ID_DYLIB)
8446 outs() << " cmd LC_ID_DYLIB\n";
8447 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8448 outs() << " cmd LC_LOAD_DYLIB\n";
8449 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8450 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8451 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8452 outs() << " cmd LC_REEXPORT_DYLIB\n";
8453 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8454 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8455 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8456 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8458 outs() << " cmd " << dl.cmd << " (unknown)\n";
8459 outs() << " cmdsize " << dl.cmdsize;
8460 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8461 outs() << " Incorrect size\n";
8464 if (dl.dylib.name < dl.cmdsize) {
8465 const char *P = (const char *)(Ptr) + dl.dylib.name;
8466 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8468 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8470 outs() << " time stamp " << dl.dylib.timestamp << " ";
8471 time_t t = dl.dylib.timestamp;
8472 outs() << ctime(&t);
8473 outs() << " current version ";
8474 if (dl.dylib.current_version == 0xffffffff)
8477 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8478 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8479 << (dl.dylib.current_version & 0xff) << "\n";
8480 outs() << "compatibility version ";
8481 if (dl.dylib.compatibility_version == 0xffffffff)
8484 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8485 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8486 << (dl.dylib.compatibility_version & 0xff) << "\n";
8489 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8490 uint32_t object_size) {
8491 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8492 outs() << " cmd LC_FUNCTION_STARTS\n";
8493 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8494 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8495 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8496 outs() << " cmd LC_FUNCTION_STARTS\n";
8497 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8498 outs() << " cmd LC_DATA_IN_CODE\n";
8499 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8500 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8501 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8502 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8504 outs() << " cmd " << ld.cmd << " (?)\n";
8505 outs() << " cmdsize " << ld.cmdsize;
8506 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8507 outs() << " Incorrect size\n";
8510 outs() << " dataoff " << ld.dataoff;
8511 if (ld.dataoff > object_size)
8512 outs() << " (past end of file)\n";
8515 outs() << " datasize " << ld.datasize;
8516 uint64_t big_size = ld.dataoff;
8517 big_size += ld.datasize;
8518 if (big_size > object_size)
8519 outs() << " (past end of file)\n";
8524 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8525 uint32_t cputype, bool verbose) {
8526 StringRef Buf = Obj->getData();
8528 for (const auto &Command : Obj->load_commands()) {
8529 outs() << "Load command " << Index++ << "\n";
8530 if (Command.C.cmd == MachO::LC_SEGMENT) {
8531 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8532 const char *sg_segname = SLC.segname;
8533 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8534 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8535 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8537 for (unsigned j = 0; j < SLC.nsects; j++) {
8538 MachO::section S = Obj->getSection(Command, j);
8539 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8540 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8541 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8543 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8544 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8545 const char *sg_segname = SLC_64.segname;
8546 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8547 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8548 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8549 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8550 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8551 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8552 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8553 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8554 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8555 sg_segname, filetype, Buf.size(), verbose);
8557 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8558 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8559 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
8560 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8561 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8562 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8563 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8565 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8566 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8567 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8568 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8569 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8570 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8571 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8572 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8573 PrintDyldLoadCommand(Dyld, Command.Ptr);
8574 } else if (Command.C.cmd == MachO::LC_UUID) {
8575 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8576 PrintUuidLoadCommand(Uuid);
8577 } else if (Command.C.cmd == MachO::LC_RPATH) {
8578 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8579 PrintRpathLoadCommand(Rpath, Command.Ptr);
8580 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
8581 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8582 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8583 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
8584 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8585 PrintVersionMinLoadCommand(Vd);
8586 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8587 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8588 PrintSourceVersionCommand(Sd);
8589 } else if (Command.C.cmd == MachO::LC_MAIN) {
8590 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8591 PrintEntryPointCommand(Ep);
8592 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
8593 MachO::encryption_info_command Ei =
8594 Obj->getEncryptionInfoCommand(Command);
8595 PrintEncryptionInfoCommand(Ei, Buf.size());
8596 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
8597 MachO::encryption_info_command_64 Ei =
8598 Obj->getEncryptionInfoCommand64(Command);
8599 PrintEncryptionInfoCommand64(Ei, Buf.size());
8600 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
8601 MachO::linker_option_command Lo =
8602 Obj->getLinkerOptionLoadCommand(Command);
8603 PrintLinkerOptionCommand(Lo, Command.Ptr);
8604 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8605 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8606 PrintSubFrameworkCommand(Sf, Command.Ptr);
8607 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8608 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8609 PrintSubUmbrellaCommand(Sf, Command.Ptr);
8610 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8611 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8612 PrintSubLibraryCommand(Sl, Command.Ptr);
8613 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8614 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8615 PrintSubClientCommand(Sc, Command.Ptr);
8616 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8617 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8618 PrintRoutinesCommand(Rc);
8619 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8620 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8621 PrintRoutinesCommand64(Rc);
8622 } else if (Command.C.cmd == MachO::LC_THREAD ||
8623 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8624 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8625 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
8626 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8627 Command.C.cmd == MachO::LC_ID_DYLIB ||
8628 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8629 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8630 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8631 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
8632 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8633 PrintDylibCommand(Dl, Command.Ptr);
8634 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8635 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8636 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8637 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8638 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8639 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8640 MachO::linkedit_data_command Ld =
8641 Obj->getLinkeditDataLoadCommand(Command);
8642 PrintLinkEditDataCommand(Ld, Buf.size());
8644 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8646 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8647 // TODO: get and print the raw bytes of the load command.
8649 // TODO: print all the other kinds of load commands.
8653 static void getAndPrintMachHeader(const MachOObjectFile *Obj,
8654 uint32_t &filetype, uint32_t &cputype,
8656 if (Obj->is64Bit()) {
8657 MachO::mach_header_64 H_64;
8658 H_64 = Obj->getHeader64();
8659 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8660 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8661 filetype = H_64.filetype;
8662 cputype = H_64.cputype;
8664 MachO::mach_header H;
8665 H = Obj->getHeader();
8666 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8667 H.sizeofcmds, H.flags, verbose);
8668 filetype = H.filetype;
8669 cputype = H.cputype;
8673 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8674 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
8675 uint32_t filetype = 0;
8676 uint32_t cputype = 0;
8677 getAndPrintMachHeader(file, filetype, cputype, !NonVerbose);
8678 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
8681 //===----------------------------------------------------------------------===//
8682 // export trie dumping
8683 //===----------------------------------------------------------------------===//
8685 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
8686 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8687 uint64_t Flags = Entry.flags();
8688 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8689 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8690 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8691 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8692 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8693 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8694 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8696 outs() << "[re-export] ";
8698 outs() << format("0x%08llX ",
8699 Entry.address()); // FIXME:add in base address
8700 outs() << Entry.name();
8701 if (WeakDef || ThreadLocal || Resolver || Abs) {
8702 bool NeedsComma = false;
8705 outs() << "weak_def";
8711 outs() << "per-thread";
8717 outs() << "absolute";
8723 outs() << format("resolver=0x%08llX", Entry.other());
8729 StringRef DylibName = "unknown";
8730 int Ordinal = Entry.other() - 1;
8731 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8732 if (Entry.otherName().empty())
8733 outs() << " (from " << DylibName << ")";
8735 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
8741 //===----------------------------------------------------------------------===//
8742 // rebase table dumping
8743 //===----------------------------------------------------------------------===//
8748 SegInfo(const object::MachOObjectFile *Obj);
8750 StringRef segmentName(uint32_t SegIndex);
8751 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8752 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
8753 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
8756 struct SectionInfo {
8759 StringRef SectionName;
8760 StringRef SegmentName;
8761 uint64_t OffsetInSegment;
8762 uint64_t SegmentStartAddress;
8763 uint32_t SegmentIndex;
8765 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8766 SmallVector<SectionInfo, 32> Sections;
8770 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8771 // Build table of sections so segIndex/offset pairs can be translated.
8772 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
8773 StringRef CurSegName;
8774 uint64_t CurSegAddress;
8775 for (const SectionRef &Section : Obj->sections()) {
8777 error(Section.getName(Info.SectionName));
8778 Info.Address = Section.getAddress();
8779 Info.Size = Section.getSize();
8781 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8782 if (!Info.SegmentName.equals(CurSegName)) {
8784 CurSegName = Info.SegmentName;
8785 CurSegAddress = Info.Address;
8787 Info.SegmentIndex = CurSegIndex - 1;
8788 Info.OffsetInSegment = Info.Address - CurSegAddress;
8789 Info.SegmentStartAddress = CurSegAddress;
8790 Sections.push_back(Info);
8794 StringRef SegInfo::segmentName(uint32_t SegIndex) {
8795 for (const SectionInfo &SI : Sections) {
8796 if (SI.SegmentIndex == SegIndex)
8797 return SI.SegmentName;
8799 llvm_unreachable("invalid segIndex");
8802 bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
8803 uint64_t OffsetInSeg) {
8804 for (const SectionInfo &SI : Sections) {
8805 if (SI.SegmentIndex != SegIndex)
8807 if (SI.OffsetInSegment > OffsetInSeg)
8809 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8816 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8817 uint64_t OffsetInSeg) {
8818 for (const SectionInfo &SI : Sections) {
8819 if (SI.SegmentIndex != SegIndex)
8821 if (SI.OffsetInSegment > OffsetInSeg)
8823 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8827 llvm_unreachable("segIndex and offset not in any section");
8830 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8831 return findSection(SegIndex, OffsetInSeg).SectionName;
8834 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8835 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8836 return SI.SegmentStartAddress + OffsetInSeg;
8839 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8840 // Build table of sections so names can used in final output.
8841 SegInfo sectionTable(Obj);
8843 outs() << "segment section address type\n";
8844 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8845 uint32_t SegIndex = Entry.segmentIndex();
8846 uint64_t OffsetInSeg = Entry.segmentOffset();
8847 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8848 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8849 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8851 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
8852 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8853 SegmentName.str().c_str(), SectionName.str().c_str(),
8854 Address, Entry.typeName().str().c_str());
8858 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8859 StringRef DylibName;
8861 case MachO::BIND_SPECIAL_DYLIB_SELF:
8862 return "this-image";
8863 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8864 return "main-executable";
8865 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8866 return "flat-namespace";
8869 std::error_code EC =
8870 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
8872 return "<<bad library ordinal>>";
8876 return "<<unknown special ordinal>>";
8879 //===----------------------------------------------------------------------===//
8880 // bind table dumping
8881 //===----------------------------------------------------------------------===//
8883 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8884 // Build table of sections so names can used in final output.
8885 SegInfo sectionTable(Obj);
8887 outs() << "segment section address type "
8888 "addend dylib symbol\n";
8889 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8890 uint32_t SegIndex = Entry.segmentIndex();
8891 uint64_t OffsetInSeg = Entry.segmentOffset();
8892 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8893 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8894 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8896 // Table lines look like:
8897 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
8899 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
8900 Attr = " (weak_import)";
8901 outs() << left_justify(SegmentName, 8) << " "
8902 << left_justify(SectionName, 18) << " "
8903 << format_hex(Address, 10, true) << " "
8904 << left_justify(Entry.typeName(), 8) << " "
8905 << format_decimal(Entry.addend(), 8) << " "
8906 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8907 << Entry.symbolName() << Attr << "\n";
8911 //===----------------------------------------------------------------------===//
8912 // lazy bind table dumping
8913 //===----------------------------------------------------------------------===//
8915 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8916 // Build table of sections so names can used in final output.
8917 SegInfo sectionTable(Obj);
8919 outs() << "segment section address "
8921 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8922 uint32_t SegIndex = Entry.segmentIndex();
8923 uint64_t OffsetInSeg = Entry.segmentOffset();
8924 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8925 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8926 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8928 // Table lines look like:
8929 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
8930 outs() << left_justify(SegmentName, 8) << " "
8931 << left_justify(SectionName, 18) << " "
8932 << format_hex(Address, 10, true) << " "
8933 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8934 << Entry.symbolName() << "\n";
8938 //===----------------------------------------------------------------------===//
8939 // weak bind table dumping
8940 //===----------------------------------------------------------------------===//
8942 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8943 // Build table of sections so names can used in final output.
8944 SegInfo sectionTable(Obj);
8946 outs() << "segment section address "
8947 "type addend symbol\n";
8948 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8949 // Strong symbols don't have a location to update.
8950 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
8951 outs() << " strong "
8952 << Entry.symbolName() << "\n";
8955 uint32_t SegIndex = Entry.segmentIndex();
8956 uint64_t OffsetInSeg = Entry.segmentOffset();
8957 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8958 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8959 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8961 // Table lines look like:
8962 // __DATA __data 0x00001000 pointer 0 _foo
8963 outs() << left_justify(SegmentName, 8) << " "
8964 << left_justify(SectionName, 18) << " "
8965 << format_hex(Address, 10, true) << " "
8966 << left_justify(Entry.typeName(), 8) << " "
8967 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8972 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
8973 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8974 // information for that address. If the address is found its binding symbol
8975 // name is returned. If not nullptr is returned.
8976 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8977 struct DisassembleInfo *info) {
8978 if (info->bindtable == nullptr) {
8979 info->bindtable = new (BindTable);
8980 SegInfo sectionTable(info->O);
8981 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8982 uint32_t SegIndex = Entry.segmentIndex();
8983 uint64_t OffsetInSeg = Entry.segmentOffset();
8984 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8986 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8987 const char *SymbolName = nullptr;
8988 StringRef name = Entry.symbolName();
8990 SymbolName = name.data();
8991 info->bindtable->push_back(std::make_pair(Address, SymbolName));
8994 for (bind_table_iterator BI = info->bindtable->begin(),
8995 BE = info->bindtable->end();
8997 uint64_t Address = BI->first;
8998 if (ReferenceValue == Address) {
8999 const char *SymbolName = BI->second;