1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the MachO-specific dumper for llvm-objdump.
12 //===----------------------------------------------------------------------===//
14 #include "llvm-objdump.h"
15 #include "llvm-c/Disassembler.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/DebugInfo/DIContext.h"
21 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCDisassembler.h"
25 #include "llvm/MC/MCInst.h"
26 #include "llvm/MC/MCInstPrinter.h"
27 #include "llvm/MC/MCInstrDesc.h"
28 #include "llvm/MC/MCInstrInfo.h"
29 #include "llvm/MC/MCRegisterInfo.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/Object/MachO.h"
32 #include "llvm/Object/MachOUniversal.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Endian.h"
37 #include "llvm/Support/Format.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/GraphWriter.h"
40 #include "llvm/Support/LEB128.h"
41 #include "llvm/Support/MachO.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/raw_ostream.h"
48 #include <system_error>
55 using namespace object;
59 cl::desc("Print line information from debug info if available"));
61 static cl::opt<std::string> DSYMFile("dsym",
62 cl::desc("Use .dSYM file for debug info"));
64 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
65 cl::desc("Print full leading address"));
67 static cl::opt<bool> NoLeadingAddr("no-leading-addr",
68 cl::desc("Print no leading address"));
70 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
71 cl::desc("Print Mach-O universal headers "
72 "(requires -macho)"));
75 llvm::ArchiveHeaders("archive-headers",
76 cl::desc("Print archive headers for Mach-O archives "
77 "(requires -macho)"));
80 ArchiveMemberOffsets("archive-member-offsets",
81 cl::desc("Print the offset to each archive member for "
82 "Mach-O archives (requires -macho and "
83 "-archive-headers)"));
86 llvm::IndirectSymbols("indirect-symbols",
87 cl::desc("Print indirect symbol table for Mach-O "
88 "objects (requires -macho)"));
91 llvm::DataInCode("data-in-code",
92 cl::desc("Print the data in code table for Mach-O objects "
93 "(requires -macho)"));
96 llvm::LinkOptHints("link-opt-hints",
97 cl::desc("Print the linker optimization hints for "
98 "Mach-O objects (requires -macho)"));
100 cl::list<std::string>
101 llvm::DumpSections("section",
102 cl::desc("Prints the specified segment,section for "
103 "Mach-O objects (requires -macho)"));
105 cl::opt<bool> llvm::Raw("raw",
106 cl::desc("Have -section dump the raw binary contents"));
109 llvm::InfoPlist("info-plist",
110 cl::desc("Print the info plist section as strings for "
111 "Mach-O objects (requires -macho)"));
114 llvm::DylibsUsed("dylibs-used",
115 cl::desc("Print the shared libraries used for linked "
116 "Mach-O files (requires -macho)"));
119 llvm::DylibId("dylib-id",
120 cl::desc("Print the shared library's id for the dylib Mach-O "
121 "file (requires -macho)"));
124 llvm::NonVerbose("non-verbose",
125 cl::desc("Print the info for Mach-O objects in "
126 "non-verbose or numeric form (requires -macho)"));
129 llvm::ObjcMetaData("objc-meta-data",
130 cl::desc("Print the Objective-C runtime meta data for "
131 "Mach-O files (requires -macho)"));
133 cl::opt<std::string> llvm::DisSymName(
135 cl::desc("disassemble just this symbol's instructions (requires -macho"));
137 static cl::opt<bool> NoSymbolicOperands(
138 "no-symbolic-operands",
139 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
141 static cl::list<std::string>
142 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
144 bool ArchAll = false;
146 static std::string ThumbTripleName;
148 static const Target *GetTarget(const MachOObjectFile *MachOObj,
149 const char **McpuDefault,
150 const Target **ThumbTarget) {
151 // Figure out the target triple.
152 if (TripleName.empty()) {
153 llvm::Triple TT("unknown-unknown-unknown");
154 llvm::Triple ThumbTriple = Triple();
155 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
156 TripleName = TT.str();
157 ThumbTripleName = ThumbTriple.str();
160 // Get the target specific parser.
162 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
163 if (TheTarget && ThumbTripleName.empty())
166 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
170 errs() << "llvm-objdump: error: unable to get target for '";
172 errs() << TripleName;
174 errs() << ThumbTripleName;
175 errs() << "', see --version and --triple.\n";
179 struct SymbolSorter {
180 bool operator()(const SymbolRef &A, const SymbolRef &B) {
181 uint64_t AAddr = (A.getType() != SymbolRef::ST_Function) ? 0 : A.getValue();
182 uint64_t BAddr = (B.getType() != SymbolRef::ST_Function) ? 0 : B.getValue();
183 return AAddr < BAddr;
187 // Types for the storted data in code table that is built before disassembly
188 // and the predicate function to sort them.
189 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
190 typedef std::vector<DiceTableEntry> DiceTable;
191 typedef DiceTable::iterator dice_table_iterator;
193 // This is used to search for a data in code table entry for the PC being
194 // disassembled. The j parameter has the PC in j.first. A single data in code
195 // table entry can cover many bytes for each of its Kind's. So if the offset,
196 // aka the i.first value, of the data in code table entry plus its Length
197 // covers the PC being searched for this will return true. If not it will
199 static bool compareDiceTableEntries(const DiceTableEntry &i,
200 const DiceTableEntry &j) {
202 i.second.getLength(Length);
204 return j.first >= i.first && j.first < i.first + Length;
207 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
208 unsigned short Kind) {
209 uint32_t Value, Size = 1;
213 case MachO::DICE_KIND_DATA:
216 dumpBytes(ArrayRef<uint8_t>(bytes, 4), outs());
217 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
218 outs() << "\t.long " << Value;
220 } else if (Length >= 2) {
222 dumpBytes(ArrayRef<uint8_t>(bytes, 2), outs());
223 Value = bytes[1] << 8 | bytes[0];
224 outs() << "\t.short " << Value;
228 dumpBytes(ArrayRef<uint8_t>(bytes, 2), outs());
230 outs() << "\t.byte " << Value;
233 if (Kind == MachO::DICE_KIND_DATA)
234 outs() << "\t@ KIND_DATA\n";
236 outs() << "\t@ data in code kind = " << Kind << "\n";
238 case MachO::DICE_KIND_JUMP_TABLE8:
240 dumpBytes(ArrayRef<uint8_t>(bytes, 1), outs());
242 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
245 case MachO::DICE_KIND_JUMP_TABLE16:
247 dumpBytes(ArrayRef<uint8_t>(bytes, 2), outs());
248 Value = bytes[1] << 8 | bytes[0];
249 outs() << "\t.short " << format("%5u", Value & 0xffff)
250 << "\t@ KIND_JUMP_TABLE16\n";
253 case MachO::DICE_KIND_JUMP_TABLE32:
254 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
256 dumpBytes(ArrayRef<uint8_t>(bytes, 4), outs());
257 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
258 outs() << "\t.long " << Value;
259 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
260 outs() << "\t@ KIND_JUMP_TABLE32\n";
262 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
269 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
270 std::vector<SectionRef> &Sections,
271 std::vector<SymbolRef> &Symbols,
272 SmallVectorImpl<uint64_t> &FoundFns,
273 uint64_t &BaseSegmentAddress) {
274 for (const SymbolRef &Symbol : MachOObj->symbols()) {
275 ErrorOr<StringRef> SymName = Symbol.getName();
276 if (std::error_code EC = SymName.getError())
277 report_fatal_error(EC.message());
278 if (!SymName->startswith("ltmp"))
279 Symbols.push_back(Symbol);
282 for (const SectionRef &Section : MachOObj->sections()) {
284 Section.getName(SectName);
285 Sections.push_back(Section);
288 bool BaseSegmentAddressSet = false;
289 for (const auto &Command : MachOObj->load_commands()) {
290 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
291 // We found a function starts segment, parse the addresses for later
293 MachO::linkedit_data_command LLC =
294 MachOObj->getLinkeditDataLoadCommand(Command);
296 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
297 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
298 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
299 StringRef SegName = SLC.segname;
300 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
301 BaseSegmentAddressSet = true;
302 BaseSegmentAddress = SLC.vmaddr;
308 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
309 uint32_t n, uint32_t count,
310 uint32_t stride, uint64_t addr) {
311 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
312 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
313 if (n > nindirectsyms)
314 outs() << " (entries start past the end of the indirect symbol "
315 "table) (reserved1 field greater than the table size)";
316 else if (n + count > nindirectsyms)
317 outs() << " (entries extends past the end of the indirect symbol "
320 uint32_t cputype = O->getHeader().cputype;
321 if (cputype & MachO::CPU_ARCH_ABI64)
322 outs() << "address index";
324 outs() << "address index";
329 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
330 if (cputype & MachO::CPU_ARCH_ABI64)
331 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
333 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
334 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
335 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
336 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
340 if (indirect_symbol ==
341 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
342 outs() << "LOCAL ABSOLUTE\n";
345 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
346 outs() << "ABSOLUTE\n";
349 outs() << format("%5u ", indirect_symbol);
351 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
352 if (indirect_symbol < Symtab.nsyms) {
353 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
354 SymbolRef Symbol = *Sym;
355 ErrorOr<StringRef> SymName = Symbol.getName();
356 if (std::error_code EC = SymName.getError())
357 report_fatal_error(EC.message());
367 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
368 for (const auto &Load : O->load_commands()) {
369 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
370 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
371 for (unsigned J = 0; J < Seg.nsects; ++J) {
372 MachO::section_64 Sec = O->getSection64(Load, J);
373 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
374 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
375 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
376 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
377 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
378 section_type == MachO::S_SYMBOL_STUBS) {
380 if (section_type == MachO::S_SYMBOL_STUBS)
381 stride = Sec.reserved2;
385 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
386 << Sec.sectname << ") "
387 << "(size of stubs in reserved2 field is zero)\n";
390 uint32_t count = Sec.size / stride;
391 outs() << "Indirect symbols for (" << Sec.segname << ","
392 << Sec.sectname << ") " << count << " entries";
393 uint32_t n = Sec.reserved1;
394 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
397 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
398 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
399 for (unsigned J = 0; J < Seg.nsects; ++J) {
400 MachO::section Sec = O->getSection(Load, J);
401 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
402 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
403 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
404 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
405 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
406 section_type == MachO::S_SYMBOL_STUBS) {
408 if (section_type == MachO::S_SYMBOL_STUBS)
409 stride = Sec.reserved2;
413 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
414 << Sec.sectname << ") "
415 << "(size of stubs in reserved2 field is zero)\n";
418 uint32_t count = Sec.size / stride;
419 outs() << "Indirect symbols for (" << Sec.segname << ","
420 << Sec.sectname << ") " << count << " entries";
421 uint32_t n = Sec.reserved1;
422 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
429 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
430 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
431 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
432 outs() << "Data in code table (" << nentries << " entries)\n";
433 outs() << "offset length kind\n";
434 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
437 DI->getOffset(Offset);
438 outs() << format("0x%08" PRIx32, Offset) << " ";
440 DI->getLength(Length);
441 outs() << format("%6u", Length) << " ";
446 case MachO::DICE_KIND_DATA:
449 case MachO::DICE_KIND_JUMP_TABLE8:
450 outs() << "JUMP_TABLE8";
452 case MachO::DICE_KIND_JUMP_TABLE16:
453 outs() << "JUMP_TABLE16";
455 case MachO::DICE_KIND_JUMP_TABLE32:
456 outs() << "JUMP_TABLE32";
458 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
459 outs() << "ABS_JUMP_TABLE32";
462 outs() << format("0x%04" PRIx32, Kind);
466 outs() << format("0x%04" PRIx32, Kind);
471 static void PrintLinkOptHints(MachOObjectFile *O) {
472 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
473 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
474 uint32_t nloh = LohLC.datasize;
475 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
476 for (uint32_t i = 0; i < nloh;) {
478 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
480 outs() << " identifier " << identifier << " ";
483 switch (identifier) {
485 outs() << "AdrpAdrp\n";
488 outs() << "AdrpLdr\n";
491 outs() << "AdrpAddLdr\n";
494 outs() << "AdrpLdrGotLdr\n";
497 outs() << "AdrpAddStr\n";
500 outs() << "AdrpLdrGotStr\n";
503 outs() << "AdrpAdd\n";
506 outs() << "AdrpLdrGot\n";
509 outs() << "Unknown identifier value\n";
512 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
514 outs() << " narguments " << narguments << "\n";
518 for (uint32_t j = 0; j < narguments; j++) {
519 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
521 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
528 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
530 for (const auto &Load : O->load_commands()) {
531 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
532 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
533 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
534 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
535 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
536 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
537 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
538 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
539 if (dl.dylib.name < dl.cmdsize) {
540 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
545 outs() << " (compatibility version "
546 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
547 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
548 << (dl.dylib.compatibility_version & 0xff) << ",";
549 outs() << " current version "
550 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
551 << ((dl.dylib.current_version >> 8) & 0xff) << "."
552 << (dl.dylib.current_version & 0xff) << ")\n";
555 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
556 if (Load.C.cmd == MachO::LC_ID_DYLIB)
557 outs() << "LC_ID_DYLIB ";
558 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
559 outs() << "LC_LOAD_DYLIB ";
560 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
561 outs() << "LC_LOAD_WEAK_DYLIB ";
562 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
563 outs() << "LC_LAZY_LOAD_DYLIB ";
564 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
565 outs() << "LC_REEXPORT_DYLIB ";
566 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
567 outs() << "LC_LOAD_UPWARD_DYLIB ";
570 outs() << "command " << Index++ << "\n";
576 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
578 static void CreateSymbolAddressMap(MachOObjectFile *O,
579 SymbolAddressMap *AddrMap) {
580 // Create a map of symbol addresses to symbol names.
581 for (const SymbolRef &Symbol : O->symbols()) {
582 SymbolRef::Type ST = Symbol.getType();
583 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
584 ST == SymbolRef::ST_Other) {
585 uint64_t Address = Symbol.getValue();
586 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
587 if (std::error_code EC = SymNameOrErr.getError())
588 report_fatal_error(EC.message());
589 StringRef SymName = *SymNameOrErr;
590 if (!SymName.startswith(".objc"))
591 (*AddrMap)[Address] = SymName;
596 // GuessSymbolName is passed the address of what might be a symbol and a
597 // pointer to the SymbolAddressMap. It returns the name of a symbol
598 // with that address or nullptr if no symbol is found with that address.
599 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
600 const char *SymbolName = nullptr;
601 // A DenseMap can't lookup up some values.
602 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
603 StringRef name = AddrMap->lookup(value);
605 SymbolName = name.data();
610 static void DumpCstringChar(const char c) {
614 outs().write_escaped(p);
617 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
618 uint32_t sect_size, uint64_t sect_addr,
619 bool print_addresses) {
620 for (uint32_t i = 0; i < sect_size; i++) {
621 if (print_addresses) {
623 outs() << format("%016" PRIx64, sect_addr + i) << " ";
625 outs() << format("%08" PRIx64, sect_addr + i) << " ";
627 for (; i < sect_size && sect[i] != '\0'; i++)
628 DumpCstringChar(sect[i]);
629 if (i < sect_size && sect[i] == '\0')
634 static void DumpLiteral4(uint32_t l, float f) {
635 outs() << format("0x%08" PRIx32, l);
636 if ((l & 0x7f800000) != 0x7f800000)
637 outs() << format(" (%.16e)\n", f);
640 outs() << " (+Infinity)\n";
641 else if (l == 0xff800000)
642 outs() << " (-Infinity)\n";
643 else if ((l & 0x00400000) == 0x00400000)
644 outs() << " (non-signaling Not-a-Number)\n";
646 outs() << " (signaling Not-a-Number)\n";
650 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
651 uint32_t sect_size, uint64_t sect_addr,
652 bool print_addresses) {
653 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
654 if (print_addresses) {
656 outs() << format("%016" PRIx64, sect_addr + i) << " ";
658 outs() << format("%08" PRIx64, sect_addr + i) << " ";
661 memcpy(&f, sect + i, sizeof(float));
662 if (O->isLittleEndian() != sys::IsLittleEndianHost)
663 sys::swapByteOrder(f);
665 memcpy(&l, sect + i, sizeof(uint32_t));
666 if (O->isLittleEndian() != sys::IsLittleEndianHost)
667 sys::swapByteOrder(l);
672 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
674 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
676 if (O->isLittleEndian()) {
683 // Hi is the high word, so this is equivalent to if(isfinite(d))
684 if ((Hi & 0x7ff00000) != 0x7ff00000)
685 outs() << format(" (%.16e)\n", d);
687 if (Hi == 0x7ff00000 && Lo == 0)
688 outs() << " (+Infinity)\n";
689 else if (Hi == 0xfff00000 && Lo == 0)
690 outs() << " (-Infinity)\n";
691 else if ((Hi & 0x00080000) == 0x00080000)
692 outs() << " (non-signaling Not-a-Number)\n";
694 outs() << " (signaling Not-a-Number)\n";
698 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
699 uint32_t sect_size, uint64_t sect_addr,
700 bool print_addresses) {
701 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
702 if (print_addresses) {
704 outs() << format("%016" PRIx64, sect_addr + i) << " ";
706 outs() << format("%08" PRIx64, sect_addr + i) << " ";
709 memcpy(&d, sect + i, sizeof(double));
710 if (O->isLittleEndian() != sys::IsLittleEndianHost)
711 sys::swapByteOrder(d);
713 memcpy(&l0, sect + i, sizeof(uint32_t));
714 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
715 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
716 sys::swapByteOrder(l0);
717 sys::swapByteOrder(l1);
719 DumpLiteral8(O, l0, l1, d);
723 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
724 outs() << format("0x%08" PRIx32, l0) << " ";
725 outs() << format("0x%08" PRIx32, l1) << " ";
726 outs() << format("0x%08" PRIx32, l2) << " ";
727 outs() << format("0x%08" PRIx32, l3) << "\n";
730 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
731 uint32_t sect_size, uint64_t sect_addr,
732 bool print_addresses) {
733 for (uint32_t i = 0; i < sect_size; i += 16) {
734 if (print_addresses) {
736 outs() << format("%016" PRIx64, sect_addr + i) << " ";
738 outs() << format("%08" PRIx64, sect_addr + i) << " ";
740 uint32_t l0, l1, l2, l3;
741 memcpy(&l0, sect + i, sizeof(uint32_t));
742 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
743 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
744 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
745 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
746 sys::swapByteOrder(l0);
747 sys::swapByteOrder(l1);
748 sys::swapByteOrder(l2);
749 sys::swapByteOrder(l3);
751 DumpLiteral16(l0, l1, l2, l3);
755 static void DumpLiteralPointerSection(MachOObjectFile *O,
756 const SectionRef &Section,
757 const char *sect, uint32_t sect_size,
759 bool print_addresses) {
760 // Collect the literal sections in this Mach-O file.
761 std::vector<SectionRef> LiteralSections;
762 for (const SectionRef &Section : O->sections()) {
763 DataRefImpl Ref = Section.getRawDataRefImpl();
764 uint32_t section_type;
766 const MachO::section_64 Sec = O->getSection64(Ref);
767 section_type = Sec.flags & MachO::SECTION_TYPE;
769 const MachO::section Sec = O->getSection(Ref);
770 section_type = Sec.flags & MachO::SECTION_TYPE;
772 if (section_type == MachO::S_CSTRING_LITERALS ||
773 section_type == MachO::S_4BYTE_LITERALS ||
774 section_type == MachO::S_8BYTE_LITERALS ||
775 section_type == MachO::S_16BYTE_LITERALS)
776 LiteralSections.push_back(Section);
779 // Set the size of the literal pointer.
780 uint32_t lp_size = O->is64Bit() ? 8 : 4;
782 // Collect the external relocation symbols for the literal pointers.
783 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
784 for (const RelocationRef &Reloc : Section.relocations()) {
786 MachO::any_relocation_info RE;
787 bool isExtern = false;
788 Rel = Reloc.getRawDataRefImpl();
789 RE = O->getRelocation(Rel);
790 isExtern = O->getPlainRelocationExternal(RE);
792 uint64_t RelocOffset = Reloc.getOffset();
793 symbol_iterator RelocSym = Reloc.getSymbol();
794 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
797 array_pod_sort(Relocs.begin(), Relocs.end());
799 // Dump each literal pointer.
800 for (uint32_t i = 0; i < sect_size; i += lp_size) {
801 if (print_addresses) {
803 outs() << format("%016" PRIx64, sect_addr + i) << " ";
805 outs() << format("%08" PRIx64, sect_addr + i) << " ";
809 memcpy(&lp, sect + i, sizeof(uint64_t));
810 if (O->isLittleEndian() != sys::IsLittleEndianHost)
811 sys::swapByteOrder(lp);
814 memcpy(&li, sect + i, sizeof(uint32_t));
815 if (O->isLittleEndian() != sys::IsLittleEndianHost)
816 sys::swapByteOrder(li);
820 // First look for an external relocation entry for this literal pointer.
821 auto Reloc = std::find_if(
822 Relocs.begin(), Relocs.end(),
823 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
824 if (Reloc != Relocs.end()) {
825 symbol_iterator RelocSym = Reloc->second;
826 ErrorOr<StringRef> SymName = RelocSym->getName();
827 if (std::error_code EC = SymName.getError())
828 report_fatal_error(EC.message());
829 outs() << "external relocation entry for symbol:" << *SymName << "\n";
833 // For local references see what the section the literal pointer points to.
834 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
835 [&](const SectionRef &R) {
836 return lp >= R.getAddress() &&
837 lp < R.getAddress() + R.getSize();
839 if (Sect == LiteralSections.end()) {
840 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
844 uint64_t SectAddress = Sect->getAddress();
845 uint64_t SectSize = Sect->getSize();
848 Sect->getName(SectName);
849 DataRefImpl Ref = Sect->getRawDataRefImpl();
850 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
851 outs() << SegmentName << ":" << SectName << ":";
853 uint32_t section_type;
855 const MachO::section_64 Sec = O->getSection64(Ref);
856 section_type = Sec.flags & MachO::SECTION_TYPE;
858 const MachO::section Sec = O->getSection(Ref);
859 section_type = Sec.flags & MachO::SECTION_TYPE;
863 Sect->getContents(BytesStr);
864 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
866 switch (section_type) {
867 case MachO::S_CSTRING_LITERALS:
868 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
870 DumpCstringChar(Contents[i]);
874 case MachO::S_4BYTE_LITERALS:
876 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
878 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
879 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
880 sys::swapByteOrder(f);
881 sys::swapByteOrder(l);
885 case MachO::S_8BYTE_LITERALS: {
887 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
889 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
890 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
892 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
893 sys::swapByteOrder(f);
894 sys::swapByteOrder(l0);
895 sys::swapByteOrder(l1);
897 DumpLiteral8(O, l0, l1, d);
900 case MachO::S_16BYTE_LITERALS: {
901 uint32_t l0, l1, l2, l3;
902 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
903 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
905 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
907 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
909 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
910 sys::swapByteOrder(l0);
911 sys::swapByteOrder(l1);
912 sys::swapByteOrder(l2);
913 sys::swapByteOrder(l3);
915 DumpLiteral16(l0, l1, l2, l3);
922 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
923 uint32_t sect_size, uint64_t sect_addr,
924 SymbolAddressMap *AddrMap,
928 stride = sizeof(uint64_t);
930 stride = sizeof(uint32_t);
931 for (uint32_t i = 0; i < sect_size; i += stride) {
932 const char *SymbolName = nullptr;
934 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
935 uint64_t pointer_value;
936 memcpy(&pointer_value, sect + i, stride);
937 if (O->isLittleEndian() != sys::IsLittleEndianHost)
938 sys::swapByteOrder(pointer_value);
939 outs() << format("0x%016" PRIx64, pointer_value);
941 SymbolName = GuessSymbolName(pointer_value, AddrMap);
943 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
944 uint32_t pointer_value;
945 memcpy(&pointer_value, sect + i, stride);
946 if (O->isLittleEndian() != sys::IsLittleEndianHost)
947 sys::swapByteOrder(pointer_value);
948 outs() << format("0x%08" PRIx32, pointer_value);
950 SymbolName = GuessSymbolName(pointer_value, AddrMap);
953 outs() << " " << SymbolName;
958 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
959 uint32_t size, uint64_t addr) {
960 uint32_t cputype = O->getHeader().cputype;
961 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
963 for (uint32_t i = 0; i < size; i += j, addr += j) {
965 outs() << format("%016" PRIx64, addr) << "\t";
967 outs() << format("%08" PRIx64, addr) << "\t";
968 for (j = 0; j < 16 && i + j < size; j++) {
969 uint8_t byte_word = *(sect + i + j);
970 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
976 for (uint32_t i = 0; i < size; i += j, addr += j) {
978 outs() << format("%016" PRIx64, addr) << "\t";
980 outs() << format("%08" PRIx64, sect) << "\t";
981 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
982 j += sizeof(int32_t)) {
983 if (i + j + sizeof(int32_t) < size) {
985 memcpy(&long_word, sect + i + j, sizeof(int32_t));
986 if (O->isLittleEndian() != sys::IsLittleEndianHost)
987 sys::swapByteOrder(long_word);
988 outs() << format("%08" PRIx32, long_word) << " ";
990 for (uint32_t k = 0; i + j + k < size; k++) {
991 uint8_t byte_word = *(sect + i + j);
992 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1001 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1002 StringRef DisSegName, StringRef DisSectName);
1003 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1004 uint32_t size, uint32_t addr);
1006 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1008 SymbolAddressMap AddrMap;
1010 CreateSymbolAddressMap(O, &AddrMap);
1012 for (unsigned i = 0; i < DumpSections.size(); ++i) {
1013 StringRef DumpSection = DumpSections[i];
1014 std::pair<StringRef, StringRef> DumpSegSectName;
1015 DumpSegSectName = DumpSection.split(',');
1016 StringRef DumpSegName, DumpSectName;
1017 if (DumpSegSectName.second.size()) {
1018 DumpSegName = DumpSegSectName.first;
1019 DumpSectName = DumpSegSectName.second;
1022 DumpSectName = DumpSegSectName.first;
1024 for (const SectionRef &Section : O->sections()) {
1026 Section.getName(SectName);
1027 DataRefImpl Ref = Section.getRawDataRefImpl();
1028 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1029 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1030 (SectName == DumpSectName)) {
1032 uint32_t section_flags;
1034 const MachO::section_64 Sec = O->getSection64(Ref);
1035 section_flags = Sec.flags;
1038 const MachO::section Sec = O->getSection(Ref);
1039 section_flags = Sec.flags;
1041 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1044 Section.getContents(BytesStr);
1045 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1046 uint32_t sect_size = BytesStr.size();
1047 uint64_t sect_addr = Section.getAddress();
1050 outs().write(BytesStr.data(), BytesStr.size());
1054 outs() << "Contents of (" << SegName << "," << SectName
1058 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1059 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1060 DisassembleMachO(Filename, O, SegName, SectName);
1063 if (SegName == "__TEXT" && SectName == "__info_plist") {
1067 if (SegName == "__OBJC" && SectName == "__protocol") {
1068 DumpProtocolSection(O, sect, sect_size, sect_addr);
1071 switch (section_type) {
1072 case MachO::S_REGULAR:
1073 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1075 case MachO::S_ZEROFILL:
1076 outs() << "zerofill section and has no contents in the file\n";
1078 case MachO::S_CSTRING_LITERALS:
1079 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1081 case MachO::S_4BYTE_LITERALS:
1082 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1084 case MachO::S_8BYTE_LITERALS:
1085 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1087 case MachO::S_16BYTE_LITERALS:
1088 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1090 case MachO::S_LITERAL_POINTERS:
1091 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1094 case MachO::S_MOD_INIT_FUNC_POINTERS:
1095 case MachO::S_MOD_TERM_FUNC_POINTERS:
1096 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1100 outs() << "Unknown section type ("
1101 << format("0x%08" PRIx32, section_type) << ")\n";
1102 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1106 if (section_type == MachO::S_ZEROFILL)
1107 outs() << "zerofill section and has no contents in the file\n";
1109 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1116 static void DumpInfoPlistSectionContents(StringRef Filename,
1117 MachOObjectFile *O) {
1118 for (const SectionRef &Section : O->sections()) {
1120 Section.getName(SectName);
1121 DataRefImpl Ref = Section.getRawDataRefImpl();
1122 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1123 if (SegName == "__TEXT" && SectName == "__info_plist") {
1124 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1126 Section.getContents(BytesStr);
1127 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1134 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1135 // and if it is and there is a list of architecture flags is specified then
1136 // check to make sure this Mach-O file is one of those architectures or all
1137 // architectures were specified. If not then an error is generated and this
1138 // routine returns false. Else it returns true.
1139 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1140 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1141 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1142 bool ArchFound = false;
1143 MachO::mach_header H;
1144 MachO::mach_header_64 H_64;
1146 if (MachO->is64Bit()) {
1147 H_64 = MachO->MachOObjectFile::getHeader64();
1148 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1150 H = MachO->MachOObjectFile::getHeader();
1151 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1154 for (i = 0; i < ArchFlags.size(); ++i) {
1155 if (ArchFlags[i] == T.getArchName())
1160 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1161 << "architecture: " + ArchFlags[i] + "\n";
1168 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1170 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1171 // archive member and or in a slice of a universal file. It prints the
1172 // the file name and header info and then processes it according to the
1173 // command line options.
1174 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1175 StringRef ArchiveMemberName = StringRef(),
1176 StringRef ArchitectureName = StringRef()) {
1177 // If we are doing some processing here on the Mach-O file print the header
1178 // info. And don't print it otherwise like in the case of printing the
1179 // UniversalHeaders or ArchiveHeaders.
1180 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
1181 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1182 DylibsUsed || DylibId || ObjcMetaData ||
1183 (DumpSections.size() != 0 && !Raw)) {
1185 if (!ArchiveMemberName.empty())
1186 outs() << '(' << ArchiveMemberName << ')';
1187 if (!ArchitectureName.empty())
1188 outs() << " (architecture " << ArchitectureName << ")";
1193 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1194 if (IndirectSymbols)
1195 PrintIndirectSymbols(MachOOF, !NonVerbose);
1197 PrintDataInCodeTable(MachOOF, !NonVerbose);
1199 PrintLinkOptHints(MachOOF);
1201 PrintRelocations(MachOOF);
1203 PrintSectionHeaders(MachOOF);
1204 if (SectionContents)
1205 PrintSectionContents(MachOOF);
1206 if (DumpSections.size() != 0)
1207 DumpSectionContents(Filename, MachOOF, !NonVerbose);
1209 DumpInfoPlistSectionContents(Filename, MachOOF);
1211 PrintDylibs(MachOOF, false);
1213 PrintDylibs(MachOOF, true);
1215 PrintSymbolTable(MachOOF);
1217 printMachOUnwindInfo(MachOOF);
1219 printMachOFileHeader(MachOOF);
1221 printObjcMetaData(MachOOF, !NonVerbose);
1223 printExportsTrie(MachOOF);
1225 printRebaseTable(MachOOF);
1227 printBindTable(MachOOF);
1229 printLazyBindTable(MachOOF);
1231 printWeakBindTable(MachOOF);
1234 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1235 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1236 outs() << " cputype (" << cputype << ")\n";
1237 outs() << " cpusubtype (" << cpusubtype << ")\n";
1240 // printCPUType() helps print_fat_headers by printing the cputype and
1241 // pusubtype (symbolically for the one's it knows about).
1242 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1244 case MachO::CPU_TYPE_I386:
1245 switch (cpusubtype) {
1246 case MachO::CPU_SUBTYPE_I386_ALL:
1247 outs() << " cputype CPU_TYPE_I386\n";
1248 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1251 printUnknownCPUType(cputype, cpusubtype);
1255 case MachO::CPU_TYPE_X86_64:
1256 switch (cpusubtype) {
1257 case MachO::CPU_SUBTYPE_X86_64_ALL:
1258 outs() << " cputype CPU_TYPE_X86_64\n";
1259 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1261 case MachO::CPU_SUBTYPE_X86_64_H:
1262 outs() << " cputype CPU_TYPE_X86_64\n";
1263 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1266 printUnknownCPUType(cputype, cpusubtype);
1270 case MachO::CPU_TYPE_ARM:
1271 switch (cpusubtype) {
1272 case MachO::CPU_SUBTYPE_ARM_ALL:
1273 outs() << " cputype CPU_TYPE_ARM\n";
1274 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1276 case MachO::CPU_SUBTYPE_ARM_V4T:
1277 outs() << " cputype CPU_TYPE_ARM\n";
1278 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1280 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1281 outs() << " cputype CPU_TYPE_ARM\n";
1282 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1284 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1285 outs() << " cputype CPU_TYPE_ARM\n";
1286 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1288 case MachO::CPU_SUBTYPE_ARM_V6:
1289 outs() << " cputype CPU_TYPE_ARM\n";
1290 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1292 case MachO::CPU_SUBTYPE_ARM_V6M:
1293 outs() << " cputype CPU_TYPE_ARM\n";
1294 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1296 case MachO::CPU_SUBTYPE_ARM_V7:
1297 outs() << " cputype CPU_TYPE_ARM\n";
1298 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1300 case MachO::CPU_SUBTYPE_ARM_V7EM:
1301 outs() << " cputype CPU_TYPE_ARM\n";
1302 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1304 case MachO::CPU_SUBTYPE_ARM_V7K:
1305 outs() << " cputype CPU_TYPE_ARM\n";
1306 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1308 case MachO::CPU_SUBTYPE_ARM_V7M:
1309 outs() << " cputype CPU_TYPE_ARM\n";
1310 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1312 case MachO::CPU_SUBTYPE_ARM_V7S:
1313 outs() << " cputype CPU_TYPE_ARM\n";
1314 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1317 printUnknownCPUType(cputype, cpusubtype);
1321 case MachO::CPU_TYPE_ARM64:
1322 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1323 case MachO::CPU_SUBTYPE_ARM64_ALL:
1324 outs() << " cputype CPU_TYPE_ARM64\n";
1325 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1328 printUnknownCPUType(cputype, cpusubtype);
1333 printUnknownCPUType(cputype, cpusubtype);
1338 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1340 outs() << "Fat headers\n";
1342 outs() << "fat_magic FAT_MAGIC\n";
1344 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1346 uint32_t nfat_arch = UB->getNumberOfObjects();
1347 StringRef Buf = UB->getData();
1348 uint64_t size = Buf.size();
1349 uint64_t big_size = sizeof(struct MachO::fat_header) +
1350 nfat_arch * sizeof(struct MachO::fat_arch);
1351 outs() << "nfat_arch " << UB->getNumberOfObjects();
1353 outs() << " (malformed, contains zero architecture types)\n";
1354 else if (big_size > size)
1355 outs() << " (malformed, architectures past end of file)\n";
1359 for (uint32_t i = 0; i < nfat_arch; ++i) {
1360 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1361 uint32_t cputype = OFA.getCPUType();
1362 uint32_t cpusubtype = OFA.getCPUSubType();
1363 outs() << "architecture ";
1364 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1365 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1366 uint32_t other_cputype = other_OFA.getCPUType();
1367 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1368 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1369 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1370 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1371 outs() << "(illegal duplicate architecture) ";
1376 outs() << OFA.getArchTypeName() << "\n";
1377 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1379 outs() << i << "\n";
1380 outs() << " cputype " << cputype << "\n";
1381 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1385 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1386 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1388 outs() << " capabilities "
1389 << format("0x%" PRIx32,
1390 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1391 outs() << " offset " << OFA.getOffset();
1392 if (OFA.getOffset() > size)
1393 outs() << " (past end of file)";
1394 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1395 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1397 outs() << " size " << OFA.getSize();
1398 big_size = OFA.getOffset() + OFA.getSize();
1399 if (big_size > size)
1400 outs() << " (past end of file)";
1402 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1407 static void printArchiveChild(Archive::Child &C, bool verbose,
1408 bool print_offset) {
1410 outs() << C.getChildOffset() << "\t";
1411 sys::fs::perms Mode = C.getAccessMode();
1413 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1414 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1416 if (Mode & sys::fs::owner_read)
1420 if (Mode & sys::fs::owner_write)
1424 if (Mode & sys::fs::owner_exe)
1428 if (Mode & sys::fs::group_read)
1432 if (Mode & sys::fs::group_write)
1436 if (Mode & sys::fs::group_exe)
1440 if (Mode & sys::fs::others_read)
1444 if (Mode & sys::fs::others_write)
1448 if (Mode & sys::fs::others_exe)
1453 outs() << format("0%o ", Mode);
1456 unsigned UID = C.getUID();
1457 outs() << format("%3d/", UID);
1458 unsigned GID = C.getGID();
1459 outs() << format("%-3d ", GID);
1460 uint64_t Size = C.getRawSize();
1461 outs() << format("%5" PRId64, Size) << " ";
1463 StringRef RawLastModified = C.getRawLastModified();
1466 if (RawLastModified.getAsInteger(10, Seconds))
1467 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1469 // Since cime(3) returns a 26 character string of the form:
1470 // "Sun Sep 16 01:03:52 1973\n\0"
1471 // just print 24 characters.
1473 outs() << format("%.24s ", ctime(&t));
1476 outs() << RawLastModified << " ";
1480 ErrorOr<StringRef> NameOrErr = C.getName();
1481 if (NameOrErr.getError()) {
1482 StringRef RawName = C.getRawName();
1483 outs() << RawName << "\n";
1485 StringRef Name = NameOrErr.get();
1486 outs() << Name << "\n";
1489 StringRef RawName = C.getRawName();
1490 outs() << RawName << "\n";
1494 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1495 if (A->hasSymbolTable()) {
1496 Archive::child_iterator S = A->getSymbolTableChild();
1497 Archive::Child C = *S;
1498 printArchiveChild(C, verbose, print_offset);
1500 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1502 Archive::Child C = *I;
1503 printArchiveChild(C, verbose, print_offset);
1507 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1508 // -arch flags selecting just those slices as specified by them and also parses
1509 // archive files. Then for each individual Mach-O file ProcessMachO() is
1510 // called to process the file based on the command line options.
1511 void llvm::ParseInputMachO(StringRef Filename) {
1512 // Check for -arch all and verifiy the -arch flags are valid.
1513 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1514 if (ArchFlags[i] == "all") {
1517 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1518 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1519 "'for the -arch option\n";
1525 // Attempt to open the binary.
1526 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1527 if (std::error_code EC = BinaryOrErr.getError()) {
1528 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
1531 Binary &Bin = *BinaryOrErr.get().getBinary();
1533 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1534 outs() << "Archive : " << Filename << "\n";
1536 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
1537 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1539 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1540 if (ChildOrErr.getError())
1542 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1543 if (!checkMachOAndArchFlags(O, Filename))
1545 ProcessMachO(Filename, O, O->getFileName());
1550 if (UniversalHeaders) {
1551 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1552 printMachOUniversalHeaders(UB, !NonVerbose);
1554 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1555 // If we have a list of architecture flags specified dump only those.
1556 if (!ArchAll && ArchFlags.size() != 0) {
1557 // Look for a slice in the universal binary that matches each ArchFlag.
1559 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1561 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1562 E = UB->end_objects();
1564 if (ArchFlags[i] == I->getArchTypeName()) {
1566 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1567 I->getAsObjectFile();
1568 std::string ArchitectureName = "";
1569 if (ArchFlags.size() > 1)
1570 ArchitectureName = I->getArchTypeName();
1572 ObjectFile &O = *ObjOrErr.get();
1573 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1574 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1575 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1576 I->getAsArchive()) {
1577 std::unique_ptr<Archive> &A = *AOrErr;
1578 outs() << "Archive : " << Filename;
1579 if (!ArchitectureName.empty())
1580 outs() << " (architecture " << ArchitectureName << ")";
1583 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1584 for (Archive::child_iterator AI = A->child_begin(),
1585 AE = A->child_end();
1587 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1588 if (ChildOrErr.getError())
1590 if (MachOObjectFile *O =
1591 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1592 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1598 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1599 << "architecture: " + ArchFlags[i] + "\n";
1605 // No architecture flags were specified so if this contains a slice that
1606 // matches the host architecture dump only that.
1608 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1609 E = UB->end_objects();
1611 if (MachOObjectFile::getHostArch().getArchName() ==
1612 I->getArchTypeName()) {
1613 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1614 std::string ArchiveName;
1615 ArchiveName.clear();
1617 ObjectFile &O = *ObjOrErr.get();
1618 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1619 ProcessMachO(Filename, MachOOF);
1620 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1621 I->getAsArchive()) {
1622 std::unique_ptr<Archive> &A = *AOrErr;
1623 outs() << "Archive : " << Filename << "\n";
1625 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1626 for (Archive::child_iterator AI = A->child_begin(),
1627 AE = A->child_end();
1629 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1630 if (ChildOrErr.getError())
1632 if (MachOObjectFile *O =
1633 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1634 ProcessMachO(Filename, O, O->getFileName());
1641 // Either all architectures have been specified or none have been specified
1642 // and this does not contain the host architecture so dump all the slices.
1643 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1644 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1645 E = UB->end_objects();
1647 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1648 std::string ArchitectureName = "";
1649 if (moreThanOneArch)
1650 ArchitectureName = I->getArchTypeName();
1652 ObjectFile &Obj = *ObjOrErr.get();
1653 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1654 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1655 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1656 std::unique_ptr<Archive> &A = *AOrErr;
1657 outs() << "Archive : " << Filename;
1658 if (!ArchitectureName.empty())
1659 outs() << " (architecture " << ArchitectureName << ")";
1662 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
1663 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1665 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1666 if (ChildOrErr.getError())
1668 if (MachOObjectFile *O =
1669 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1670 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1671 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1679 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1680 if (!checkMachOAndArchFlags(O, Filename))
1682 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1683 ProcessMachO(Filename, MachOOF);
1685 errs() << "llvm-objdump: '" << Filename << "': "
1686 << "Object is not a Mach-O file type.\n";
1688 errs() << "llvm-objdump: '" << Filename << "': "
1689 << "Unrecognized file type.\n";
1692 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1693 typedef std::vector<BindInfoEntry> BindTable;
1694 typedef BindTable::iterator bind_table_iterator;
1696 // The block of info used by the Symbolizer call backs.
1697 struct DisassembleInfo {
1701 SymbolAddressMap *AddrMap;
1702 std::vector<SectionRef> *Sections;
1703 const char *class_name;
1704 const char *selector_name;
1706 char *demangled_name;
1709 BindTable *bindtable;
1712 // SymbolizerGetOpInfo() is the operand information call back function.
1713 // This is called to get the symbolic information for operand(s) of an
1714 // instruction when it is being done. This routine does this from
1715 // the relocation information, symbol table, etc. That block of information
1716 // is a pointer to the struct DisassembleInfo that was passed when the
1717 // disassembler context was created and passed to back to here when
1718 // called back by the disassembler for instruction operands that could have
1719 // relocation information. The address of the instruction containing operand is
1720 // at the Pc parameter. The immediate value the operand has is passed in
1721 // op_info->Value and is at Offset past the start of the instruction and has a
1722 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1723 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1724 // names and addends of the symbolic expression to add for the operand. The
1725 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1726 // information is returned then this function returns 1 else it returns 0.
1727 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1728 uint64_t Size, int TagType, void *TagBuf) {
1729 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1730 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1731 uint64_t value = op_info->Value;
1733 // Make sure all fields returned are zero if we don't set them.
1734 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1735 op_info->Value = value;
1737 // If the TagType is not the value 1 which it code knows about or if no
1738 // verbose symbolic information is wanted then just return 0, indicating no
1739 // information is being returned.
1740 if (TagType != 1 || !info->verbose)
1743 unsigned int Arch = info->O->getArch();
1744 if (Arch == Triple::x86) {
1745 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1747 // First search the section's relocation entries (if any) for an entry
1748 // for this section offset.
1749 uint32_t sect_addr = info->S.getAddress();
1750 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1751 bool reloc_found = false;
1753 MachO::any_relocation_info RE;
1754 bool isExtern = false;
1756 bool r_scattered = false;
1757 uint32_t r_value, pair_r_value, r_type;
1758 for (const RelocationRef &Reloc : info->S.relocations()) {
1759 uint64_t RelocOffset = Reloc.getOffset();
1760 if (RelocOffset == sect_offset) {
1761 Rel = Reloc.getRawDataRefImpl();
1762 RE = info->O->getRelocation(Rel);
1763 r_type = info->O->getAnyRelocationType(RE);
1764 r_scattered = info->O->isRelocationScattered(RE);
1766 r_value = info->O->getScatteredRelocationValue(RE);
1767 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1768 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1769 DataRefImpl RelNext = Rel;
1770 info->O->moveRelocationNext(RelNext);
1771 MachO::any_relocation_info RENext;
1772 RENext = info->O->getRelocation(RelNext);
1773 if (info->O->isRelocationScattered(RENext))
1774 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1779 isExtern = info->O->getPlainRelocationExternal(RE);
1781 symbol_iterator RelocSym = Reloc.getSymbol();
1789 if (reloc_found && isExtern) {
1790 ErrorOr<StringRef> SymName = Symbol.getName();
1791 if (std::error_code EC = SymName.getError())
1792 report_fatal_error(EC.message());
1793 const char *name = SymName->data();
1794 op_info->AddSymbol.Present = 1;
1795 op_info->AddSymbol.Name = name;
1796 // For i386 extern relocation entries the value in the instruction is
1797 // the offset from the symbol, and value is already set in op_info->Value.
1800 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1801 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1802 const char *add = GuessSymbolName(r_value, info->AddrMap);
1803 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1804 uint32_t offset = value - (r_value - pair_r_value);
1805 op_info->AddSymbol.Present = 1;
1807 op_info->AddSymbol.Name = add;
1809 op_info->AddSymbol.Value = r_value;
1810 op_info->SubtractSymbol.Present = 1;
1812 op_info->SubtractSymbol.Name = sub;
1814 op_info->SubtractSymbol.Value = pair_r_value;
1815 op_info->Value = offset;
1819 // Second search the external relocation entries of a fully linked image
1820 // (if any) for an entry that matches this segment offset.
1821 // uint32_t seg_offset = (Pc + Offset);
1824 if (Arch == Triple::x86_64) {
1825 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1827 // First search the section's relocation entries (if any) for an entry
1828 // for this section offset.
1829 uint64_t sect_addr = info->S.getAddress();
1830 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1831 bool reloc_found = false;
1833 MachO::any_relocation_info RE;
1834 bool isExtern = false;
1836 for (const RelocationRef &Reloc : info->S.relocations()) {
1837 uint64_t RelocOffset = Reloc.getOffset();
1838 if (RelocOffset == sect_offset) {
1839 Rel = Reloc.getRawDataRefImpl();
1840 RE = info->O->getRelocation(Rel);
1841 // NOTE: Scattered relocations don't exist on x86_64.
1842 isExtern = info->O->getPlainRelocationExternal(RE);
1844 symbol_iterator RelocSym = Reloc.getSymbol();
1851 if (reloc_found && isExtern) {
1852 // The Value passed in will be adjusted by the Pc if the instruction
1853 // adds the Pc. But for x86_64 external relocation entries the Value
1854 // is the offset from the external symbol.
1855 if (info->O->getAnyRelocationPCRel(RE))
1856 op_info->Value -= Pc + Offset + Size;
1857 ErrorOr<StringRef> SymName = Symbol.getName();
1858 if (std::error_code EC = SymName.getError())
1859 report_fatal_error(EC.message());
1860 const char *name = SymName->data();
1861 unsigned Type = info->O->getAnyRelocationType(RE);
1862 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1863 DataRefImpl RelNext = Rel;
1864 info->O->moveRelocationNext(RelNext);
1865 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1866 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1867 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1868 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1869 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1870 op_info->SubtractSymbol.Present = 1;
1871 op_info->SubtractSymbol.Name = name;
1872 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1873 Symbol = *RelocSymNext;
1874 ErrorOr<StringRef> SymNameNext = Symbol.getName();
1875 if (std::error_code EC = SymNameNext.getError())
1876 report_fatal_error(EC.message());
1877 name = SymNameNext->data();
1880 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1881 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1882 op_info->AddSymbol.Present = 1;
1883 op_info->AddSymbol.Name = name;
1887 // Second search the external relocation entries of a fully linked image
1888 // (if any) for an entry that matches this segment offset.
1889 // uint64_t seg_offset = (Pc + Offset);
1892 if (Arch == Triple::arm) {
1893 if (Offset != 0 || (Size != 4 && Size != 2))
1895 // First search the section's relocation entries (if any) for an entry
1896 // for this section offset.
1897 uint32_t sect_addr = info->S.getAddress();
1898 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1900 MachO::any_relocation_info RE;
1901 bool isExtern = false;
1903 bool r_scattered = false;
1904 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1906 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1907 [&](const RelocationRef &Reloc) {
1908 uint64_t RelocOffset = Reloc.getOffset();
1909 return RelocOffset == sect_offset;
1912 if (Reloc == info->S.relocations().end())
1915 Rel = Reloc->getRawDataRefImpl();
1916 RE = info->O->getRelocation(Rel);
1917 r_length = info->O->getAnyRelocationLength(RE);
1918 r_scattered = info->O->isRelocationScattered(RE);
1920 r_value = info->O->getScatteredRelocationValue(RE);
1921 r_type = info->O->getScatteredRelocationType(RE);
1923 r_type = info->O->getAnyRelocationType(RE);
1924 isExtern = info->O->getPlainRelocationExternal(RE);
1926 symbol_iterator RelocSym = Reloc->getSymbol();
1930 if (r_type == MachO::ARM_RELOC_HALF ||
1931 r_type == MachO::ARM_RELOC_SECTDIFF ||
1932 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1933 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1934 DataRefImpl RelNext = Rel;
1935 info->O->moveRelocationNext(RelNext);
1936 MachO::any_relocation_info RENext;
1937 RENext = info->O->getRelocation(RelNext);
1938 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1939 if (info->O->isRelocationScattered(RENext))
1940 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1944 ErrorOr<StringRef> SymName = Symbol.getName();
1945 if (std::error_code EC = SymName.getError())
1946 report_fatal_error(EC.message());
1947 const char *name = SymName->data();
1948 op_info->AddSymbol.Present = 1;
1949 op_info->AddSymbol.Name = name;
1951 case MachO::ARM_RELOC_HALF:
1952 if ((r_length & 0x1) == 1) {
1953 op_info->Value = value << 16 | other_half;
1954 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1956 op_info->Value = other_half << 16 | value;
1957 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1965 // If we have a branch that is not an external relocation entry then
1966 // return 0 so the code in tryAddingSymbolicOperand() can use the
1967 // SymbolLookUp call back with the branch target address to look up the
1968 // symbol and possiblity add an annotation for a symbol stub.
1969 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1970 r_type == MachO::ARM_THUMB_RELOC_BR22))
1973 uint32_t offset = 0;
1974 if (r_type == MachO::ARM_RELOC_HALF ||
1975 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1976 if ((r_length & 0x1) == 1)
1977 value = value << 16 | other_half;
1979 value = other_half << 16 | value;
1981 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1982 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1983 offset = value - r_value;
1987 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1988 if ((r_length & 0x1) == 1)
1989 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1991 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1992 const char *add = GuessSymbolName(r_value, info->AddrMap);
1993 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1994 int32_t offset = value - (r_value - pair_r_value);
1995 op_info->AddSymbol.Present = 1;
1997 op_info->AddSymbol.Name = add;
1999 op_info->AddSymbol.Value = r_value;
2000 op_info->SubtractSymbol.Present = 1;
2002 op_info->SubtractSymbol.Name = sub;
2004 op_info->SubtractSymbol.Value = pair_r_value;
2005 op_info->Value = offset;
2009 op_info->AddSymbol.Present = 1;
2010 op_info->Value = offset;
2011 if (r_type == MachO::ARM_RELOC_HALF) {
2012 if ((r_length & 0x1) == 1)
2013 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2015 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2017 const char *add = GuessSymbolName(value, info->AddrMap);
2018 if (add != nullptr) {
2019 op_info->AddSymbol.Name = add;
2022 op_info->AddSymbol.Value = value;
2025 if (Arch == Triple::aarch64) {
2026 if (Offset != 0 || Size != 4)
2028 // First search the section's relocation entries (if any) for an entry
2029 // for this section offset.
2030 uint64_t sect_addr = info->S.getAddress();
2031 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2033 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2034 [&](const RelocationRef &Reloc) {
2035 uint64_t RelocOffset = Reloc.getOffset();
2036 return RelocOffset == sect_offset;
2039 if (Reloc == info->S.relocations().end())
2042 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2043 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2044 uint32_t r_type = info->O->getAnyRelocationType(RE);
2045 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2046 DataRefImpl RelNext = Rel;
2047 info->O->moveRelocationNext(RelNext);
2048 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2050 value = info->O->getPlainRelocationSymbolNum(RENext);
2051 op_info->Value = value;
2054 // NOTE: Scattered relocations don't exist on arm64.
2055 if (!info->O->getPlainRelocationExternal(RE))
2057 ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
2058 if (std::error_code EC = SymName.getError())
2059 report_fatal_error(EC.message());
2060 const char *name = SymName->data();
2061 op_info->AddSymbol.Present = 1;
2062 op_info->AddSymbol.Name = name;
2065 case MachO::ARM64_RELOC_PAGE21:
2067 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2069 case MachO::ARM64_RELOC_PAGEOFF12:
2071 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2073 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2075 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2077 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2079 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2081 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2082 /* @tvlppage is not implemented in llvm-mc */
2083 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2085 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2086 /* @tvlppageoff is not implemented in llvm-mc */
2087 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2090 case MachO::ARM64_RELOC_BRANCH26:
2091 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2099 // GuessCstringPointer is passed the address of what might be a pointer to a
2100 // literal string in a cstring section. If that address is in a cstring section
2101 // it returns a pointer to that string. Else it returns nullptr.
2102 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2103 struct DisassembleInfo *info) {
2104 for (const auto &Load : info->O->load_commands()) {
2105 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2106 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2107 for (unsigned J = 0; J < Seg.nsects; ++J) {
2108 MachO::section_64 Sec = info->O->getSection64(Load, J);
2109 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2110 if (section_type == MachO::S_CSTRING_LITERALS &&
2111 ReferenceValue >= Sec.addr &&
2112 ReferenceValue < Sec.addr + Sec.size) {
2113 uint64_t sect_offset = ReferenceValue - Sec.addr;
2114 uint64_t object_offset = Sec.offset + sect_offset;
2115 StringRef MachOContents = info->O->getData();
2116 uint64_t object_size = MachOContents.size();
2117 const char *object_addr = (const char *)MachOContents.data();
2118 if (object_offset < object_size) {
2119 const char *name = object_addr + object_offset;
2126 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2127 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2128 for (unsigned J = 0; J < Seg.nsects; ++J) {
2129 MachO::section Sec = info->O->getSection(Load, J);
2130 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2131 if (section_type == MachO::S_CSTRING_LITERALS &&
2132 ReferenceValue >= Sec.addr &&
2133 ReferenceValue < Sec.addr + Sec.size) {
2134 uint64_t sect_offset = ReferenceValue - Sec.addr;
2135 uint64_t object_offset = Sec.offset + sect_offset;
2136 StringRef MachOContents = info->O->getData();
2137 uint64_t object_size = MachOContents.size();
2138 const char *object_addr = (const char *)MachOContents.data();
2139 if (object_offset < object_size) {
2140 const char *name = object_addr + object_offset;
2152 // GuessIndirectSymbol returns the name of the indirect symbol for the
2153 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2154 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2155 // symbol name being referenced by the stub or pointer.
2156 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2157 struct DisassembleInfo *info) {
2158 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2159 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2160 for (const auto &Load : info->O->load_commands()) {
2161 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2162 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2163 for (unsigned J = 0; J < Seg.nsects; ++J) {
2164 MachO::section_64 Sec = info->O->getSection64(Load, J);
2165 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2166 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2167 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2168 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2169 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2170 section_type == MachO::S_SYMBOL_STUBS) &&
2171 ReferenceValue >= Sec.addr &&
2172 ReferenceValue < Sec.addr + Sec.size) {
2174 if (section_type == MachO::S_SYMBOL_STUBS)
2175 stride = Sec.reserved2;
2180 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2181 if (index < Dysymtab.nindirectsyms) {
2182 uint32_t indirect_symbol =
2183 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2184 if (indirect_symbol < Symtab.nsyms) {
2185 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2186 SymbolRef Symbol = *Sym;
2187 ErrorOr<StringRef> SymName = Symbol.getName();
2188 if (std::error_code EC = SymName.getError())
2189 report_fatal_error(EC.message());
2190 const char *name = SymName->data();
2196 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2197 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2198 for (unsigned J = 0; J < Seg.nsects; ++J) {
2199 MachO::section Sec = info->O->getSection(Load, J);
2200 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2201 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2202 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2203 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2204 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2205 section_type == MachO::S_SYMBOL_STUBS) &&
2206 ReferenceValue >= Sec.addr &&
2207 ReferenceValue < Sec.addr + Sec.size) {
2209 if (section_type == MachO::S_SYMBOL_STUBS)
2210 stride = Sec.reserved2;
2215 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2216 if (index < Dysymtab.nindirectsyms) {
2217 uint32_t indirect_symbol =
2218 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2219 if (indirect_symbol < Symtab.nsyms) {
2220 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2221 SymbolRef Symbol = *Sym;
2222 ErrorOr<StringRef> SymName = Symbol.getName();
2223 if (std::error_code EC = SymName.getError())
2224 report_fatal_error(EC.message());
2225 const char *name = SymName->data();
2236 // method_reference() is called passing it the ReferenceName that might be
2237 // a reference it to an Objective-C method call. If so then it allocates and
2238 // assembles a method call string with the values last seen and saved in
2239 // the DisassembleInfo's class_name and selector_name fields. This is saved
2240 // into the method field of the info and any previous string is free'ed.
2241 // Then the class_name field in the info is set to nullptr. The method call
2242 // string is set into ReferenceName and ReferenceType is set to
2243 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2244 // then both ReferenceType and ReferenceName are left unchanged.
2245 static void method_reference(struct DisassembleInfo *info,
2246 uint64_t *ReferenceType,
2247 const char **ReferenceName) {
2248 unsigned int Arch = info->O->getArch();
2249 if (*ReferenceName != nullptr) {
2250 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2251 if (info->selector_name != nullptr) {
2252 if (info->method != nullptr)
2254 if (info->class_name != nullptr) {
2255 info->method = (char *)malloc(5 + strlen(info->class_name) +
2256 strlen(info->selector_name));
2257 if (info->method != nullptr) {
2258 strcpy(info->method, "+[");
2259 strcat(info->method, info->class_name);
2260 strcat(info->method, " ");
2261 strcat(info->method, info->selector_name);
2262 strcat(info->method, "]");
2263 *ReferenceName = info->method;
2264 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2267 info->method = (char *)malloc(9 + strlen(info->selector_name));
2268 if (info->method != nullptr) {
2269 if (Arch == Triple::x86_64)
2270 strcpy(info->method, "-[%rdi ");
2271 else if (Arch == Triple::aarch64)
2272 strcpy(info->method, "-[x0 ");
2274 strcpy(info->method, "-[r? ");
2275 strcat(info->method, info->selector_name);
2276 strcat(info->method, "]");
2277 *ReferenceName = info->method;
2278 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2281 info->class_name = nullptr;
2283 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2284 if (info->selector_name != nullptr) {
2285 if (info->method != nullptr)
2287 info->method = (char *)malloc(17 + strlen(info->selector_name));
2288 if (info->method != nullptr) {
2289 if (Arch == Triple::x86_64)
2290 strcpy(info->method, "-[[%rdi super] ");
2291 else if (Arch == Triple::aarch64)
2292 strcpy(info->method, "-[[x0 super] ");
2294 strcpy(info->method, "-[[r? super] ");
2295 strcat(info->method, info->selector_name);
2296 strcat(info->method, "]");
2297 *ReferenceName = info->method;
2298 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2300 info->class_name = nullptr;
2306 // GuessPointerPointer() is passed the address of what might be a pointer to
2307 // a reference to an Objective-C class, selector, message ref or cfstring.
2308 // If so the value of the pointer is returned and one of the booleans are set
2309 // to true. If not zero is returned and all the booleans are set to false.
2310 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2311 struct DisassembleInfo *info,
2312 bool &classref, bool &selref, bool &msgref,
2318 for (const auto &Load : info->O->load_commands()) {
2319 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2320 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2321 for (unsigned J = 0; J < Seg.nsects; ++J) {
2322 MachO::section_64 Sec = info->O->getSection64(Load, J);
2323 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2324 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2325 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2326 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2327 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2328 ReferenceValue >= Sec.addr &&
2329 ReferenceValue < Sec.addr + Sec.size) {
2330 uint64_t sect_offset = ReferenceValue - Sec.addr;
2331 uint64_t object_offset = Sec.offset + sect_offset;
2332 StringRef MachOContents = info->O->getData();
2333 uint64_t object_size = MachOContents.size();
2334 const char *object_addr = (const char *)MachOContents.data();
2335 if (object_offset < object_size) {
2336 uint64_t pointer_value;
2337 memcpy(&pointer_value, object_addr + object_offset,
2339 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2340 sys::swapByteOrder(pointer_value);
2341 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2343 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2344 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2346 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2347 ReferenceValue + 8 < Sec.addr + Sec.size) {
2349 memcpy(&pointer_value, object_addr + object_offset + 8,
2351 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2352 sys::swapByteOrder(pointer_value);
2353 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2355 return pointer_value;
2362 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2367 // get_pointer_64 returns a pointer to the bytes in the object file at the
2368 // Address from a section in the Mach-O file. And indirectly returns the
2369 // offset into the section, number of bytes left in the section past the offset
2370 // and which section is was being referenced. If the Address is not in a
2371 // section nullptr is returned.
2372 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2373 uint32_t &left, SectionRef &S,
2374 DisassembleInfo *info,
2375 bool objc_only = false) {
2379 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2380 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2381 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2384 ((*(info->Sections))[SectIdx]).getName(SectName);
2385 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2386 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2387 if (SegName != "__OBJC" && SectName != "__cstring")
2390 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2391 S = (*(info->Sections))[SectIdx];
2392 offset = Address - SectAddress;
2393 left = SectSize - offset;
2394 StringRef SectContents;
2395 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2396 return SectContents.data() + offset;
2402 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2403 uint32_t &left, SectionRef &S,
2404 DisassembleInfo *info,
2405 bool objc_only = false) {
2406 return get_pointer_64(Address, offset, left, S, info, objc_only);
2409 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2410 // the symbol indirectly through n_value. Based on the relocation information
2411 // for the specified section offset in the specified section reference.
2412 // If no relocation information is found and a non-zero ReferenceValue for the
2413 // symbol is passed, look up that address in the info's AddrMap.
2414 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2415 DisassembleInfo *info, uint64_t &n_value,
2416 uint64_t ReferenceValue = UnknownAddress) {
2421 // See if there is an external relocation entry at the sect_offset.
2422 bool reloc_found = false;
2424 MachO::any_relocation_info RE;
2425 bool isExtern = false;
2427 for (const RelocationRef &Reloc : S.relocations()) {
2428 uint64_t RelocOffset = Reloc.getOffset();
2429 if (RelocOffset == sect_offset) {
2430 Rel = Reloc.getRawDataRefImpl();
2431 RE = info->O->getRelocation(Rel);
2432 if (info->O->isRelocationScattered(RE))
2434 isExtern = info->O->getPlainRelocationExternal(RE);
2436 symbol_iterator RelocSym = Reloc.getSymbol();
2443 // If there is an external relocation entry for a symbol in this section
2444 // at this section_offset then use that symbol's value for the n_value
2445 // and return its name.
2446 const char *SymbolName = nullptr;
2447 if (reloc_found && isExtern) {
2448 n_value = Symbol.getValue();
2449 if (n_value == UnknownAddress)
2451 ErrorOr<StringRef> NameOrError = Symbol.getName();
2452 if (std::error_code EC = NameOrError.getError())
2453 report_fatal_error(EC.message());
2454 StringRef Name = *NameOrError;
2455 if (!Name.empty()) {
2456 SymbolName = Name.data();
2461 // TODO: For fully linked images, look through the external relocation
2462 // entries off the dynamic symtab command. For these the r_offset is from the
2463 // start of the first writeable segment in the Mach-O file. So the offset
2464 // to this section from that segment is passed to this routine by the caller,
2465 // as the database_offset. Which is the difference of the section's starting
2466 // address and the first writable segment.
2468 // NOTE: need add passing the database_offset to this routine.
2470 // We did not find an external relocation entry so look up the ReferenceValue
2471 // as an address of a symbol and if found return that symbol's name.
2472 if (ReferenceValue != UnknownAddress)
2473 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2478 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2479 DisassembleInfo *info,
2480 uint32_t ReferenceValue) {
2482 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2485 // These are structs in the Objective-C meta data and read to produce the
2486 // comments for disassembly. While these are part of the ABI they are no
2487 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2489 // The cfstring object in a 64-bit Mach-O file.
2490 struct cfstring64_t {
2491 uint64_t isa; // class64_t * (64-bit pointer)
2492 uint64_t flags; // flag bits
2493 uint64_t characters; // char * (64-bit pointer)
2494 uint64_t length; // number of non-NULL characters in above
2497 // The class object in a 64-bit Mach-O file.
2499 uint64_t isa; // class64_t * (64-bit pointer)
2500 uint64_t superclass; // class64_t * (64-bit pointer)
2501 uint64_t cache; // Cache (64-bit pointer)
2502 uint64_t vtable; // IMP * (64-bit pointer)
2503 uint64_t data; // class_ro64_t * (64-bit pointer)
2507 uint32_t isa; /* class32_t * (32-bit pointer) */
2508 uint32_t superclass; /* class32_t * (32-bit pointer) */
2509 uint32_t cache; /* Cache (32-bit pointer) */
2510 uint32_t vtable; /* IMP * (32-bit pointer) */
2511 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2514 struct class_ro64_t {
2516 uint32_t instanceStart;
2517 uint32_t instanceSize;
2519 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2520 uint64_t name; // const char * (64-bit pointer)
2521 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2522 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2523 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2524 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2525 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2528 struct class_ro32_t {
2530 uint32_t instanceStart;
2531 uint32_t instanceSize;
2532 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2533 uint32_t name; /* const char * (32-bit pointer) */
2534 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2535 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2536 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2537 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2538 uint32_t baseProperties; /* const struct objc_property_list *
2542 /* Values for class_ro{64,32}_t->flags */
2543 #define RO_META (1 << 0)
2544 #define RO_ROOT (1 << 1)
2545 #define RO_HAS_CXX_STRUCTORS (1 << 2)
2547 struct method_list64_t {
2550 /* struct method64_t first; These structures follow inline */
2553 struct method_list32_t {
2556 /* struct method32_t first; These structures follow inline */
2560 uint64_t name; /* SEL (64-bit pointer) */
2561 uint64_t types; /* const char * (64-bit pointer) */
2562 uint64_t imp; /* IMP (64-bit pointer) */
2566 uint32_t name; /* SEL (32-bit pointer) */
2567 uint32_t types; /* const char * (32-bit pointer) */
2568 uint32_t imp; /* IMP (32-bit pointer) */
2571 struct protocol_list64_t {
2572 uint64_t count; /* uintptr_t (a 64-bit value) */
2573 /* struct protocol64_t * list[0]; These pointers follow inline */
2576 struct protocol_list32_t {
2577 uint32_t count; /* uintptr_t (a 32-bit value) */
2578 /* struct protocol32_t * list[0]; These pointers follow inline */
2581 struct protocol64_t {
2582 uint64_t isa; /* id * (64-bit pointer) */
2583 uint64_t name; /* const char * (64-bit pointer) */
2584 uint64_t protocols; /* struct protocol_list64_t *
2586 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2587 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2588 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2589 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2590 uint64_t instanceProperties; /* struct objc_property_list *
2594 struct protocol32_t {
2595 uint32_t isa; /* id * (32-bit pointer) */
2596 uint32_t name; /* const char * (32-bit pointer) */
2597 uint32_t protocols; /* struct protocol_list_t *
2599 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2600 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2601 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2602 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2603 uint32_t instanceProperties; /* struct objc_property_list *
2607 struct ivar_list64_t {
2610 /* struct ivar64_t first; These structures follow inline */
2613 struct ivar_list32_t {
2616 /* struct ivar32_t first; These structures follow inline */
2620 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2621 uint64_t name; /* const char * (64-bit pointer) */
2622 uint64_t type; /* const char * (64-bit pointer) */
2628 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2629 uint32_t name; /* const char * (32-bit pointer) */
2630 uint32_t type; /* const char * (32-bit pointer) */
2635 struct objc_property_list64 {
2638 /* struct objc_property64 first; These structures follow inline */
2641 struct objc_property_list32 {
2644 /* struct objc_property32 first; These structures follow inline */
2647 struct objc_property64 {
2648 uint64_t name; /* const char * (64-bit pointer) */
2649 uint64_t attributes; /* const char * (64-bit pointer) */
2652 struct objc_property32 {
2653 uint32_t name; /* const char * (32-bit pointer) */
2654 uint32_t attributes; /* const char * (32-bit pointer) */
2657 struct category64_t {
2658 uint64_t name; /* const char * (64-bit pointer) */
2659 uint64_t cls; /* struct class_t * (64-bit pointer) */
2660 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2661 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2662 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2663 uint64_t instanceProperties; /* struct objc_property_list *
2667 struct category32_t {
2668 uint32_t name; /* const char * (32-bit pointer) */
2669 uint32_t cls; /* struct class_t * (32-bit pointer) */
2670 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2671 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2672 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2673 uint32_t instanceProperties; /* struct objc_property_list *
2677 struct objc_image_info64 {
2681 struct objc_image_info32 {
2685 struct imageInfo_t {
2689 /* masks for objc_image_info.flags */
2690 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2691 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2693 struct message_ref64 {
2694 uint64_t imp; /* IMP (64-bit pointer) */
2695 uint64_t sel; /* SEL (64-bit pointer) */
2698 struct message_ref32 {
2699 uint32_t imp; /* IMP (32-bit pointer) */
2700 uint32_t sel; /* SEL (32-bit pointer) */
2703 // Objective-C 1 (32-bit only) meta data structs.
2705 struct objc_module_t {
2708 uint32_t name; /* char * (32-bit pointer) */
2709 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2712 struct objc_symtab_t {
2713 uint32_t sel_ref_cnt;
2714 uint32_t refs; /* SEL * (32-bit pointer) */
2715 uint16_t cls_def_cnt;
2716 uint16_t cat_def_cnt;
2717 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2720 struct objc_class_t {
2721 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2722 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2723 uint32_t name; /* const char * (32-bit pointer) */
2726 int32_t instance_size;
2727 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2728 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2729 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2730 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2733 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2734 // class is not a metaclass
2735 #define CLS_CLASS 0x1
2736 // class is a metaclass
2737 #define CLS_META 0x2
2739 struct objc_category_t {
2740 uint32_t category_name; /* char * (32-bit pointer) */
2741 uint32_t class_name; /* char * (32-bit pointer) */
2742 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2743 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2744 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2747 struct objc_ivar_t {
2748 uint32_t ivar_name; /* char * (32-bit pointer) */
2749 uint32_t ivar_type; /* char * (32-bit pointer) */
2750 int32_t ivar_offset;
2753 struct objc_ivar_list_t {
2755 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2758 struct objc_method_list_t {
2759 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2760 int32_t method_count;
2761 // struct objc_method_t method_list[1]; /* variable length structure */
2764 struct objc_method_t {
2765 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2766 uint32_t method_types; /* char * (32-bit pointer) */
2767 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2771 struct objc_protocol_list_t {
2772 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2774 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2775 // (32-bit pointer) */
2778 struct objc_protocol_t {
2779 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2780 uint32_t protocol_name; /* char * (32-bit pointer) */
2781 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2782 uint32_t instance_methods; /* struct objc_method_description_list *
2784 uint32_t class_methods; /* struct objc_method_description_list *
2788 struct objc_method_description_list_t {
2790 // struct objc_method_description_t list[1];
2793 struct objc_method_description_t {
2794 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2795 uint32_t types; /* char * (32-bit pointer) */
2798 inline void swapStruct(struct cfstring64_t &cfs) {
2799 sys::swapByteOrder(cfs.isa);
2800 sys::swapByteOrder(cfs.flags);
2801 sys::swapByteOrder(cfs.characters);
2802 sys::swapByteOrder(cfs.length);
2805 inline void swapStruct(struct class64_t &c) {
2806 sys::swapByteOrder(c.isa);
2807 sys::swapByteOrder(c.superclass);
2808 sys::swapByteOrder(c.cache);
2809 sys::swapByteOrder(c.vtable);
2810 sys::swapByteOrder(c.data);
2813 inline void swapStruct(struct class32_t &c) {
2814 sys::swapByteOrder(c.isa);
2815 sys::swapByteOrder(c.superclass);
2816 sys::swapByteOrder(c.cache);
2817 sys::swapByteOrder(c.vtable);
2818 sys::swapByteOrder(c.data);
2821 inline void swapStruct(struct class_ro64_t &cro) {
2822 sys::swapByteOrder(cro.flags);
2823 sys::swapByteOrder(cro.instanceStart);
2824 sys::swapByteOrder(cro.instanceSize);
2825 sys::swapByteOrder(cro.reserved);
2826 sys::swapByteOrder(cro.ivarLayout);
2827 sys::swapByteOrder(cro.name);
2828 sys::swapByteOrder(cro.baseMethods);
2829 sys::swapByteOrder(cro.baseProtocols);
2830 sys::swapByteOrder(cro.ivars);
2831 sys::swapByteOrder(cro.weakIvarLayout);
2832 sys::swapByteOrder(cro.baseProperties);
2835 inline void swapStruct(struct class_ro32_t &cro) {
2836 sys::swapByteOrder(cro.flags);
2837 sys::swapByteOrder(cro.instanceStart);
2838 sys::swapByteOrder(cro.instanceSize);
2839 sys::swapByteOrder(cro.ivarLayout);
2840 sys::swapByteOrder(cro.name);
2841 sys::swapByteOrder(cro.baseMethods);
2842 sys::swapByteOrder(cro.baseProtocols);
2843 sys::swapByteOrder(cro.ivars);
2844 sys::swapByteOrder(cro.weakIvarLayout);
2845 sys::swapByteOrder(cro.baseProperties);
2848 inline void swapStruct(struct method_list64_t &ml) {
2849 sys::swapByteOrder(ml.entsize);
2850 sys::swapByteOrder(ml.count);
2853 inline void swapStruct(struct method_list32_t &ml) {
2854 sys::swapByteOrder(ml.entsize);
2855 sys::swapByteOrder(ml.count);
2858 inline void swapStruct(struct method64_t &m) {
2859 sys::swapByteOrder(m.name);
2860 sys::swapByteOrder(m.types);
2861 sys::swapByteOrder(m.imp);
2864 inline void swapStruct(struct method32_t &m) {
2865 sys::swapByteOrder(m.name);
2866 sys::swapByteOrder(m.types);
2867 sys::swapByteOrder(m.imp);
2870 inline void swapStruct(struct protocol_list64_t &pl) {
2871 sys::swapByteOrder(pl.count);
2874 inline void swapStruct(struct protocol_list32_t &pl) {
2875 sys::swapByteOrder(pl.count);
2878 inline void swapStruct(struct protocol64_t &p) {
2879 sys::swapByteOrder(p.isa);
2880 sys::swapByteOrder(p.name);
2881 sys::swapByteOrder(p.protocols);
2882 sys::swapByteOrder(p.instanceMethods);
2883 sys::swapByteOrder(p.classMethods);
2884 sys::swapByteOrder(p.optionalInstanceMethods);
2885 sys::swapByteOrder(p.optionalClassMethods);
2886 sys::swapByteOrder(p.instanceProperties);
2889 inline void swapStruct(struct protocol32_t &p) {
2890 sys::swapByteOrder(p.isa);
2891 sys::swapByteOrder(p.name);
2892 sys::swapByteOrder(p.protocols);
2893 sys::swapByteOrder(p.instanceMethods);
2894 sys::swapByteOrder(p.classMethods);
2895 sys::swapByteOrder(p.optionalInstanceMethods);
2896 sys::swapByteOrder(p.optionalClassMethods);
2897 sys::swapByteOrder(p.instanceProperties);
2900 inline void swapStruct(struct ivar_list64_t &il) {
2901 sys::swapByteOrder(il.entsize);
2902 sys::swapByteOrder(il.count);
2905 inline void swapStruct(struct ivar_list32_t &il) {
2906 sys::swapByteOrder(il.entsize);
2907 sys::swapByteOrder(il.count);
2910 inline void swapStruct(struct ivar64_t &i) {
2911 sys::swapByteOrder(i.offset);
2912 sys::swapByteOrder(i.name);
2913 sys::swapByteOrder(i.type);
2914 sys::swapByteOrder(i.alignment);
2915 sys::swapByteOrder(i.size);
2918 inline void swapStruct(struct ivar32_t &i) {
2919 sys::swapByteOrder(i.offset);
2920 sys::swapByteOrder(i.name);
2921 sys::swapByteOrder(i.type);
2922 sys::swapByteOrder(i.alignment);
2923 sys::swapByteOrder(i.size);
2926 inline void swapStruct(struct objc_property_list64 &pl) {
2927 sys::swapByteOrder(pl.entsize);
2928 sys::swapByteOrder(pl.count);
2931 inline void swapStruct(struct objc_property_list32 &pl) {
2932 sys::swapByteOrder(pl.entsize);
2933 sys::swapByteOrder(pl.count);
2936 inline void swapStruct(struct objc_property64 &op) {
2937 sys::swapByteOrder(op.name);
2938 sys::swapByteOrder(op.attributes);
2941 inline void swapStruct(struct objc_property32 &op) {
2942 sys::swapByteOrder(op.name);
2943 sys::swapByteOrder(op.attributes);
2946 inline void swapStruct(struct category64_t &c) {
2947 sys::swapByteOrder(c.name);
2948 sys::swapByteOrder(c.cls);
2949 sys::swapByteOrder(c.instanceMethods);
2950 sys::swapByteOrder(c.classMethods);
2951 sys::swapByteOrder(c.protocols);
2952 sys::swapByteOrder(c.instanceProperties);
2955 inline void swapStruct(struct category32_t &c) {
2956 sys::swapByteOrder(c.name);
2957 sys::swapByteOrder(c.cls);
2958 sys::swapByteOrder(c.instanceMethods);
2959 sys::swapByteOrder(c.classMethods);
2960 sys::swapByteOrder(c.protocols);
2961 sys::swapByteOrder(c.instanceProperties);
2964 inline void swapStruct(struct objc_image_info64 &o) {
2965 sys::swapByteOrder(o.version);
2966 sys::swapByteOrder(o.flags);
2969 inline void swapStruct(struct objc_image_info32 &o) {
2970 sys::swapByteOrder(o.version);
2971 sys::swapByteOrder(o.flags);
2974 inline void swapStruct(struct imageInfo_t &o) {
2975 sys::swapByteOrder(o.version);
2976 sys::swapByteOrder(o.flags);
2979 inline void swapStruct(struct message_ref64 &mr) {
2980 sys::swapByteOrder(mr.imp);
2981 sys::swapByteOrder(mr.sel);
2984 inline void swapStruct(struct message_ref32 &mr) {
2985 sys::swapByteOrder(mr.imp);
2986 sys::swapByteOrder(mr.sel);
2989 inline void swapStruct(struct objc_module_t &module) {
2990 sys::swapByteOrder(module.version);
2991 sys::swapByteOrder(module.size);
2992 sys::swapByteOrder(module.name);
2993 sys::swapByteOrder(module.symtab);
2996 inline void swapStruct(struct objc_symtab_t &symtab) {
2997 sys::swapByteOrder(symtab.sel_ref_cnt);
2998 sys::swapByteOrder(symtab.refs);
2999 sys::swapByteOrder(symtab.cls_def_cnt);
3000 sys::swapByteOrder(symtab.cat_def_cnt);
3003 inline void swapStruct(struct objc_class_t &objc_class) {
3004 sys::swapByteOrder(objc_class.isa);
3005 sys::swapByteOrder(objc_class.super_class);
3006 sys::swapByteOrder(objc_class.name);
3007 sys::swapByteOrder(objc_class.version);
3008 sys::swapByteOrder(objc_class.info);
3009 sys::swapByteOrder(objc_class.instance_size);
3010 sys::swapByteOrder(objc_class.ivars);
3011 sys::swapByteOrder(objc_class.methodLists);
3012 sys::swapByteOrder(objc_class.cache);
3013 sys::swapByteOrder(objc_class.protocols);
3016 inline void swapStruct(struct objc_category_t &objc_category) {
3017 sys::swapByteOrder(objc_category.category_name);
3018 sys::swapByteOrder(objc_category.class_name);
3019 sys::swapByteOrder(objc_category.instance_methods);
3020 sys::swapByteOrder(objc_category.class_methods);
3021 sys::swapByteOrder(objc_category.protocols);
3024 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3025 sys::swapByteOrder(objc_ivar_list.ivar_count);
3028 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3029 sys::swapByteOrder(objc_ivar.ivar_name);
3030 sys::swapByteOrder(objc_ivar.ivar_type);
3031 sys::swapByteOrder(objc_ivar.ivar_offset);
3034 inline void swapStruct(struct objc_method_list_t &method_list) {
3035 sys::swapByteOrder(method_list.obsolete);
3036 sys::swapByteOrder(method_list.method_count);
3039 inline void swapStruct(struct objc_method_t &method) {
3040 sys::swapByteOrder(method.method_name);
3041 sys::swapByteOrder(method.method_types);
3042 sys::swapByteOrder(method.method_imp);
3045 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3046 sys::swapByteOrder(protocol_list.next);
3047 sys::swapByteOrder(protocol_list.count);
3050 inline void swapStruct(struct objc_protocol_t &protocol) {
3051 sys::swapByteOrder(protocol.isa);
3052 sys::swapByteOrder(protocol.protocol_name);
3053 sys::swapByteOrder(protocol.protocol_list);
3054 sys::swapByteOrder(protocol.instance_methods);
3055 sys::swapByteOrder(protocol.class_methods);
3058 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3059 sys::swapByteOrder(mdl.count);
3062 inline void swapStruct(struct objc_method_description_t &md) {
3063 sys::swapByteOrder(md.name);
3064 sys::swapByteOrder(md.types);
3067 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3068 struct DisassembleInfo *info);
3070 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3071 // to an Objective-C class and returns the class name. It is also passed the
3072 // address of the pointer, so when the pointer is zero as it can be in an .o
3073 // file, that is used to look for an external relocation entry with a symbol
3075 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3076 uint64_t ReferenceValue,
3077 struct DisassembleInfo *info) {
3079 uint32_t offset, left;
3082 // The pointer_value can be 0 in an object file and have a relocation
3083 // entry for the class symbol at the ReferenceValue (the address of the
3085 if (pointer_value == 0) {
3086 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3087 if (r == nullptr || left < sizeof(uint64_t))
3090 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3091 if (symbol_name == nullptr)
3093 const char *class_name = strrchr(symbol_name, '$');
3094 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3095 return class_name + 2;
3100 // The case were the pointer_value is non-zero and points to a class defined
3101 // in this Mach-O file.
3102 r = get_pointer_64(pointer_value, offset, left, S, info);
3103 if (r == nullptr || left < sizeof(struct class64_t))
3106 memcpy(&c, r, sizeof(struct class64_t));
3107 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3111 r = get_pointer_64(c.data, offset, left, S, info);
3112 if (r == nullptr || left < sizeof(struct class_ro64_t))
3114 struct class_ro64_t cro;
3115 memcpy(&cro, r, sizeof(struct class_ro64_t));
3116 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3120 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3124 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3125 // pointer to a cfstring and returns its name or nullptr.
3126 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3127 struct DisassembleInfo *info) {
3128 const char *r, *name;
3129 uint32_t offset, left;
3131 struct cfstring64_t cfs;
3132 uint64_t cfs_characters;
3134 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3135 if (r == nullptr || left < sizeof(struct cfstring64_t))
3137 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3138 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3140 if (cfs.characters == 0) {
3142 const char *symbol_name = get_symbol_64(
3143 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3144 if (symbol_name == nullptr)
3146 cfs_characters = n_value;
3148 cfs_characters = cfs.characters;
3149 name = get_pointer_64(cfs_characters, offset, left, S, info);
3154 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
3155 // of a pointer to an Objective-C selector reference when the pointer value is
3156 // zero as in a .o file and is likely to have a external relocation entry with
3157 // who's symbol's n_value is the real pointer to the selector name. If that is
3158 // the case the real pointer to the selector name is returned else 0 is
3160 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3161 struct DisassembleInfo *info) {
3162 uint32_t offset, left;
3165 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3166 if (r == nullptr || left < sizeof(uint64_t))
3169 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3170 if (symbol_name == nullptr)
3175 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3176 const char *sectname) {
3177 for (const SectionRef &Section : O->sections()) {
3179 Section.getName(SectName);
3180 DataRefImpl Ref = Section.getRawDataRefImpl();
3181 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3182 if (SegName == segname && SectName == sectname)
3185 return SectionRef();
3189 walk_pointer_list_64(const char *listname, const SectionRef S,
3190 MachOObjectFile *O, struct DisassembleInfo *info,
3191 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3192 if (S == SectionRef())
3196 S.getName(SectName);
3197 DataRefImpl Ref = S.getRawDataRefImpl();
3198 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3199 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3202 S.getContents(BytesStr);
3203 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3205 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3206 uint32_t left = S.getSize() - i;
3207 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3209 memcpy(&p, Contents + i, size);
3210 if (i + sizeof(uint64_t) > S.getSize())
3211 outs() << listname << " list pointer extends past end of (" << SegName
3212 << "," << SectName << ") section\n";
3213 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3215 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3216 sys::swapByteOrder(p);
3218 uint64_t n_value = 0;
3219 const char *name = get_symbol_64(i, S, info, n_value, p);
3220 if (name == nullptr)
3221 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3224 outs() << format("0x%" PRIx64, n_value);
3226 outs() << " + " << format("0x%" PRIx64, p);
3228 outs() << format("0x%" PRIx64, p);
3229 if (name != nullptr)
3230 outs() << " " << name;
3240 walk_pointer_list_32(const char *listname, const SectionRef S,
3241 MachOObjectFile *O, struct DisassembleInfo *info,
3242 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3243 if (S == SectionRef())
3247 S.getName(SectName);
3248 DataRefImpl Ref = S.getRawDataRefImpl();
3249 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3250 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3253 S.getContents(BytesStr);
3254 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3256 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3257 uint32_t left = S.getSize() - i;
3258 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3260 memcpy(&p, Contents + i, size);
3261 if (i + sizeof(uint32_t) > S.getSize())
3262 outs() << listname << " list pointer extends past end of (" << SegName
3263 << "," << SectName << ") section\n";
3264 uint32_t Address = S.getAddress() + i;
3265 outs() << format("%08" PRIx32, Address) << " ";
3267 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3268 sys::swapByteOrder(p);
3269 outs() << format("0x%" PRIx32, p);
3271 const char *name = get_symbol_32(i, S, info, p);
3272 if (name != nullptr)
3273 outs() << " " << name;
3281 static void print_layout_map(const char *layout_map, uint32_t left) {
3282 outs() << " layout map: ";
3284 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3287 } while (*layout_map != '\0' && left != 0);
3291 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3292 uint32_t offset, left;
3294 const char *layout_map;
3298 layout_map = get_pointer_64(p, offset, left, S, info);
3299 print_layout_map(layout_map, left);
3302 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3303 uint32_t offset, left;
3305 const char *layout_map;
3309 layout_map = get_pointer_32(p, offset, left, S, info);
3310 print_layout_map(layout_map, left);
3313 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3314 const char *indent) {
3315 struct method_list64_t ml;
3316 struct method64_t m;
3318 uint32_t offset, xoffset, left, i;
3320 const char *name, *sym_name;
3323 r = get_pointer_64(p, offset, left, S, info);
3326 memset(&ml, '\0', sizeof(struct method_list64_t));
3327 if (left < sizeof(struct method_list64_t)) {
3328 memcpy(&ml, r, left);
3329 outs() << " (method_list_t entends past the end of the section)\n";
3331 memcpy(&ml, r, sizeof(struct method_list64_t));
3332 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3334 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3335 outs() << indent << "\t\t count " << ml.count << "\n";
3337 p += sizeof(struct method_list64_t);
3338 offset += sizeof(struct method_list64_t);
3339 for (i = 0; i < ml.count; i++) {
3340 r = get_pointer_64(p, offset, left, S, info);
3343 memset(&m, '\0', sizeof(struct method64_t));
3344 if (left < sizeof(struct method64_t)) {
3345 memcpy(&ml, r, left);
3346 outs() << indent << " (method_t entends past the end of the section)\n";
3348 memcpy(&m, r, sizeof(struct method64_t));
3349 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3352 outs() << indent << "\t\t name ";
3353 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3354 info, n_value, m.name);
3356 if (info->verbose && sym_name != nullptr)
3359 outs() << format("0x%" PRIx64, n_value);
3361 outs() << " + " << format("0x%" PRIx64, m.name);
3363 outs() << format("0x%" PRIx64, m.name);
3364 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3365 if (name != nullptr)
3366 outs() << format(" %.*s", left, name);
3369 outs() << indent << "\t\t types ";
3370 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3371 info, n_value, m.types);
3373 if (info->verbose && sym_name != nullptr)
3376 outs() << format("0x%" PRIx64, n_value);
3378 outs() << " + " << format("0x%" PRIx64, m.types);
3380 outs() << format("0x%" PRIx64, m.types);
3381 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3382 if (name != nullptr)
3383 outs() << format(" %.*s", left, name);
3386 outs() << indent << "\t\t imp ";
3387 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3389 if (info->verbose && name == nullptr) {
3391 outs() << format("0x%" PRIx64, n_value) << " ";
3393 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3395 outs() << format("0x%" PRIx64, m.imp) << " ";
3397 if (name != nullptr)
3401 p += sizeof(struct method64_t);
3402 offset += sizeof(struct method64_t);
3406 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3407 const char *indent) {
3408 struct method_list32_t ml;
3409 struct method32_t m;
3410 const char *r, *name;
3411 uint32_t offset, xoffset, left, i;
3414 r = get_pointer_32(p, offset, left, S, info);
3417 memset(&ml, '\0', sizeof(struct method_list32_t));
3418 if (left < sizeof(struct method_list32_t)) {
3419 memcpy(&ml, r, left);
3420 outs() << " (method_list_t entends past the end of the section)\n";
3422 memcpy(&ml, r, sizeof(struct method_list32_t));
3423 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3425 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3426 outs() << indent << "\t\t count " << ml.count << "\n";
3428 p += sizeof(struct method_list32_t);
3429 offset += sizeof(struct method_list32_t);
3430 for (i = 0; i < ml.count; i++) {
3431 r = get_pointer_32(p, offset, left, S, info);
3434 memset(&m, '\0', sizeof(struct method32_t));
3435 if (left < sizeof(struct method32_t)) {
3436 memcpy(&ml, r, left);
3437 outs() << indent << " (method_t entends past the end of the section)\n";
3439 memcpy(&m, r, sizeof(struct method32_t));
3440 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3443 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3444 name = get_pointer_32(m.name, xoffset, left, xS, info);
3445 if (name != nullptr)
3446 outs() << format(" %.*s", left, name);
3449 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3450 name = get_pointer_32(m.types, xoffset, left, xS, info);
3451 if (name != nullptr)
3452 outs() << format(" %.*s", left, name);
3455 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3456 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3458 if (name != nullptr)
3459 outs() << " " << name;
3462 p += sizeof(struct method32_t);
3463 offset += sizeof(struct method32_t);
3467 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3468 uint32_t offset, left, xleft;
3470 struct objc_method_list_t method_list;
3471 struct objc_method_t method;
3472 const char *r, *methods, *name, *SymbolName;
3475 r = get_pointer_32(p, offset, left, S, info, true);
3480 if (left > sizeof(struct objc_method_list_t)) {
3481 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3483 outs() << "\t\t objc_method_list extends past end of the section\n";
3484 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3485 memcpy(&method_list, r, left);
3487 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3488 swapStruct(method_list);
3490 outs() << "\t\t obsolete "
3491 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3492 outs() << "\t\t method_count " << method_list.method_count << "\n";
3494 methods = r + sizeof(struct objc_method_list_t);
3495 for (i = 0; i < method_list.method_count; i++) {
3496 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3497 outs() << "\t\t remaining method's extend past the of the section\n";
3500 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3501 sizeof(struct objc_method_t));
3502 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3505 outs() << "\t\t method_name "
3506 << format("0x%08" PRIx32, method.method_name);
3507 if (info->verbose) {
3508 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3509 if (name != nullptr)
3510 outs() << format(" %.*s", xleft, name);
3512 outs() << " (not in an __OBJC section)";
3516 outs() << "\t\t method_types "
3517 << format("0x%08" PRIx32, method.method_types);
3518 if (info->verbose) {
3519 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3520 if (name != nullptr)
3521 outs() << format(" %.*s", xleft, name);
3523 outs() << " (not in an __OBJC section)";
3527 outs() << "\t\t method_imp "
3528 << format("0x%08" PRIx32, method.method_imp) << " ";
3529 if (info->verbose) {
3530 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3531 if (SymbolName != nullptr)
3532 outs() << SymbolName;
3539 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3540 struct protocol_list64_t pl;
3541 uint64_t q, n_value;
3542 struct protocol64_t pc;
3544 uint32_t offset, xoffset, left, i;
3546 const char *name, *sym_name;
3548 r = get_pointer_64(p, offset, left, S, info);
3551 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3552 if (left < sizeof(struct protocol_list64_t)) {
3553 memcpy(&pl, r, left);
3554 outs() << " (protocol_list_t entends past the end of the section)\n";
3556 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3557 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3559 outs() << " count " << pl.count << "\n";
3561 p += sizeof(struct protocol_list64_t);
3562 offset += sizeof(struct protocol_list64_t);
3563 for (i = 0; i < pl.count; i++) {
3564 r = get_pointer_64(p, offset, left, S, info);
3568 if (left < sizeof(uint64_t)) {
3569 memcpy(&q, r, left);
3570 outs() << " (protocol_t * entends past the end of the section)\n";
3572 memcpy(&q, r, sizeof(uint64_t));
3573 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3574 sys::swapByteOrder(q);
3576 outs() << "\t\t list[" << i << "] ";
3577 sym_name = get_symbol_64(offset, S, info, n_value, q);
3579 if (info->verbose && sym_name != nullptr)
3582 outs() << format("0x%" PRIx64, n_value);
3584 outs() << " + " << format("0x%" PRIx64, q);
3586 outs() << format("0x%" PRIx64, q);
3587 outs() << " (struct protocol_t *)\n";
3589 r = get_pointer_64(q + n_value, offset, left, S, info);
3592 memset(&pc, '\0', sizeof(struct protocol64_t));
3593 if (left < sizeof(struct protocol64_t)) {
3594 memcpy(&pc, r, left);
3595 outs() << " (protocol_t entends past the end of the section)\n";
3597 memcpy(&pc, r, sizeof(struct protocol64_t));
3598 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3601 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3603 outs() << "\t\t\t name ";
3604 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3605 info, n_value, pc.name);
3607 if (info->verbose && sym_name != nullptr)
3610 outs() << format("0x%" PRIx64, n_value);
3612 outs() << " + " << format("0x%" PRIx64, pc.name);
3614 outs() << format("0x%" PRIx64, pc.name);
3615 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3616 if (name != nullptr)
3617 outs() << format(" %.*s", left, name);
3620 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3622 outs() << "\t\t instanceMethods ";
3624 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3625 S, info, n_value, pc.instanceMethods);
3627 if (info->verbose && sym_name != nullptr)
3630 outs() << format("0x%" PRIx64, n_value);
3631 if (pc.instanceMethods != 0)
3632 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3634 outs() << format("0x%" PRIx64, pc.instanceMethods);
3635 outs() << " (struct method_list_t *)\n";
3636 if (pc.instanceMethods + n_value != 0)
3637 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3639 outs() << "\t\t classMethods ";
3641 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3642 info, n_value, pc.classMethods);
3644 if (info->verbose && sym_name != nullptr)
3647 outs() << format("0x%" PRIx64, n_value);
3648 if (pc.classMethods != 0)
3649 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3651 outs() << format("0x%" PRIx64, pc.classMethods);
3652 outs() << " (struct method_list_t *)\n";
3653 if (pc.classMethods + n_value != 0)
3654 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3656 outs() << "\t optionalInstanceMethods "
3657 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3658 outs() << "\t optionalClassMethods "
3659 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3660 outs() << "\t instanceProperties "
3661 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3663 p += sizeof(uint64_t);
3664 offset += sizeof(uint64_t);
3668 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3669 struct protocol_list32_t pl;
3671 struct protocol32_t pc;
3673 uint32_t offset, xoffset, left, i;
3677 r = get_pointer_32(p, offset, left, S, info);
3680 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3681 if (left < sizeof(struct protocol_list32_t)) {
3682 memcpy(&pl, r, left);
3683 outs() << " (protocol_list_t entends past the end of the section)\n";
3685 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3686 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3688 outs() << " count " << pl.count << "\n";
3690 p += sizeof(struct protocol_list32_t);
3691 offset += sizeof(struct protocol_list32_t);
3692 for (i = 0; i < pl.count; i++) {
3693 r = get_pointer_32(p, offset, left, S, info);
3697 if (left < sizeof(uint32_t)) {
3698 memcpy(&q, r, left);
3699 outs() << " (protocol_t * entends past the end of the section)\n";
3701 memcpy(&q, r, sizeof(uint32_t));
3702 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3703 sys::swapByteOrder(q);
3704 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3705 << " (struct protocol_t *)\n";
3706 r = get_pointer_32(q, offset, left, S, info);
3709 memset(&pc, '\0', sizeof(struct protocol32_t));
3710 if (left < sizeof(struct protocol32_t)) {
3711 memcpy(&pc, r, left);
3712 outs() << " (protocol_t entends past the end of the section)\n";
3714 memcpy(&pc, r, sizeof(struct protocol32_t));
3715 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3717 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3718 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3719 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3720 if (name != nullptr)
3721 outs() << format(" %.*s", left, name);
3723 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3724 outs() << "\t\t instanceMethods "
3725 << format("0x%" PRIx32, pc.instanceMethods)
3726 << " (struct method_list_t *)\n";
3727 if (pc.instanceMethods != 0)
3728 print_method_list32_t(pc.instanceMethods, info, "\t");
3729 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3730 << " (struct method_list_t *)\n";
3731 if (pc.classMethods != 0)
3732 print_method_list32_t(pc.classMethods, info, "\t");
3733 outs() << "\t optionalInstanceMethods "
3734 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3735 outs() << "\t optionalClassMethods "
3736 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3737 outs() << "\t instanceProperties "
3738 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3739 p += sizeof(uint32_t);
3740 offset += sizeof(uint32_t);
3744 static void print_indent(uint32_t indent) {
3745 for (uint32_t i = 0; i < indent;) {
3746 if (indent - i >= 8) {
3750 for (uint32_t j = i; j < indent; j++)
3757 static bool print_method_description_list(uint32_t p, uint32_t indent,
3758 struct DisassembleInfo *info) {
3759 uint32_t offset, left, xleft;
3761 struct objc_method_description_list_t mdl;
3762 struct objc_method_description_t md;
3763 const char *r, *list, *name;
3766 r = get_pointer_32(p, offset, left, S, info, true);
3771 if (left > sizeof(struct objc_method_description_list_t)) {
3772 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3774 print_indent(indent);
3775 outs() << " objc_method_description_list extends past end of the section\n";
3776 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3777 memcpy(&mdl, r, left);
3779 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3782 print_indent(indent);
3783 outs() << " count " << mdl.count << "\n";
3785 list = r + sizeof(struct objc_method_description_list_t);
3786 for (i = 0; i < mdl.count; i++) {
3787 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3788 print_indent(indent);
3789 outs() << " remaining list entries extend past the of the section\n";
3792 print_indent(indent);
3793 outs() << " list[" << i << "]\n";
3794 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3795 sizeof(struct objc_method_description_t));
3796 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3799 print_indent(indent);
3800 outs() << " name " << format("0x%08" PRIx32, md.name);
3801 if (info->verbose) {
3802 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3803 if (name != nullptr)
3804 outs() << format(" %.*s", xleft, name);
3806 outs() << " (not in an __OBJC section)";
3810 print_indent(indent);
3811 outs() << " types " << format("0x%08" PRIx32, md.types);
3812 if (info->verbose) {
3813 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3814 if (name != nullptr)
3815 outs() << format(" %.*s", xleft, name);
3817 outs() << " (not in an __OBJC section)";
3824 static bool print_protocol_list(uint32_t p, uint32_t indent,
3825 struct DisassembleInfo *info);
3827 static bool print_protocol(uint32_t p, uint32_t indent,
3828 struct DisassembleInfo *info) {
3829 uint32_t offset, left;
3831 struct objc_protocol_t protocol;
3832 const char *r, *name;
3834 r = get_pointer_32(p, offset, left, S, info, true);
3839 if (left >= sizeof(struct objc_protocol_t)) {
3840 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3842 print_indent(indent);
3843 outs() << " Protocol extends past end of the section\n";
3844 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3845 memcpy(&protocol, r, left);
3847 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3848 swapStruct(protocol);
3850 print_indent(indent);
3851 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3854 print_indent(indent);
3855 outs() << " protocol_name "
3856 << format("0x%08" PRIx32, protocol.protocol_name);
3857 if (info->verbose) {
3858 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3859 if (name != nullptr)
3860 outs() << format(" %.*s", left, name);
3862 outs() << " (not in an __OBJC section)";
3866 print_indent(indent);
3867 outs() << " protocol_list "
3868 << format("0x%08" PRIx32, protocol.protocol_list);
3869 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3870 outs() << " (not in an __OBJC section)\n";
3872 print_indent(indent);
3873 outs() << " instance_methods "
3874 << format("0x%08" PRIx32, protocol.instance_methods);
3875 if (print_method_description_list(protocol.instance_methods, indent, info))
3876 outs() << " (not in an __OBJC section)\n";
3878 print_indent(indent);
3879 outs() << " class_methods "
3880 << format("0x%08" PRIx32, protocol.class_methods);
3881 if (print_method_description_list(protocol.class_methods, indent, info))
3882 outs() << " (not in an __OBJC section)\n";
3887 static bool print_protocol_list(uint32_t p, uint32_t indent,
3888 struct DisassembleInfo *info) {
3889 uint32_t offset, left, l;
3891 struct objc_protocol_list_t protocol_list;
3892 const char *r, *list;
3895 r = get_pointer_32(p, offset, left, S, info, true);
3900 if (left > sizeof(struct objc_protocol_list_t)) {
3901 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3903 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3904 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3905 memcpy(&protocol_list, r, left);
3907 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3908 swapStruct(protocol_list);
3910 print_indent(indent);
3911 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3913 print_indent(indent);
3914 outs() << " count " << protocol_list.count << "\n";
3916 list = r + sizeof(struct objc_protocol_list_t);
3917 for (i = 0; i < protocol_list.count; i++) {
3918 if ((i + 1) * sizeof(uint32_t) > left) {
3919 outs() << "\t\t remaining list entries extend past the of the section\n";
3922 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3923 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3924 sys::swapByteOrder(l);
3926 print_indent(indent);
3927 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3928 if (print_protocol(l, indent, info))
3929 outs() << "(not in an __OBJC section)\n";
3934 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3935 struct ivar_list64_t il;
3938 uint32_t offset, xoffset, left, j;
3940 const char *name, *sym_name, *ivar_offset_p;
3941 uint64_t ivar_offset, n_value;
3943 r = get_pointer_64(p, offset, left, S, info);
3946 memset(&il, '\0', sizeof(struct ivar_list64_t));
3947 if (left < sizeof(struct ivar_list64_t)) {
3948 memcpy(&il, r, left);
3949 outs() << " (ivar_list_t entends past the end of the section)\n";
3951 memcpy(&il, r, sizeof(struct ivar_list64_t));
3952 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3954 outs() << " entsize " << il.entsize << "\n";
3955 outs() << " count " << il.count << "\n";
3957 p += sizeof(struct ivar_list64_t);
3958 offset += sizeof(struct ivar_list64_t);
3959 for (j = 0; j < il.count; j++) {
3960 r = get_pointer_64(p, offset, left, S, info);
3963 memset(&i, '\0', sizeof(struct ivar64_t));
3964 if (left < sizeof(struct ivar64_t)) {
3965 memcpy(&i, r, left);
3966 outs() << " (ivar_t entends past the end of the section)\n";
3968 memcpy(&i, r, sizeof(struct ivar64_t));
3969 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3972 outs() << "\t\t\t offset ";
3973 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3974 info, n_value, i.offset);
3976 if (info->verbose && sym_name != nullptr)
3979 outs() << format("0x%" PRIx64, n_value);
3981 outs() << " + " << format("0x%" PRIx64, i.offset);
3983 outs() << format("0x%" PRIx64, i.offset);
3984 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3985 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3986 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3987 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3988 sys::swapByteOrder(ivar_offset);
3989 outs() << " " << ivar_offset << "\n";
3993 outs() << "\t\t\t name ";
3994 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
3997 if (info->verbose && sym_name != nullptr)
4000 outs() << format("0x%" PRIx64, n_value);
4002 outs() << " + " << format("0x%" PRIx64, i.name);
4004 outs() << format("0x%" PRIx64, i.name);
4005 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4006 if (name != nullptr)
4007 outs() << format(" %.*s", left, name);
4010 outs() << "\t\t\t type ";
4011 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4013 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4015 if (info->verbose && sym_name != nullptr)
4018 outs() << format("0x%" PRIx64, n_value);
4020 outs() << " + " << format("0x%" PRIx64, i.type);
4022 outs() << format("0x%" PRIx64, i.type);
4023 if (name != nullptr)
4024 outs() << format(" %.*s", left, name);
4027 outs() << "\t\t\talignment " << i.alignment << "\n";
4028 outs() << "\t\t\t size " << i.size << "\n";
4030 p += sizeof(struct ivar64_t);
4031 offset += sizeof(struct ivar64_t);
4035 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4036 struct ivar_list32_t il;
4039 uint32_t offset, xoffset, left, j;
4041 const char *name, *ivar_offset_p;
4042 uint32_t ivar_offset;
4044 r = get_pointer_32(p, offset, left, S, info);
4047 memset(&il, '\0', sizeof(struct ivar_list32_t));
4048 if (left < sizeof(struct ivar_list32_t)) {
4049 memcpy(&il, r, left);
4050 outs() << " (ivar_list_t entends past the end of the section)\n";
4052 memcpy(&il, r, sizeof(struct ivar_list32_t));
4053 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4055 outs() << " entsize " << il.entsize << "\n";
4056 outs() << " count " << il.count << "\n";
4058 p += sizeof(struct ivar_list32_t);
4059 offset += sizeof(struct ivar_list32_t);
4060 for (j = 0; j < il.count; j++) {
4061 r = get_pointer_32(p, offset, left, S, info);
4064 memset(&i, '\0', sizeof(struct ivar32_t));
4065 if (left < sizeof(struct ivar32_t)) {
4066 memcpy(&i, r, left);
4067 outs() << " (ivar_t entends past the end of the section)\n";
4069 memcpy(&i, r, sizeof(struct ivar32_t));
4070 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4073 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4074 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4075 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4076 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4077 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4078 sys::swapByteOrder(ivar_offset);
4079 outs() << " " << ivar_offset << "\n";
4083 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4084 name = get_pointer_32(i.name, xoffset, left, xS, info);
4085 if (name != nullptr)
4086 outs() << format(" %.*s", left, name);
4089 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4090 name = get_pointer_32(i.type, xoffset, left, xS, info);
4091 if (name != nullptr)
4092 outs() << format(" %.*s", left, name);
4095 outs() << "\t\t\talignment " << i.alignment << "\n";
4096 outs() << "\t\t\t size " << i.size << "\n";
4098 p += sizeof(struct ivar32_t);
4099 offset += sizeof(struct ivar32_t);
4103 static void print_objc_property_list64(uint64_t p,
4104 struct DisassembleInfo *info) {
4105 struct objc_property_list64 opl;
4106 struct objc_property64 op;
4108 uint32_t offset, xoffset, left, j;
4110 const char *name, *sym_name;
4113 r = get_pointer_64(p, offset, left, S, info);
4116 memset(&opl, '\0', sizeof(struct objc_property_list64));
4117 if (left < sizeof(struct objc_property_list64)) {
4118 memcpy(&opl, r, left);
4119 outs() << " (objc_property_list entends past the end of the section)\n";
4121 memcpy(&opl, r, sizeof(struct objc_property_list64));
4122 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4124 outs() << " entsize " << opl.entsize << "\n";
4125 outs() << " count " << opl.count << "\n";
4127 p += sizeof(struct objc_property_list64);
4128 offset += sizeof(struct objc_property_list64);
4129 for (j = 0; j < opl.count; j++) {
4130 r = get_pointer_64(p, offset, left, S, info);
4133 memset(&op, '\0', sizeof(struct objc_property64));
4134 if (left < sizeof(struct objc_property64)) {
4135 memcpy(&op, r, left);
4136 outs() << " (objc_property entends past the end of the section)\n";
4138 memcpy(&op, r, sizeof(struct objc_property64));
4139 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4142 outs() << "\t\t\t name ";
4143 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4144 info, n_value, op.name);
4146 if (info->verbose && sym_name != nullptr)
4149 outs() << format("0x%" PRIx64, n_value);
4151 outs() << " + " << format("0x%" PRIx64, op.name);
4153 outs() << format("0x%" PRIx64, op.name);
4154 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4155 if (name != nullptr)
4156 outs() << format(" %.*s", left, name);
4159 outs() << "\t\t\tattributes ";
4161 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4162 info, n_value, op.attributes);
4164 if (info->verbose && sym_name != nullptr)
4167 outs() << format("0x%" PRIx64, n_value);
4168 if (op.attributes != 0)
4169 outs() << " + " << format("0x%" PRIx64, op.attributes);
4171 outs() << format("0x%" PRIx64, op.attributes);
4172 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4173 if (name != nullptr)
4174 outs() << format(" %.*s", left, name);
4177 p += sizeof(struct objc_property64);
4178 offset += sizeof(struct objc_property64);
4182 static void print_objc_property_list32(uint32_t p,
4183 struct DisassembleInfo *info) {
4184 struct objc_property_list32 opl;
4185 struct objc_property32 op;
4187 uint32_t offset, xoffset, left, j;
4191 r = get_pointer_32(p, offset, left, S, info);
4194 memset(&opl, '\0', sizeof(struct objc_property_list32));
4195 if (left < sizeof(struct objc_property_list32)) {
4196 memcpy(&opl, r, left);
4197 outs() << " (objc_property_list entends past the end of the section)\n";
4199 memcpy(&opl, r, sizeof(struct objc_property_list32));
4200 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4202 outs() << " entsize " << opl.entsize << "\n";
4203 outs() << " count " << opl.count << "\n";
4205 p += sizeof(struct objc_property_list32);
4206 offset += sizeof(struct objc_property_list32);
4207 for (j = 0; j < opl.count; j++) {
4208 r = get_pointer_32(p, offset, left, S, info);
4211 memset(&op, '\0', sizeof(struct objc_property32));
4212 if (left < sizeof(struct objc_property32)) {
4213 memcpy(&op, r, left);
4214 outs() << " (objc_property entends past the end of the section)\n";
4216 memcpy(&op, r, sizeof(struct objc_property32));
4217 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4220 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4221 name = get_pointer_32(op.name, xoffset, left, xS, info);
4222 if (name != nullptr)
4223 outs() << format(" %.*s", left, name);
4226 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4227 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4228 if (name != nullptr)
4229 outs() << format(" %.*s", left, name);
4232 p += sizeof(struct objc_property32);
4233 offset += sizeof(struct objc_property32);
4237 static void print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
4238 bool &is_meta_class) {
4239 struct class_ro64_t cro;
4241 uint32_t offset, xoffset, left;
4243 const char *name, *sym_name;
4246 r = get_pointer_64(p, offset, left, S, info);
4247 if (r == nullptr || left < sizeof(struct class_ro64_t))
4249 memset(&cro, '\0', sizeof(struct class_ro64_t));
4250 if (left < sizeof(struct class_ro64_t)) {
4251 memcpy(&cro, r, left);
4252 outs() << " (class_ro_t entends past the end of the section)\n";
4254 memcpy(&cro, r, sizeof(struct class_ro64_t));
4255 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4257 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4258 if (cro.flags & RO_META)
4259 outs() << " RO_META";
4260 if (cro.flags & RO_ROOT)
4261 outs() << " RO_ROOT";
4262 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4263 outs() << " RO_HAS_CXX_STRUCTORS";
4265 outs() << " instanceStart " << cro.instanceStart << "\n";
4266 outs() << " instanceSize " << cro.instanceSize << "\n";
4267 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4269 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4271 print_layout_map64(cro.ivarLayout, info);
4274 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4275 info, n_value, cro.name);
4277 if (info->verbose && sym_name != nullptr)
4280 outs() << format("0x%" PRIx64, n_value);
4282 outs() << " + " << format("0x%" PRIx64, cro.name);
4284 outs() << format("0x%" PRIx64, cro.name);
4285 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4286 if (name != nullptr)
4287 outs() << format(" %.*s", left, name);
4290 outs() << " baseMethods ";
4291 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4292 S, info, n_value, cro.baseMethods);
4294 if (info->verbose && sym_name != nullptr)
4297 outs() << format("0x%" PRIx64, n_value);
4298 if (cro.baseMethods != 0)
4299 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4301 outs() << format("0x%" PRIx64, cro.baseMethods);
4302 outs() << " (struct method_list_t *)\n";
4303 if (cro.baseMethods + n_value != 0)
4304 print_method_list64_t(cro.baseMethods + n_value, info, "");
4306 outs() << " baseProtocols ";
4308 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4309 info, n_value, cro.baseProtocols);
4311 if (info->verbose && sym_name != nullptr)
4314 outs() << format("0x%" PRIx64, n_value);
4315 if (cro.baseProtocols != 0)
4316 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4318 outs() << format("0x%" PRIx64, cro.baseProtocols);
4320 if (cro.baseProtocols + n_value != 0)
4321 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4323 outs() << " ivars ";
4324 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
4325 info, n_value, cro.ivars);
4327 if (info->verbose && sym_name != nullptr)
4330 outs() << format("0x%" PRIx64, n_value);
4332 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4334 outs() << format("0x%" PRIx64, cro.ivars);
4336 if (cro.ivars + n_value != 0)
4337 print_ivar_list64_t(cro.ivars + n_value, info);
4339 outs() << " weakIvarLayout ";
4341 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4342 info, n_value, cro.weakIvarLayout);
4344 if (info->verbose && sym_name != nullptr)
4347 outs() << format("0x%" PRIx64, n_value);
4348 if (cro.weakIvarLayout != 0)
4349 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4351 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4353 print_layout_map64(cro.weakIvarLayout + n_value, info);
4355 outs() << " baseProperties ";
4357 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4358 info, n_value, cro.baseProperties);
4360 if (info->verbose && sym_name != nullptr)
4363 outs() << format("0x%" PRIx64, n_value);
4364 if (cro.baseProperties != 0)
4365 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4367 outs() << format("0x%" PRIx64, cro.baseProperties);
4369 if (cro.baseProperties + n_value != 0)
4370 print_objc_property_list64(cro.baseProperties + n_value, info);
4372 is_meta_class = (cro.flags & RO_META) ? true : false;
4375 static void print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
4376 bool &is_meta_class) {
4377 struct class_ro32_t cro;
4379 uint32_t offset, xoffset, left;
4383 r = get_pointer_32(p, offset, left, S, info);
4386 memset(&cro, '\0', sizeof(struct class_ro32_t));
4387 if (left < sizeof(struct class_ro32_t)) {
4388 memcpy(&cro, r, left);
4389 outs() << " (class_ro_t entends past the end of the section)\n";
4391 memcpy(&cro, r, sizeof(struct class_ro32_t));
4392 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4394 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4395 if (cro.flags & RO_META)
4396 outs() << " RO_META";
4397 if (cro.flags & RO_ROOT)
4398 outs() << " RO_ROOT";
4399 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4400 outs() << " RO_HAS_CXX_STRUCTORS";
4402 outs() << " instanceStart " << cro.instanceStart << "\n";
4403 outs() << " instanceSize " << cro.instanceSize << "\n";
4404 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4406 print_layout_map32(cro.ivarLayout, info);
4408 outs() << " name " << format("0x%" PRIx32, cro.name);
4409 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4410 if (name != nullptr)
4411 outs() << format(" %.*s", left, name);
4414 outs() << " baseMethods "
4415 << format("0x%" PRIx32, cro.baseMethods)
4416 << " (struct method_list_t *)\n";
4417 if (cro.baseMethods != 0)
4418 print_method_list32_t(cro.baseMethods, info, "");
4420 outs() << " baseProtocols "
4421 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4422 if (cro.baseProtocols != 0)
4423 print_protocol_list32_t(cro.baseProtocols, info);
4424 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4427 print_ivar_list32_t(cro.ivars, info);
4428 outs() << " weakIvarLayout "
4429 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4430 print_layout_map32(cro.weakIvarLayout, info);
4431 outs() << " baseProperties "
4432 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4433 if (cro.baseProperties != 0)
4434 print_objc_property_list32(cro.baseProperties, info);
4435 is_meta_class = (cro.flags & RO_META) ? true : false;
4438 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4441 uint32_t offset, left;
4444 uint64_t isa_n_value, n_value;
4446 r = get_pointer_64(p, offset, left, S, info);
4447 if (r == nullptr || left < sizeof(struct class64_t))
4449 memset(&c, '\0', sizeof(struct class64_t));
4450 if (left < sizeof(struct class64_t)) {
4451 memcpy(&c, r, left);
4452 outs() << " (class_t entends past the end of the section)\n";
4454 memcpy(&c, r, sizeof(struct class64_t));
4455 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4458 outs() << " isa " << format("0x%" PRIx64, c.isa);
4459 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4460 isa_n_value, c.isa);
4461 if (name != nullptr)
4462 outs() << " " << name;
4465 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4466 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4467 n_value, c.superclass);
4468 if (name != nullptr)
4469 outs() << " " << name;
4472 outs() << " cache " << format("0x%" PRIx64, c.cache);
4473 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4475 if (name != nullptr)
4476 outs() << " " << name;
4479 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4480 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4482 if (name != nullptr)
4483 outs() << " " << name;
4486 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4490 if (info->verbose && name != nullptr)
4493 outs() << format("0x%" PRIx64, n_value);
4495 outs() << " + " << format("0x%" PRIx64, c.data);
4497 outs() << format("0x%" PRIx64, c.data);
4498 outs() << " (struct class_ro_t *)";
4500 // This is a Swift class if some of the low bits of the pointer are set.
4501 if ((c.data + n_value) & 0x7)
4502 outs() << " Swift class";
4505 print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class);
4507 if (is_meta_class == false) {
4508 outs() << "Meta Class\n";
4509 print_class64_t(c.isa + isa_n_value, info);
4513 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4516 uint32_t offset, left;
4520 r = get_pointer_32(p, offset, left, S, info);
4523 memset(&c, '\0', sizeof(struct class32_t));
4524 if (left < sizeof(struct class32_t)) {
4525 memcpy(&c, r, left);
4526 outs() << " (class_t entends past the end of the section)\n";
4528 memcpy(&c, r, sizeof(struct class32_t));
4529 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4532 outs() << " isa " << format("0x%" PRIx32, c.isa);
4534 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4535 if (name != nullptr)
4536 outs() << " " << name;
4539 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4540 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4542 if (name != nullptr)
4543 outs() << " " << name;
4546 outs() << " cache " << format("0x%" PRIx32, c.cache);
4547 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4549 if (name != nullptr)
4550 outs() << " " << name;
4553 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4554 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4556 if (name != nullptr)
4557 outs() << " " << name;
4561 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4562 outs() << " data " << format("0x%" PRIx32, c.data)
4563 << " (struct class_ro_t *)";
4565 // This is a Swift class if some of the low bits of the pointer are set.
4567 outs() << " Swift class";
4570 print_class_ro32_t(c.data & ~0x3, info, is_meta_class);
4572 if (is_meta_class == false) {
4573 outs() << "Meta Class\n";
4574 print_class32_t(c.isa, info);
4578 static void print_objc_class_t(struct objc_class_t *objc_class,
4579 struct DisassembleInfo *info) {
4580 uint32_t offset, left, xleft;
4581 const char *name, *p, *ivar_list;
4584 struct objc_ivar_list_t objc_ivar_list;
4585 struct objc_ivar_t ivar;
4587 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4588 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4589 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4590 if (name != nullptr)
4591 outs() << format(" %.*s", left, name);
4593 outs() << " (not in an __OBJC section)";
4597 outs() << "\t super_class "
4598 << format("0x%08" PRIx32, objc_class->super_class);
4599 if (info->verbose) {
4600 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4601 if (name != nullptr)
4602 outs() << format(" %.*s", left, name);
4604 outs() << " (not in an __OBJC section)";
4608 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4609 if (info->verbose) {
4610 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4611 if (name != nullptr)
4612 outs() << format(" %.*s", left, name);
4614 outs() << " (not in an __OBJC section)";
4618 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4621 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4622 if (info->verbose) {
4623 if (CLS_GETINFO(objc_class, CLS_CLASS))
4624 outs() << " CLS_CLASS";
4625 else if (CLS_GETINFO(objc_class, CLS_META))
4626 outs() << " CLS_META";
4630 outs() << "\t instance_size "
4631 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4633 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4634 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4636 if (left > sizeof(struct objc_ivar_list_t)) {
4638 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4640 outs() << " (entends past the end of the section)\n";
4641 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4642 memcpy(&objc_ivar_list, p, left);
4644 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4645 swapStruct(objc_ivar_list);
4646 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4647 ivar_list = p + sizeof(struct objc_ivar_list_t);
4648 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4649 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4650 outs() << "\t\t remaining ivar's extend past the of the section\n";
4653 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4654 sizeof(struct objc_ivar_t));
4655 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4658 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4659 if (info->verbose) {
4660 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4661 if (name != nullptr)
4662 outs() << format(" %.*s", xleft, name);
4664 outs() << " (not in an __OBJC section)";
4668 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4669 if (info->verbose) {
4670 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4671 if (name != nullptr)
4672 outs() << format(" %.*s", xleft, name);
4674 outs() << " (not in an __OBJC section)";
4678 outs() << "\t\t ivar_offset "
4679 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4682 outs() << " (not in an __OBJC section)\n";
4685 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4686 if (print_method_list(objc_class->methodLists, info))
4687 outs() << " (not in an __OBJC section)\n";
4689 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4692 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4693 if (print_protocol_list(objc_class->protocols, 16, info))
4694 outs() << " (not in an __OBJC section)\n";
4697 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4698 struct DisassembleInfo *info) {
4699 uint32_t offset, left;
4703 outs() << "\t category name "
4704 << format("0x%08" PRIx32, objc_category->category_name);
4705 if (info->verbose) {
4706 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4708 if (name != nullptr)
4709 outs() << format(" %.*s", left, name);
4711 outs() << " (not in an __OBJC section)";
4715 outs() << "\t\t class name "
4716 << format("0x%08" PRIx32, objc_category->class_name);
4717 if (info->verbose) {
4719 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4720 if (name != nullptr)
4721 outs() << format(" %.*s", left, name);
4723 outs() << " (not in an __OBJC section)";
4727 outs() << "\t instance methods "
4728 << format("0x%08" PRIx32, objc_category->instance_methods);
4729 if (print_method_list(objc_category->instance_methods, info))
4730 outs() << " (not in an __OBJC section)\n";
4732 outs() << "\t class methods "
4733 << format("0x%08" PRIx32, objc_category->class_methods);
4734 if (print_method_list(objc_category->class_methods, info))
4735 outs() << " (not in an __OBJC section)\n";
4738 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4739 struct category64_t c;
4741 uint32_t offset, xoffset, left;
4743 const char *name, *sym_name;
4746 r = get_pointer_64(p, offset, left, S, info);
4749 memset(&c, '\0', sizeof(struct category64_t));
4750 if (left < sizeof(struct category64_t)) {
4751 memcpy(&c, r, left);
4752 outs() << " (category_t entends past the end of the section)\n";
4754 memcpy(&c, r, sizeof(struct category64_t));
4755 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4759 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4760 info, n_value, c.name);
4762 if (info->verbose && sym_name != nullptr)
4765 outs() << format("0x%" PRIx64, n_value);
4767 outs() << " + " << format("0x%" PRIx64, c.name);
4769 outs() << format("0x%" PRIx64, c.name);
4770 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4771 if (name != nullptr)
4772 outs() << format(" %.*s", left, name);
4776 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4779 if (info->verbose && sym_name != nullptr)
4782 outs() << format("0x%" PRIx64, n_value);
4784 outs() << " + " << format("0x%" PRIx64, c.cls);
4786 outs() << format("0x%" PRIx64, c.cls);
4788 if (c.cls + n_value != 0)
4789 print_class64_t(c.cls + n_value, info);
4791 outs() << " instanceMethods ";
4793 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4794 info, n_value, c.instanceMethods);
4796 if (info->verbose && sym_name != nullptr)
4799 outs() << format("0x%" PRIx64, n_value);
4800 if (c.instanceMethods != 0)
4801 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4803 outs() << format("0x%" PRIx64, c.instanceMethods);
4805 if (c.instanceMethods + n_value != 0)
4806 print_method_list64_t(c.instanceMethods + n_value, info, "");
4808 outs() << " classMethods ";
4809 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4810 S, info, n_value, c.classMethods);
4812 if (info->verbose && sym_name != nullptr)
4815 outs() << format("0x%" PRIx64, n_value);
4816 if (c.classMethods != 0)
4817 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4819 outs() << format("0x%" PRIx64, c.classMethods);
4821 if (c.classMethods + n_value != 0)
4822 print_method_list64_t(c.classMethods + n_value, info, "");
4824 outs() << " protocols ";
4825 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4826 info, n_value, c.protocols);
4828 if (info->verbose && sym_name != nullptr)
4831 outs() << format("0x%" PRIx64, n_value);
4832 if (c.protocols != 0)
4833 outs() << " + " << format("0x%" PRIx64, c.protocols);
4835 outs() << format("0x%" PRIx64, c.protocols);
4837 if (c.protocols + n_value != 0)
4838 print_protocol_list64_t(c.protocols + n_value, info);
4840 outs() << "instanceProperties ";
4842 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4843 S, info, n_value, c.instanceProperties);
4845 if (info->verbose && sym_name != nullptr)
4848 outs() << format("0x%" PRIx64, n_value);
4849 if (c.instanceProperties != 0)
4850 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4852 outs() << format("0x%" PRIx64, c.instanceProperties);
4854 if (c.instanceProperties + n_value != 0)
4855 print_objc_property_list64(c.instanceProperties + n_value, info);
4858 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4859 struct category32_t c;
4861 uint32_t offset, left;
4865 r = get_pointer_32(p, offset, left, S, info);
4868 memset(&c, '\0', sizeof(struct category32_t));
4869 if (left < sizeof(struct category32_t)) {
4870 memcpy(&c, r, left);
4871 outs() << " (category_t entends past the end of the section)\n";
4873 memcpy(&c, r, sizeof(struct category32_t));
4874 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4877 outs() << " name " << format("0x%" PRIx32, c.name);
4878 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4881 outs() << " " << name;
4884 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4886 print_class32_t(c.cls, info);
4887 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4889 if (c.instanceMethods != 0)
4890 print_method_list32_t(c.instanceMethods, info, "");
4891 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4893 if (c.classMethods != 0)
4894 print_method_list32_t(c.classMethods, info, "");
4895 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4896 if (c.protocols != 0)
4897 print_protocol_list32_t(c.protocols, info);
4898 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4900 if (c.instanceProperties != 0)
4901 print_objc_property_list32(c.instanceProperties, info);
4904 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4905 uint32_t i, left, offset, xoffset;
4906 uint64_t p, n_value;
4907 struct message_ref64 mr;
4908 const char *name, *sym_name;
4912 if (S == SectionRef())
4916 S.getName(SectName);
4917 DataRefImpl Ref = S.getRawDataRefImpl();
4918 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4919 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4921 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4922 p = S.getAddress() + i;
4923 r = get_pointer_64(p, offset, left, S, info);
4926 memset(&mr, '\0', sizeof(struct message_ref64));
4927 if (left < sizeof(struct message_ref64)) {
4928 memcpy(&mr, r, left);
4929 outs() << " (message_ref entends past the end of the section)\n";
4931 memcpy(&mr, r, sizeof(struct message_ref64));
4932 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4936 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4939 outs() << format("0x%" PRIx64, n_value) << " ";
4941 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4943 outs() << format("0x%" PRIx64, mr.imp) << " ";
4944 if (name != nullptr)
4945 outs() << " " << name;
4949 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4950 info, n_value, mr.sel);
4952 if (info->verbose && sym_name != nullptr)
4955 outs() << format("0x%" PRIx64, n_value);
4957 outs() << " + " << format("0x%" PRIx64, mr.sel);
4959 outs() << format("0x%" PRIx64, mr.sel);
4960 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4961 if (name != nullptr)
4962 outs() << format(" %.*s", left, name);
4965 offset += sizeof(struct message_ref64);
4969 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
4970 uint32_t i, left, offset, xoffset, p;
4971 struct message_ref32 mr;
4972 const char *name, *r;
4975 if (S == SectionRef())
4979 S.getName(SectName);
4980 DataRefImpl Ref = S.getRawDataRefImpl();
4981 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4982 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4984 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4985 p = S.getAddress() + i;
4986 r = get_pointer_32(p, offset, left, S, info);
4989 memset(&mr, '\0', sizeof(struct message_ref32));
4990 if (left < sizeof(struct message_ref32)) {
4991 memcpy(&mr, r, left);
4992 outs() << " (message_ref entends past the end of the section)\n";
4994 memcpy(&mr, r, sizeof(struct message_ref32));
4995 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4998 outs() << " imp " << format("0x%" PRIx32, mr.imp);
4999 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5001 if (name != nullptr)
5002 outs() << " " << name;
5005 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5006 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5007 if (name != nullptr)
5008 outs() << " " << name;
5011 offset += sizeof(struct message_ref32);
5015 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5016 uint32_t left, offset, swift_version;
5018 struct objc_image_info64 o;
5022 S.getName(SectName);
5023 DataRefImpl Ref = S.getRawDataRefImpl();
5024 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5025 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5027 r = get_pointer_64(p, offset, left, S, info);
5030 memset(&o, '\0', sizeof(struct objc_image_info64));
5031 if (left < sizeof(struct objc_image_info64)) {
5032 memcpy(&o, r, left);
5033 outs() << " (objc_image_info entends past the end of the section)\n";
5035 memcpy(&o, r, sizeof(struct objc_image_info64));
5036 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5038 outs() << " version " << o.version << "\n";
5039 outs() << " flags " << format("0x%" PRIx32, o.flags);
5040 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5041 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5042 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5043 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5044 swift_version = (o.flags >> 8) & 0xff;
5045 if (swift_version != 0) {
5046 if (swift_version == 1)
5047 outs() << " Swift 1.0";
5048 else if (swift_version == 2)
5049 outs() << " Swift 1.1";
5051 outs() << " unknown future Swift version (" << swift_version << ")";
5056 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5057 uint32_t left, offset, swift_version, p;
5058 struct objc_image_info32 o;
5062 S.getName(SectName);
5063 DataRefImpl Ref = S.getRawDataRefImpl();
5064 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5065 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5067 r = get_pointer_32(p, offset, left, S, info);
5070 memset(&o, '\0', sizeof(struct objc_image_info32));
5071 if (left < sizeof(struct objc_image_info32)) {
5072 memcpy(&o, r, left);
5073 outs() << " (objc_image_info entends past the end of the section)\n";
5075 memcpy(&o, r, sizeof(struct objc_image_info32));
5076 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5078 outs() << " version " << o.version << "\n";
5079 outs() << " flags " << format("0x%" PRIx32, o.flags);
5080 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5081 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5082 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5083 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5084 swift_version = (o.flags >> 8) & 0xff;
5085 if (swift_version != 0) {
5086 if (swift_version == 1)
5087 outs() << " Swift 1.0";
5088 else if (swift_version == 2)
5089 outs() << " Swift 1.1";
5091 outs() << " unknown future Swift version (" << swift_version << ")";
5096 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5097 uint32_t left, offset, p;
5098 struct imageInfo_t o;
5102 S.getName(SectName);
5103 DataRefImpl Ref = S.getRawDataRefImpl();
5104 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5105 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5107 r = get_pointer_32(p, offset, left, S, info);
5110 memset(&o, '\0', sizeof(struct imageInfo_t));
5111 if (left < sizeof(struct imageInfo_t)) {
5112 memcpy(&o, r, left);
5113 outs() << " (imageInfo entends past the end of the section)\n";
5115 memcpy(&o, r, sizeof(struct imageInfo_t));
5116 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5118 outs() << " version " << o.version << "\n";
5119 outs() << " flags " << format("0x%" PRIx32, o.flags);
5125 outs() << " GC-only";
5131 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5132 SymbolAddressMap AddrMap;
5134 CreateSymbolAddressMap(O, &AddrMap);
5136 std::vector<SectionRef> Sections;
5137 for (const SectionRef &Section : O->sections()) {
5139 Section.getName(SectName);
5140 Sections.push_back(Section);
5143 struct DisassembleInfo info;
5144 // Set up the block of info used by the Symbolizer call backs.
5145 info.verbose = verbose;
5147 info.AddrMap = &AddrMap;
5148 info.Sections = &Sections;
5149 info.class_name = nullptr;
5150 info.selector_name = nullptr;
5151 info.method = nullptr;
5152 info.demangled_name = nullptr;
5153 info.bindtable = nullptr;
5157 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5158 if (CL != SectionRef()) {
5160 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5162 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5164 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5167 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5168 if (CR != SectionRef()) {
5170 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5172 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5174 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5177 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5178 if (SR != SectionRef()) {
5180 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5182 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5184 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5187 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5188 if (CA != SectionRef()) {
5190 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5192 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5194 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5197 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5198 if (PL != SectionRef()) {
5200 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5202 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5204 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5207 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5208 if (MR != SectionRef()) {
5210 print_message_refs64(MR, &info);
5212 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5214 print_message_refs64(MR, &info);
5217 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5218 if (II != SectionRef()) {
5220 print_image_info64(II, &info);
5222 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5224 print_image_info64(II, &info);
5227 if (info.bindtable != nullptr)
5228 delete info.bindtable;
5231 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5232 SymbolAddressMap AddrMap;
5234 CreateSymbolAddressMap(O, &AddrMap);
5236 std::vector<SectionRef> Sections;
5237 for (const SectionRef &Section : O->sections()) {
5239 Section.getName(SectName);
5240 Sections.push_back(Section);
5243 struct DisassembleInfo info;
5244 // Set up the block of info used by the Symbolizer call backs.
5245 info.verbose = verbose;
5247 info.AddrMap = &AddrMap;
5248 info.Sections = &Sections;
5249 info.class_name = nullptr;
5250 info.selector_name = nullptr;
5251 info.method = nullptr;
5252 info.demangled_name = nullptr;
5253 info.bindtable = nullptr;
5257 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5258 if (CL != SectionRef()) {
5260 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5262 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5264 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5267 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5268 if (CR != SectionRef()) {
5270 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5272 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5274 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5277 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5278 if (SR != SectionRef()) {
5280 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5282 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5284 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5287 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5288 if (CA != SectionRef()) {
5290 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5292 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5294 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5297 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5298 if (PL != SectionRef()) {
5300 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5302 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5304 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5307 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5308 if (MR != SectionRef()) {
5310 print_message_refs32(MR, &info);
5312 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5314 print_message_refs32(MR, &info);
5317 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5318 if (II != SectionRef()) {
5320 print_image_info32(II, &info);
5322 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5324 print_image_info32(II, &info);
5328 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5329 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5330 const char *r, *name, *defs;
5331 struct objc_module_t module;
5333 struct objc_symtab_t symtab;
5334 struct objc_class_t objc_class;
5335 struct objc_category_t objc_category;
5337 outs() << "Objective-C segment\n";
5338 S = get_section(O, "__OBJC", "__module_info");
5339 if (S == SectionRef())
5342 SymbolAddressMap AddrMap;
5344 CreateSymbolAddressMap(O, &AddrMap);
5346 std::vector<SectionRef> Sections;
5347 for (const SectionRef &Section : O->sections()) {
5349 Section.getName(SectName);
5350 Sections.push_back(Section);
5353 struct DisassembleInfo info;
5354 // Set up the block of info used by the Symbolizer call backs.
5355 info.verbose = verbose;
5357 info.AddrMap = &AddrMap;
5358 info.Sections = &Sections;
5359 info.class_name = nullptr;
5360 info.selector_name = nullptr;
5361 info.method = nullptr;
5362 info.demangled_name = nullptr;
5363 info.bindtable = nullptr;
5367 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5368 p = S.getAddress() + i;
5369 r = get_pointer_32(p, offset, left, S, &info, true);
5372 memset(&module, '\0', sizeof(struct objc_module_t));
5373 if (left < sizeof(struct objc_module_t)) {
5374 memcpy(&module, r, left);
5375 outs() << " (module extends past end of __module_info section)\n";
5377 memcpy(&module, r, sizeof(struct objc_module_t));
5378 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5381 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5382 outs() << " version " << module.version << "\n";
5383 outs() << " size " << module.size << "\n";
5385 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5386 if (name != nullptr)
5387 outs() << format("%.*s", left, name);
5389 outs() << format("0x%08" PRIx32, module.name)
5390 << "(not in an __OBJC section)";
5393 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5394 if (module.symtab == 0 || r == nullptr) {
5395 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5396 << " (not in an __OBJC section)\n";
5399 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5400 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5403 if (left < sizeof(struct objc_symtab_t)) {
5404 memcpy(&symtab, r, left);
5405 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5407 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5408 if (left > sizeof(struct objc_symtab_t)) {
5409 defs_left = left - sizeof(struct objc_symtab_t);
5410 defs = r + sizeof(struct objc_symtab_t);
5413 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5416 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5417 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5418 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5420 outs() << " (not in an __OBJC section)";
5422 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5423 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5424 if (symtab.cls_def_cnt > 0)
5425 outs() << "\tClass Definitions\n";
5426 for (j = 0; j < symtab.cls_def_cnt; j++) {
5427 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5428 outs() << "\t(remaining class defs entries entends past the end of the "
5432 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5433 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5434 sys::swapByteOrder(def);
5436 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5437 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5439 if (left > sizeof(struct objc_class_t)) {
5441 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5443 outs() << " (entends past the end of the section)\n";
5444 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5445 memcpy(&objc_class, r, left);
5447 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5448 swapStruct(objc_class);
5449 print_objc_class_t(&objc_class, &info);
5451 outs() << "(not in an __OBJC section)\n";
5454 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5455 outs() << "\tMeta Class";
5456 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5458 if (left > sizeof(struct objc_class_t)) {
5460 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5462 outs() << " (entends past the end of the section)\n";
5463 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5464 memcpy(&objc_class, r, left);
5466 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5467 swapStruct(objc_class);
5468 print_objc_class_t(&objc_class, &info);
5470 outs() << "(not in an __OBJC section)\n";
5474 if (symtab.cat_def_cnt > 0)
5475 outs() << "\tCategory Definitions\n";
5476 for (j = 0; j < symtab.cat_def_cnt; j++) {
5477 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5478 outs() << "\t(remaining category defs entries entends past the end of "
5479 << "the section)\n";
5482 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5484 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5485 sys::swapByteOrder(def);
5487 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5488 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5489 << format("0x%08" PRIx32, def);
5491 if (left > sizeof(struct objc_category_t)) {
5493 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5495 outs() << " (entends past the end of the section)\n";
5496 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5497 memcpy(&objc_category, r, left);
5499 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5500 swapStruct(objc_category);
5501 print_objc_objc_category_t(&objc_category, &info);
5503 outs() << "(not in an __OBJC section)\n";
5507 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5508 if (II != SectionRef())
5509 print_image_info(II, &info);
5514 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5515 uint32_t size, uint32_t addr) {
5516 SymbolAddressMap AddrMap;
5517 CreateSymbolAddressMap(O, &AddrMap);
5519 std::vector<SectionRef> Sections;
5520 for (const SectionRef &Section : O->sections()) {
5522 Section.getName(SectName);
5523 Sections.push_back(Section);
5526 struct DisassembleInfo info;
5527 // Set up the block of info used by the Symbolizer call backs.
5528 info.verbose = true;
5530 info.AddrMap = &AddrMap;
5531 info.Sections = &Sections;
5532 info.class_name = nullptr;
5533 info.selector_name = nullptr;
5534 info.method = nullptr;
5535 info.demangled_name = nullptr;
5536 info.bindtable = nullptr;
5541 struct objc_protocol_t protocol;
5542 uint32_t left, paddr;
5543 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5544 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5545 left = size - (p - sect);
5546 if (left < sizeof(struct objc_protocol_t)) {
5547 outs() << "Protocol extends past end of __protocol section\n";
5548 memcpy(&protocol, p, left);
5550 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5551 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5552 swapStruct(protocol);
5553 paddr = addr + (p - sect);
5554 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5555 if (print_protocol(paddr, 0, &info))
5556 outs() << "(not in an __OBJC section)\n";
5560 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5562 printObjc2_64bit_MetaData(O, verbose);
5564 MachO::mach_header H;
5566 if (H.cputype == MachO::CPU_TYPE_ARM)
5567 printObjc2_32bit_MetaData(O, verbose);
5569 // This is the 32-bit non-arm cputype case. Which is normally
5570 // the first Objective-C ABI. But it may be the case of a
5571 // binary for the iOS simulator which is the second Objective-C
5572 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5573 // and return false.
5574 if (printObjc1_32bit_MetaData(O, verbose) == false)
5575 printObjc2_32bit_MetaData(O, verbose);
5580 // GuessLiteralPointer returns a string which for the item in the Mach-O file
5581 // for the address passed in as ReferenceValue for printing as a comment with
5582 // the instruction and also returns the corresponding type of that item
5583 // indirectly through ReferenceType.
5585 // If ReferenceValue is an address of literal cstring then a pointer to the
5586 // cstring is returned and ReferenceType is set to
5587 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5589 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5590 // Class ref that name is returned and the ReferenceType is set accordingly.
5592 // Lastly, literals which are Symbol address in a literal pool are looked for
5593 // and if found the symbol name is returned and ReferenceType is set to
5594 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5596 // If there is no item in the Mach-O file for the address passed in as
5597 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
5598 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5599 uint64_t ReferencePC,
5600 uint64_t *ReferenceType,
5601 struct DisassembleInfo *info) {
5602 // First see if there is an external relocation entry at the ReferencePC.
5603 uint64_t sect_addr = info->S.getAddress();
5604 uint64_t sect_offset = ReferencePC - sect_addr;
5605 bool reloc_found = false;
5607 MachO::any_relocation_info RE;
5608 bool isExtern = false;
5610 for (const RelocationRef &Reloc : info->S.relocations()) {
5611 uint64_t RelocOffset = Reloc.getOffset();
5612 if (RelocOffset == sect_offset) {
5613 Rel = Reloc.getRawDataRefImpl();
5614 RE = info->O->getRelocation(Rel);
5615 if (info->O->isRelocationScattered(RE))
5617 isExtern = info->O->getPlainRelocationExternal(RE);
5619 symbol_iterator RelocSym = Reloc.getSymbol();
5626 // If there is an external relocation entry for a symbol in a section
5627 // then used that symbol's value for the value of the reference.
5628 if (reloc_found && isExtern) {
5629 if (info->O->getAnyRelocationPCRel(RE)) {
5630 unsigned Type = info->O->getAnyRelocationType(RE);
5631 if (Type == MachO::X86_64_RELOC_SIGNED) {
5632 ReferenceValue = Symbol.getValue();
5637 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5638 // Message refs and Class refs.
5639 bool classref, selref, msgref, cfstring;
5640 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5641 selref, msgref, cfstring);
5642 if (classref && pointer_value == 0) {
5643 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5644 // And the pointer_value in that section is typically zero as it will be
5645 // set by dyld as part of the "bind information".
5646 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5647 if (name != nullptr) {
5648 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5649 const char *class_name = strrchr(name, '$');
5650 if (class_name != nullptr && class_name[1] == '_' &&
5651 class_name[2] != '\0') {
5652 info->class_name = class_name + 2;
5659 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5661 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5662 if (name != nullptr)
5663 info->class_name = name;
5665 name = "bad class ref";
5670 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5671 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5675 if (selref && pointer_value == 0)
5676 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5678 if (pointer_value != 0)
5679 ReferenceValue = pointer_value;
5681 const char *name = GuessCstringPointer(ReferenceValue, info);
5683 if (pointer_value != 0 && selref) {
5684 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5685 info->selector_name = name;
5686 } else if (pointer_value != 0 && msgref) {
5687 info->class_name = nullptr;
5688 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5689 info->selector_name = name;
5691 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5695 // Lastly look for an indirect symbol with this ReferenceValue which is in
5696 // a literal pool. If found return that symbol name.
5697 name = GuessIndirectSymbol(ReferenceValue, info);
5699 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5706 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
5707 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
5708 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5709 // is created and returns the symbol name that matches the ReferenceValue or
5710 // nullptr if none. The ReferenceType is passed in for the IN type of
5711 // reference the instruction is making from the values in defined in the header
5712 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5713 // Out type and the ReferenceName will also be set which is added as a comment
5714 // to the disassembled instruction.
5717 // If the symbol name is a C++ mangled name then the demangled name is
5718 // returned through ReferenceName and ReferenceType is set to
5719 // LLVMDisassembler_ReferenceType_DeMangled_Name .
5722 // When this is called to get a symbol name for a branch target then the
5723 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5724 // SymbolValue will be looked for in the indirect symbol table to determine if
5725 // it is an address for a symbol stub. If so then the symbol name for that
5726 // stub is returned indirectly through ReferenceName and then ReferenceType is
5727 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5729 // When this is called with an value loaded via a PC relative load then
5730 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5731 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
5732 // or an Objective-C meta data reference. If so the output ReferenceType is
5733 // set to correspond to that as well as setting the ReferenceName.
5734 static const char *SymbolizerSymbolLookUp(void *DisInfo,
5735 uint64_t ReferenceValue,
5736 uint64_t *ReferenceType,
5737 uint64_t ReferencePC,
5738 const char **ReferenceName) {
5739 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
5740 // If no verbose symbolic information is wanted then just return nullptr.
5741 if (!info->verbose) {
5742 *ReferenceName = nullptr;
5743 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5747 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
5749 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5750 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
5751 if (*ReferenceName != nullptr) {
5752 method_reference(info, ReferenceType, ReferenceName);
5753 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5754 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5757 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5758 if (info->demangled_name != nullptr)
5759 free(info->demangled_name);
5761 info->demangled_name =
5762 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5763 if (info->demangled_name != nullptr) {
5764 *ReferenceName = info->demangled_name;
5765 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5767 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5770 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5771 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5773 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5775 method_reference(info, ReferenceType, ReferenceName);
5777 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5778 // If this is arm64 and the reference is an adrp instruction save the
5779 // instruction, passed in ReferenceValue and the address of the instruction
5780 // for use later if we see and add immediate instruction.
5781 } else if (info->O->getArch() == Triple::aarch64 &&
5782 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5783 info->adrp_inst = ReferenceValue;
5784 info->adrp_addr = ReferencePC;
5785 SymbolName = nullptr;
5786 *ReferenceName = nullptr;
5787 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5788 // If this is arm64 and reference is an add immediate instruction and we
5790 // seen an adrp instruction just before it and the adrp's Xd register
5792 // this add's Xn register reconstruct the value being referenced and look to
5793 // see if it is a literal pointer. Note the add immediate instruction is
5794 // passed in ReferenceValue.
5795 } else if (info->O->getArch() == Triple::aarch64 &&
5796 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5797 ReferencePC - 4 == info->adrp_addr &&
5798 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5799 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5800 uint32_t addxri_inst;
5801 uint64_t adrp_imm, addxri_imm;
5804 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5805 if (info->adrp_inst & 0x0200000)
5806 adrp_imm |= 0xfffffffffc000000LL;
5808 addxri_inst = ReferenceValue;
5809 addxri_imm = (addxri_inst >> 10) & 0xfff;
5810 if (((addxri_inst >> 22) & 0x3) == 1)
5813 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5814 (adrp_imm << 12) + addxri_imm;
5817 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5818 if (*ReferenceName == nullptr)
5819 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5820 // If this is arm64 and the reference is a load register instruction and we
5821 // have seen an adrp instruction just before it and the adrp's Xd register
5822 // matches this add's Xn register reconstruct the value being referenced and
5823 // look to see if it is a literal pointer. Note the load register
5824 // instruction is passed in ReferenceValue.
5825 } else if (info->O->getArch() == Triple::aarch64 &&
5826 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5827 ReferencePC - 4 == info->adrp_addr &&
5828 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5829 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5830 uint32_t ldrxui_inst;
5831 uint64_t adrp_imm, ldrxui_imm;
5834 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5835 if (info->adrp_inst & 0x0200000)
5836 adrp_imm |= 0xfffffffffc000000LL;
5838 ldrxui_inst = ReferenceValue;
5839 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5841 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5842 (adrp_imm << 12) + (ldrxui_imm << 3);
5845 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5846 if (*ReferenceName == nullptr)
5847 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5849 // If this arm64 and is an load register (PC-relative) instruction the
5850 // ReferenceValue is the PC plus the immediate value.
5851 else if (info->O->getArch() == Triple::aarch64 &&
5852 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5853 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5855 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5856 if (*ReferenceName == nullptr)
5857 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5860 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5861 if (info->demangled_name != nullptr)
5862 free(info->demangled_name);
5864 info->demangled_name =
5865 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
5866 if (info->demangled_name != nullptr) {
5867 *ReferenceName = info->demangled_name;
5868 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5873 *ReferenceName = nullptr;
5874 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5880 /// \brief Emits the comments that are stored in the CommentStream.
5881 /// Each comment in the CommentStream must end with a newline.
5882 static void emitComments(raw_svector_ostream &CommentStream,
5883 SmallString<128> &CommentsToEmit,
5884 formatted_raw_ostream &FormattedOS,
5885 const MCAsmInfo &MAI) {
5886 // Flush the stream before taking its content.
5887 CommentStream.flush();
5888 StringRef Comments = CommentsToEmit.str();
5889 // Get the default information for printing a comment.
5890 const char *CommentBegin = MAI.getCommentString();
5891 unsigned CommentColumn = MAI.getCommentColumn();
5892 bool IsFirst = true;
5893 while (!Comments.empty()) {
5895 FormattedOS << '\n';
5896 // Emit a line of comments.
5897 FormattedOS.PadToColumn(CommentColumn);
5898 size_t Position = Comments.find('\n');
5899 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5900 // Move after the newline character.
5901 Comments = Comments.substr(Position + 1);
5904 FormattedOS.flush();
5906 // Tell the comment stream that the vector changed underneath it.
5907 CommentsToEmit.clear();
5908 CommentStream.resync();
5911 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5912 StringRef DisSegName, StringRef DisSectName) {
5913 const char *McpuDefault = nullptr;
5914 const Target *ThumbTarget = nullptr;
5915 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
5917 // GetTarget prints out stuff.
5920 if (MCPU.empty() && McpuDefault)
5923 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
5924 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
5926 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
5928 // Package up features to be passed to target/subtarget
5929 std::string FeaturesStr;
5930 if (MAttrs.size()) {
5931 SubtargetFeatures Features;
5932 for (unsigned i = 0; i != MAttrs.size(); ++i)
5933 Features.AddFeature(MAttrs[i]);
5934 FeaturesStr = Features.getString();
5937 // Set up disassembler.
5938 std::unique_ptr<const MCRegisterInfo> MRI(
5939 TheTarget->createMCRegInfo(TripleName));
5940 std::unique_ptr<const MCAsmInfo> AsmInfo(
5941 TheTarget->createMCAsmInfo(*MRI, TripleName));
5942 std::unique_ptr<const MCSubtargetInfo> STI(
5943 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
5944 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
5945 std::unique_ptr<MCDisassembler> DisAsm(
5946 TheTarget->createMCDisassembler(*STI, Ctx));
5947 std::unique_ptr<MCSymbolizer> Symbolizer;
5948 struct DisassembleInfo SymbolizerInfo;
5949 std::unique_ptr<MCRelocationInfo> RelInfo(
5950 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5952 Symbolizer.reset(TheTarget->createMCSymbolizer(
5953 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
5954 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
5955 DisAsm->setSymbolizer(std::move(Symbolizer));
5957 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
5958 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
5959 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
5960 // Set the display preference for hex vs. decimal immediates.
5961 IP->setPrintImmHex(PrintImmHex);
5962 // Comment stream and backing vector.
5963 SmallString<128> CommentsToEmit;
5964 raw_svector_ostream CommentStream(CommentsToEmit);
5965 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5966 // if it is done then arm64 comments for string literals don't get printed
5967 // and some constant get printed instead and not setting it causes intel
5968 // (32-bit and 64-bit) comments printed with different spacing before the
5969 // comment causing different diffs with the 'C' disassembler library API.
5970 // IP->setCommentStream(CommentStream);
5972 if (!AsmInfo || !STI || !DisAsm || !IP) {
5973 errs() << "error: couldn't initialize disassembler for target "
5974 << TripleName << '\n';
5978 // Set up thumb disassembler.
5979 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5980 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5981 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
5982 std::unique_ptr<MCDisassembler> ThumbDisAsm;
5983 std::unique_ptr<MCInstPrinter> ThumbIP;
5984 std::unique_ptr<MCContext> ThumbCtx;
5985 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5986 struct DisassembleInfo ThumbSymbolizerInfo;
5987 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
5989 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
5991 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
5993 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
5994 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
5995 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
5996 MCContext *PtrThumbCtx = ThumbCtx.get();
5998 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6000 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6001 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
6002 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
6003 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6005 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6006 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
6007 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6008 *ThumbInstrInfo, *ThumbMRI));
6009 // Set the display preference for hex vs. decimal immediates.
6010 ThumbIP->setPrintImmHex(PrintImmHex);
6013 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
6014 errs() << "error: couldn't initialize disassembler for target "
6015 << ThumbTripleName << '\n';
6019 MachO::mach_header Header = MachOOF->getHeader();
6021 // FIXME: Using the -cfg command line option, this code used to be able to
6022 // annotate relocations with the referenced symbol's name, and if this was
6023 // inside a __[cf]string section, the data it points to. This is now replaced
6024 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
6025 std::vector<SectionRef> Sections;
6026 std::vector<SymbolRef> Symbols;
6027 SmallVector<uint64_t, 8> FoundFns;
6028 uint64_t BaseSegmentAddress;
6030 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
6031 BaseSegmentAddress);
6033 // Sort the symbols by address, just in case they didn't come in that way.
6034 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
6036 // Build a data in code table that is sorted on by the address of each entry.
6037 uint64_t BaseAddress = 0;
6038 if (Header.filetype == MachO::MH_OBJECT)
6039 BaseAddress = Sections[0].getAddress();
6041 BaseAddress = BaseSegmentAddress;
6043 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
6046 DI->getOffset(Offset);
6047 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6049 array_pod_sort(Dices.begin(), Dices.end());
6052 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6054 raw_ostream &DebugOut = nulls();
6057 std::unique_ptr<DIContext> diContext;
6058 ObjectFile *DbgObj = MachOOF;
6059 // Try to find debug info and set up the DIContext for it.
6061 // A separate DSym file path was specified, parse it as a macho file,
6062 // get the sections and supply it to the section name parsing machinery.
6063 if (!DSYMFile.empty()) {
6064 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
6065 MemoryBuffer::getFileOrSTDIN(DSYMFile);
6066 if (std::error_code EC = BufOrErr.getError()) {
6067 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
6071 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6076 // Setup the DIContext
6077 diContext.reset(new DWARFContextInMemory(*DbgObj));
6080 if (DumpSections.size() == 0)
6081 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
6083 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
6085 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6088 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
6090 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
6091 if (SegmentName != DisSegName)
6095 Sections[SectIdx].getContents(BytesStr);
6096 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6098 uint64_t SectAddress = Sections[SectIdx].getAddress();
6100 bool symbolTableWorked = false;
6102 // Parse relocations.
6103 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
6104 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
6105 uint64_t RelocOffset = Reloc.getOffset();
6106 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6107 RelocOffset -= SectionAddress;
6109 symbol_iterator RelocSym = Reloc.getSymbol();
6111 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
6113 array_pod_sort(Relocs.begin(), Relocs.end());
6115 // Create a map of symbol addresses to symbol names for use by
6116 // the SymbolizerSymbolLookUp() routine.
6117 SymbolAddressMap AddrMap;
6118 bool DisSymNameFound = false;
6119 for (const SymbolRef &Symbol : MachOOF->symbols()) {
6120 SymbolRef::Type ST = Symbol.getType();
6121 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6122 ST == SymbolRef::ST_Other) {
6123 uint64_t Address = Symbol.getValue();
6124 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6125 if (std::error_code EC = SymNameOrErr.getError())
6126 report_fatal_error(EC.message());
6127 StringRef SymName = *SymNameOrErr;
6128 AddrMap[Address] = SymName;
6129 if (!DisSymName.empty() && DisSymName == SymName)
6130 DisSymNameFound = true;
6133 if (!DisSymName.empty() && !DisSymNameFound) {
6134 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6137 // Set up the block of info used by the Symbolizer call backs.
6138 SymbolizerInfo.verbose = !NoSymbolicOperands;
6139 SymbolizerInfo.O = MachOOF;
6140 SymbolizerInfo.S = Sections[SectIdx];
6141 SymbolizerInfo.AddrMap = &AddrMap;
6142 SymbolizerInfo.Sections = &Sections;
6143 SymbolizerInfo.class_name = nullptr;
6144 SymbolizerInfo.selector_name = nullptr;
6145 SymbolizerInfo.method = nullptr;
6146 SymbolizerInfo.demangled_name = nullptr;
6147 SymbolizerInfo.bindtable = nullptr;
6148 SymbolizerInfo.adrp_addr = 0;
6149 SymbolizerInfo.adrp_inst = 0;
6150 // Same for the ThumbSymbolizer
6151 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
6152 ThumbSymbolizerInfo.O = MachOOF;
6153 ThumbSymbolizerInfo.S = Sections[SectIdx];
6154 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6155 ThumbSymbolizerInfo.Sections = &Sections;
6156 ThumbSymbolizerInfo.class_name = nullptr;
6157 ThumbSymbolizerInfo.selector_name = nullptr;
6158 ThumbSymbolizerInfo.method = nullptr;
6159 ThumbSymbolizerInfo.demangled_name = nullptr;
6160 ThumbSymbolizerInfo.bindtable = nullptr;
6161 ThumbSymbolizerInfo.adrp_addr = 0;
6162 ThumbSymbolizerInfo.adrp_inst = 0;
6164 // Disassemble symbol by symbol.
6165 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
6166 ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6167 if (std::error_code EC = SymNameOrErr.getError())
6168 report_fatal_error(EC.message());
6169 StringRef SymName = *SymNameOrErr;
6171 SymbolRef::Type ST = Symbols[SymIdx].getType();
6172 if (ST != SymbolRef::ST_Function)
6175 // Make sure the symbol is defined in this section.
6176 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
6180 // If we are only disassembling one symbol see if this is that symbol.
6181 if (!DisSymName.empty() && DisSymName != SymName)
6184 // Start at the address of the symbol relative to the section's address.
6185 uint64_t Start = Symbols[SymIdx].getValue();
6186 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6187 Start -= SectionAddress;
6189 // Stop disassembling either at the beginning of the next symbol or at
6190 // the end of the section.
6191 bool containsNextSym = false;
6192 uint64_t NextSym = 0;
6193 uint64_t NextSymIdx = SymIdx + 1;
6194 while (Symbols.size() > NextSymIdx) {
6195 SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
6196 if (NextSymType == SymbolRef::ST_Function) {
6198 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
6199 NextSym = Symbols[NextSymIdx].getValue();
6200 NextSym -= SectionAddress;
6206 uint64_t SectSize = Sections[SectIdx].getSize();
6207 uint64_t End = containsNextSym ? NextSym : SectSize;
6210 symbolTableWorked = true;
6212 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6214 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6216 outs() << SymName << ":\n";
6217 DILineInfo lastLine;
6218 for (uint64_t Index = Start; Index < End; Index += Size) {
6221 uint64_t PC = SectAddress + Index;
6222 if (!NoLeadingAddr) {
6223 if (FullLeadingAddr) {
6224 if (MachOOF->is64Bit())
6225 outs() << format("%016" PRIx64, PC);
6227 outs() << format("%08" PRIx64, PC);
6229 outs() << format("%8" PRIx64 ":", PC);
6235 // Check the data in code table here to see if this is data not an
6236 // instruction to be disassembled.
6238 Dice.push_back(std::make_pair(PC, DiceRef()));
6239 dice_table_iterator DTI =
6240 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6241 compareDiceTableEntries);
6242 if (DTI != Dices.end()) {
6244 DTI->second.getLength(Length);
6246 DTI->second.getKind(Kind);
6247 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
6248 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6249 (PC == (DTI->first + Length - 1)) && (Length & 1))
6254 SmallVector<char, 64> AnnotationsBytes;
6255 raw_svector_ostream Annotations(AnnotationsBytes);
6259 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
6260 PC, DebugOut, Annotations);
6262 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
6263 DebugOut, Annotations);
6265 if (!NoShowRawInsn) {
6266 dumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, Size), outs());
6268 formatted_raw_ostream FormattedOS(outs());
6269 Annotations.flush();
6270 StringRef AnnotationsStr = Annotations.str();
6272 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
6274 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
6275 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
6277 // Print debug info.
6279 DILineInfo dli = diContext->getLineInfoForAddress(PC);
6280 // Print valid line info if it changed.
6281 if (dli != lastLine && dli.Line != 0)
6282 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6288 unsigned int Arch = MachOOF->getArch();
6289 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6290 outs() << format("\t.byte 0x%02x #bad opcode\n",
6291 *(Bytes.data() + Index) & 0xff);
6292 Size = 1; // skip exactly one illegible byte and move on.
6293 } else if (Arch == Triple::aarch64) {
6294 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6295 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6296 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6297 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6298 outs() << format("\t.long\t0x%08x\n", opcode);
6301 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6303 Size = 1; // skip illegible bytes
6308 if (!symbolTableWorked) {
6309 // Reading the symbol table didn't work, disassemble the whole section.
6310 uint64_t SectAddress = Sections[SectIdx].getAddress();
6311 uint64_t SectSize = Sections[SectIdx].getSize();
6313 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
6316 uint64_t PC = SectAddress + Index;
6317 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6318 DebugOut, nulls())) {
6319 if (!NoLeadingAddr) {
6320 if (FullLeadingAddr) {
6321 if (MachOOF->is64Bit())
6322 outs() << format("%016" PRIx64, PC);
6324 outs() << format("%08" PRIx64, PC);
6326 outs() << format("%8" PRIx64 ":", PC);
6329 if (!NoShowRawInsn) {
6331 dumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, InstSize), outs());
6333 IP->printInst(&Inst, outs(), "", *STI);
6336 unsigned int Arch = MachOOF->getArch();
6337 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6338 outs() << format("\t.byte 0x%02x #bad opcode\n",
6339 *(Bytes.data() + Index) & 0xff);
6340 InstSize = 1; // skip exactly one illegible byte and move on.
6342 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6344 InstSize = 1; // skip illegible bytes
6349 // The TripleName's need to be reset if we are called again for a different
6352 ThumbTripleName = "";
6354 if (SymbolizerInfo.method != nullptr)
6355 free(SymbolizerInfo.method);
6356 if (SymbolizerInfo.demangled_name != nullptr)
6357 free(SymbolizerInfo.demangled_name);
6358 if (SymbolizerInfo.bindtable != nullptr)
6359 delete SymbolizerInfo.bindtable;
6360 if (ThumbSymbolizerInfo.method != nullptr)
6361 free(ThumbSymbolizerInfo.method);
6362 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6363 free(ThumbSymbolizerInfo.demangled_name);
6364 if (ThumbSymbolizerInfo.bindtable != nullptr)
6365 delete ThumbSymbolizerInfo.bindtable;
6369 //===----------------------------------------------------------------------===//
6370 // __compact_unwind section dumping
6371 //===----------------------------------------------------------------------===//
6375 template <typename T> static uint64_t readNext(const char *&Buf) {
6376 using llvm::support::little;
6377 using llvm::support::unaligned;
6379 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6384 struct CompactUnwindEntry {
6385 uint32_t OffsetInSection;
6387 uint64_t FunctionAddr;
6389 uint32_t CompactEncoding;
6390 uint64_t PersonalityAddr;
6393 RelocationRef FunctionReloc;
6394 RelocationRef PersonalityReloc;
6395 RelocationRef LSDAReloc;
6397 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
6398 : OffsetInSection(Offset) {
6400 read<uint64_t>(Contents.data() + Offset);
6402 read<uint32_t>(Contents.data() + Offset);
6406 template <typename UIntPtr> void read(const char *Buf) {
6407 FunctionAddr = readNext<UIntPtr>(Buf);
6408 Length = readNext<uint32_t>(Buf);
6409 CompactEncoding = readNext<uint32_t>(Buf);
6410 PersonalityAddr = readNext<UIntPtr>(Buf);
6411 LSDAAddr = readNext<UIntPtr>(Buf);
6416 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
6417 /// and data being relocated, determine the best base Name and Addend to use for
6418 /// display purposes.
6420 /// 1. An Extern relocation will directly reference a symbol (and the data is
6421 /// then already an addend), so use that.
6422 /// 2. Otherwise the data is an offset in the object file's layout; try to find
6423 // a symbol before it in the same section, and use the offset from there.
6424 /// 3. Finally, if all that fails, fall back to an offset from the start of the
6425 /// referenced section.
6426 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6427 std::map<uint64_t, SymbolRef> &Symbols,
6428 const RelocationRef &Reloc, uint64_t Addr,
6429 StringRef &Name, uint64_t &Addend) {
6430 if (Reloc.getSymbol() != Obj->symbol_end()) {
6431 ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6432 if (std::error_code EC = NameOrErr.getError())
6433 report_fatal_error(EC.message());
6439 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
6440 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
6442 uint64_t SectionAddr = RelocSection.getAddress();
6444 auto Sym = Symbols.upper_bound(Addr);
6445 if (Sym == Symbols.begin()) {
6446 // The first symbol in the object is after this reference, the best we can
6447 // do is section-relative notation.
6448 RelocSection.getName(Name);
6449 Addend = Addr - SectionAddr;
6453 // Go back one so that SymbolAddress <= Addr.
6456 section_iterator SymSection = Obj->section_end();
6457 Sym->second.getSection(SymSection);
6458 if (RelocSection == *SymSection) {
6459 // There's a valid symbol in the same section before this reference.
6460 ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6461 if (std::error_code EC = NameOrErr.getError())
6462 report_fatal_error(EC.message());
6464 Addend = Addr - Sym->first;
6468 // There is a symbol before this reference, but it's in a different
6469 // section. Probably not helpful to mention it, so use the section name.
6470 RelocSection.getName(Name);
6471 Addend = Addr - SectionAddr;
6474 static void printUnwindRelocDest(const MachOObjectFile *Obj,
6475 std::map<uint64_t, SymbolRef> &Symbols,
6476 const RelocationRef &Reloc, uint64_t Addr) {
6480 if (!Reloc.getObject())
6483 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6487 outs() << " + " << format("0x%" PRIx64, Addend);
6491 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6492 std::map<uint64_t, SymbolRef> &Symbols,
6493 const SectionRef &CompactUnwind) {
6495 assert(Obj->isLittleEndian() &&
6496 "There should not be a big-endian .o with __compact_unwind");
6498 bool Is64 = Obj->is64Bit();
6499 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6500 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6503 CompactUnwind.getContents(Contents);
6505 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6507 // First populate the initial raw offsets, encodings and so on from the entry.
6508 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6509 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6510 CompactUnwinds.push_back(Entry);
6513 // Next we need to look at the relocations to find out what objects are
6514 // actually being referred to.
6515 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
6516 uint64_t RelocAddress = Reloc.getOffset();
6518 uint32_t EntryIdx = RelocAddress / EntrySize;
6519 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6520 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6522 if (OffsetInEntry == 0)
6523 Entry.FunctionReloc = Reloc;
6524 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6525 Entry.PersonalityReloc = Reloc;
6526 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6527 Entry.LSDAReloc = Reloc;
6529 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6532 // Finally, we're ready to print the data we've gathered.
6533 outs() << "Contents of __compact_unwind section:\n";
6534 for (auto &Entry : CompactUnwinds) {
6535 outs() << " Entry at offset "
6536 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
6538 // 1. Start of the region this entry applies to.
6539 outs() << " start: " << format("0x%" PRIx64,
6540 Entry.FunctionAddr) << ' ';
6541 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
6544 // 2. Length of the region this entry applies to.
6545 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6547 // 3. The 32-bit compact encoding.
6548 outs() << " compact encoding: "
6549 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
6551 // 4. The personality function, if present.
6552 if (Entry.PersonalityReloc.getObject()) {
6553 outs() << " personality function: "
6554 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
6555 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6556 Entry.PersonalityAddr);
6560 // 5. This entry's language-specific data area.
6561 if (Entry.LSDAReloc.getObject()) {
6562 outs() << " LSDA: " << format("0x%" PRIx64,
6563 Entry.LSDAAddr) << ' ';
6564 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6570 //===----------------------------------------------------------------------===//
6571 // __unwind_info section dumping
6572 //===----------------------------------------------------------------------===//
6574 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6575 const char *Pos = PageStart;
6576 uint32_t Kind = readNext<uint32_t>(Pos);
6578 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6580 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6581 uint16_t NumEntries = readNext<uint16_t>(Pos);
6583 Pos = PageStart + EntriesStart;
6584 for (unsigned i = 0; i < NumEntries; ++i) {
6585 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6586 uint32_t Encoding = readNext<uint32_t>(Pos);
6588 outs() << " [" << i << "]: "
6589 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6591 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
6595 static void printCompressedSecondLevelUnwindPage(
6596 const char *PageStart, uint32_t FunctionBase,
6597 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6598 const char *Pos = PageStart;
6599 uint32_t Kind = readNext<uint32_t>(Pos);
6601 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6603 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6604 uint16_t NumEntries = readNext<uint16_t>(Pos);
6606 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6607 readNext<uint16_t>(Pos);
6608 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6609 PageStart + EncodingsStart);
6611 Pos = PageStart + EntriesStart;
6612 for (unsigned i = 0; i < NumEntries; ++i) {
6613 uint32_t Entry = readNext<uint32_t>(Pos);
6614 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6615 uint32_t EncodingIdx = Entry >> 24;
6618 if (EncodingIdx < CommonEncodings.size())
6619 Encoding = CommonEncodings[EncodingIdx];
6621 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6623 outs() << " [" << i << "]: "
6624 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6626 << "encoding[" << EncodingIdx
6627 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
6631 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6632 std::map<uint64_t, SymbolRef> &Symbols,
6633 const SectionRef &UnwindInfo) {
6635 assert(Obj->isLittleEndian() &&
6636 "There should not be a big-endian .o with __unwind_info");
6638 outs() << "Contents of __unwind_info section:\n";
6641 UnwindInfo.getContents(Contents);
6642 const char *Pos = Contents.data();
6644 //===----------------------------------
6646 //===----------------------------------
6648 uint32_t Version = readNext<uint32_t>(Pos);
6649 outs() << " Version: "
6650 << format("0x%" PRIx32, Version) << '\n';
6651 assert(Version == 1 && "only understand version 1");
6653 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6654 outs() << " Common encodings array section offset: "
6655 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6656 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6657 outs() << " Number of common encodings in array: "
6658 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6660 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6661 outs() << " Personality function array section offset: "
6662 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6663 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6664 outs() << " Number of personality functions in array: "
6665 << format("0x%" PRIx32, NumPersonalities) << '\n';
6667 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6668 outs() << " Index array section offset: "
6669 << format("0x%" PRIx32, IndicesStart) << '\n';
6670 uint32_t NumIndices = readNext<uint32_t>(Pos);
6671 outs() << " Number of indices in array: "
6672 << format("0x%" PRIx32, NumIndices) << '\n';
6674 //===----------------------------------
6675 // A shared list of common encodings
6676 //===----------------------------------
6678 // These occupy indices in the range [0, N] whenever an encoding is referenced
6679 // from a compressed 2nd level index table. In practice the linker only
6680 // creates ~128 of these, so that indices are available to embed encodings in
6681 // the 2nd level index.
6683 SmallVector<uint32_t, 64> CommonEncodings;
6684 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6685 Pos = Contents.data() + CommonEncodingsStart;
6686 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6687 uint32_t Encoding = readNext<uint32_t>(Pos);
6688 CommonEncodings.push_back(Encoding);
6690 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6694 //===----------------------------------
6695 // Personality functions used in this executable
6696 //===----------------------------------
6698 // There should be only a handful of these (one per source language,
6699 // roughly). Particularly since they only get 2 bits in the compact encoding.
6701 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6702 Pos = Contents.data() + PersonalitiesStart;
6703 for (unsigned i = 0; i < NumPersonalities; ++i) {
6704 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6705 outs() << " personality[" << i + 1
6706 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6709 //===----------------------------------
6710 // The level 1 index entries
6711 //===----------------------------------
6713 // These specify an approximate place to start searching for the more detailed
6714 // information, sorted by PC.
6717 uint32_t FunctionOffset;
6718 uint32_t SecondLevelPageStart;
6722 SmallVector<IndexEntry, 4> IndexEntries;
6724 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6725 Pos = Contents.data() + IndicesStart;
6726 for (unsigned i = 0; i < NumIndices; ++i) {
6729 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6730 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6731 Entry.LSDAStart = readNext<uint32_t>(Pos);
6732 IndexEntries.push_back(Entry);
6734 outs() << " [" << i << "]: "
6735 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6737 << "2nd level page offset="
6738 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
6739 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
6742 //===----------------------------------
6743 // Next come the LSDA tables
6744 //===----------------------------------
6746 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6747 // the first top-level index's LSDAOffset to the last (sentinel).
6749 outs() << " LSDA descriptors:\n";
6750 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6751 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6752 (2 * sizeof(uint32_t));
6753 for (int i = 0; i < NumLSDAs; ++i) {
6754 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6755 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6756 outs() << " [" << i << "]: "
6757 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6759 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
6762 //===----------------------------------
6763 // Finally, the 2nd level indices
6764 //===----------------------------------
6766 // Generally these are 4K in size, and have 2 possible forms:
6767 // + Regular stores up to 511 entries with disparate encodings
6768 // + Compressed stores up to 1021 entries if few enough compact encoding
6770 outs() << " Second level indices:\n";
6771 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6772 // The final sentinel top-level index has no associated 2nd level page
6773 if (IndexEntries[i].SecondLevelPageStart == 0)
6776 outs() << " Second level index[" << i << "]: "
6777 << "offset in section="
6778 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6780 << "base function offset="
6781 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6783 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
6784 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
6786 printRegularSecondLevelUnwindPage(Pos);
6788 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6791 llvm_unreachable("Do not know how to print this kind of 2nd level page");
6795 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6796 std::map<uint64_t, SymbolRef> Symbols;
6797 for (const SymbolRef &SymRef : Obj->symbols()) {
6798 // Discard any undefined or absolute symbols. They're not going to take part
6799 // in the convenience lookup for unwind info and just take up resources.
6800 section_iterator Section = Obj->section_end();
6801 SymRef.getSection(Section);
6802 if (Section == Obj->section_end())
6805 uint64_t Addr = SymRef.getValue();
6806 Symbols.insert(std::make_pair(Addr, SymRef));
6809 for (const SectionRef &Section : Obj->sections()) {
6811 Section.getName(SectName);
6812 if (SectName == "__compact_unwind")
6813 printMachOCompactUnwindSection(Obj, Symbols, Section);
6814 else if (SectName == "__unwind_info")
6815 printMachOUnwindInfoSection(Obj, Symbols, Section);
6816 else if (SectName == "__eh_frame")
6817 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
6821 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6822 uint32_t cpusubtype, uint32_t filetype,
6823 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6825 outs() << "Mach header\n";
6826 outs() << " magic cputype cpusubtype caps filetype ncmds "
6827 "sizeofcmds flags\n";
6829 if (magic == MachO::MH_MAGIC)
6830 outs() << " MH_MAGIC";
6831 else if (magic == MachO::MH_MAGIC_64)
6832 outs() << "MH_MAGIC_64";
6834 outs() << format(" 0x%08" PRIx32, magic);
6836 case MachO::CPU_TYPE_I386:
6838 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6839 case MachO::CPU_SUBTYPE_I386_ALL:
6843 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6847 case MachO::CPU_TYPE_X86_64:
6848 outs() << " X86_64";
6849 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6850 case MachO::CPU_SUBTYPE_X86_64_ALL:
6853 case MachO::CPU_SUBTYPE_X86_64_H:
6854 outs() << " Haswell";
6857 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6861 case MachO::CPU_TYPE_ARM:
6863 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6864 case MachO::CPU_SUBTYPE_ARM_ALL:
6867 case MachO::CPU_SUBTYPE_ARM_V4T:
6870 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6873 case MachO::CPU_SUBTYPE_ARM_XSCALE:
6874 outs() << " XSCALE";
6876 case MachO::CPU_SUBTYPE_ARM_V6:
6879 case MachO::CPU_SUBTYPE_ARM_V6M:
6882 case MachO::CPU_SUBTYPE_ARM_V7:
6885 case MachO::CPU_SUBTYPE_ARM_V7EM:
6888 case MachO::CPU_SUBTYPE_ARM_V7K:
6891 case MachO::CPU_SUBTYPE_ARM_V7M:
6894 case MachO::CPU_SUBTYPE_ARM_V7S:
6898 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6902 case MachO::CPU_TYPE_ARM64:
6904 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6905 case MachO::CPU_SUBTYPE_ARM64_ALL:
6909 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6913 case MachO::CPU_TYPE_POWERPC:
6915 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6916 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6920 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6924 case MachO::CPU_TYPE_POWERPC64:
6926 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6927 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6931 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6936 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
6939 outs() << format(" 0x%02" PRIx32,
6940 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
6943 case MachO::MH_OBJECT:
6944 outs() << " OBJECT";
6946 case MachO::MH_EXECUTE:
6947 outs() << " EXECUTE";
6949 case MachO::MH_FVMLIB:
6950 outs() << " FVMLIB";
6952 case MachO::MH_CORE:
6955 case MachO::MH_PRELOAD:
6956 outs() << " PRELOAD";
6958 case MachO::MH_DYLIB:
6961 case MachO::MH_DYLIB_STUB:
6962 outs() << " DYLIB_STUB";
6964 case MachO::MH_DYLINKER:
6965 outs() << " DYLINKER";
6967 case MachO::MH_BUNDLE:
6968 outs() << " BUNDLE";
6970 case MachO::MH_DSYM:
6973 case MachO::MH_KEXT_BUNDLE:
6974 outs() << " KEXTBUNDLE";
6977 outs() << format(" %10u", filetype);
6980 outs() << format(" %5u", ncmds);
6981 outs() << format(" %10u", sizeofcmds);
6983 if (f & MachO::MH_NOUNDEFS) {
6984 outs() << " NOUNDEFS";
6985 f &= ~MachO::MH_NOUNDEFS;
6987 if (f & MachO::MH_INCRLINK) {
6988 outs() << " INCRLINK";
6989 f &= ~MachO::MH_INCRLINK;
6991 if (f & MachO::MH_DYLDLINK) {
6992 outs() << " DYLDLINK";
6993 f &= ~MachO::MH_DYLDLINK;
6995 if (f & MachO::MH_BINDATLOAD) {
6996 outs() << " BINDATLOAD";
6997 f &= ~MachO::MH_BINDATLOAD;
6999 if (f & MachO::MH_PREBOUND) {
7000 outs() << " PREBOUND";
7001 f &= ~MachO::MH_PREBOUND;
7003 if (f & MachO::MH_SPLIT_SEGS) {
7004 outs() << " SPLIT_SEGS";
7005 f &= ~MachO::MH_SPLIT_SEGS;
7007 if (f & MachO::MH_LAZY_INIT) {
7008 outs() << " LAZY_INIT";
7009 f &= ~MachO::MH_LAZY_INIT;
7011 if (f & MachO::MH_TWOLEVEL) {
7012 outs() << " TWOLEVEL";
7013 f &= ~MachO::MH_TWOLEVEL;
7015 if (f & MachO::MH_FORCE_FLAT) {
7016 outs() << " FORCE_FLAT";
7017 f &= ~MachO::MH_FORCE_FLAT;
7019 if (f & MachO::MH_NOMULTIDEFS) {
7020 outs() << " NOMULTIDEFS";
7021 f &= ~MachO::MH_NOMULTIDEFS;
7023 if (f & MachO::MH_NOFIXPREBINDING) {
7024 outs() << " NOFIXPREBINDING";
7025 f &= ~MachO::MH_NOFIXPREBINDING;
7027 if (f & MachO::MH_PREBINDABLE) {
7028 outs() << " PREBINDABLE";
7029 f &= ~MachO::MH_PREBINDABLE;
7031 if (f & MachO::MH_ALLMODSBOUND) {
7032 outs() << " ALLMODSBOUND";
7033 f &= ~MachO::MH_ALLMODSBOUND;
7035 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7036 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7037 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7039 if (f & MachO::MH_CANONICAL) {
7040 outs() << " CANONICAL";
7041 f &= ~MachO::MH_CANONICAL;
7043 if (f & MachO::MH_WEAK_DEFINES) {
7044 outs() << " WEAK_DEFINES";
7045 f &= ~MachO::MH_WEAK_DEFINES;
7047 if (f & MachO::MH_BINDS_TO_WEAK) {
7048 outs() << " BINDS_TO_WEAK";
7049 f &= ~MachO::MH_BINDS_TO_WEAK;
7051 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7052 outs() << " ALLOW_STACK_EXECUTION";
7053 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7055 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7056 outs() << " DEAD_STRIPPABLE_DYLIB";
7057 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7059 if (f & MachO::MH_PIE) {
7061 f &= ~MachO::MH_PIE;
7063 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7064 outs() << " NO_REEXPORTED_DYLIBS";
7065 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7067 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7068 outs() << " MH_HAS_TLV_DESCRIPTORS";
7069 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7071 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7072 outs() << " MH_NO_HEAP_EXECUTION";
7073 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7075 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7076 outs() << " APP_EXTENSION_SAFE";
7077 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7079 if (f != 0 || flags == 0)
7080 outs() << format(" 0x%08" PRIx32, f);
7082 outs() << format(" 0x%08" PRIx32, magic);
7083 outs() << format(" %7d", cputype);
7084 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7085 outs() << format(" 0x%02" PRIx32,
7086 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7087 outs() << format(" %10u", filetype);
7088 outs() << format(" %5u", ncmds);
7089 outs() << format(" %10u", sizeofcmds);
7090 outs() << format(" 0x%08" PRIx32, flags);
7095 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7096 StringRef SegName, uint64_t vmaddr,
7097 uint64_t vmsize, uint64_t fileoff,
7098 uint64_t filesize, uint32_t maxprot,
7099 uint32_t initprot, uint32_t nsects,
7100 uint32_t flags, uint32_t object_size,
7102 uint64_t expected_cmdsize;
7103 if (cmd == MachO::LC_SEGMENT) {
7104 outs() << " cmd LC_SEGMENT\n";
7105 expected_cmdsize = nsects;
7106 expected_cmdsize *= sizeof(struct MachO::section);
7107 expected_cmdsize += sizeof(struct MachO::segment_command);
7109 outs() << " cmd LC_SEGMENT_64\n";
7110 expected_cmdsize = nsects;
7111 expected_cmdsize *= sizeof(struct MachO::section_64);
7112 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7114 outs() << " cmdsize " << cmdsize;
7115 if (cmdsize != expected_cmdsize)
7116 outs() << " Inconsistent size\n";
7119 outs() << " segname " << SegName << "\n";
7120 if (cmd == MachO::LC_SEGMENT_64) {
7121 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7122 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7124 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7125 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
7127 outs() << " fileoff " << fileoff;
7128 if (fileoff > object_size)
7129 outs() << " (past end of file)\n";
7132 outs() << " filesize " << filesize;
7133 if (fileoff + filesize > object_size)
7134 outs() << " (past end of file)\n";
7139 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7140 MachO::VM_PROT_EXECUTE)) != 0)
7141 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7143 if (maxprot & MachO::VM_PROT_READ)
7144 outs() << " maxprot r";
7146 outs() << " maxprot -";
7147 if (maxprot & MachO::VM_PROT_WRITE)
7151 if (maxprot & MachO::VM_PROT_EXECUTE)
7157 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7158 MachO::VM_PROT_EXECUTE)) != 0)
7159 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7161 if (initprot & MachO::VM_PROT_READ)
7162 outs() << " initprot r";
7164 outs() << " initprot -";
7165 if (initprot & MachO::VM_PROT_WRITE)
7169 if (initprot & MachO::VM_PROT_EXECUTE)
7175 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7176 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7178 outs() << " nsects " << nsects << "\n";
7182 outs() << " (none)\n";
7184 if (flags & MachO::SG_HIGHVM) {
7185 outs() << " HIGHVM";
7186 flags &= ~MachO::SG_HIGHVM;
7188 if (flags & MachO::SG_FVMLIB) {
7189 outs() << " FVMLIB";
7190 flags &= ~MachO::SG_FVMLIB;
7192 if (flags & MachO::SG_NORELOC) {
7193 outs() << " NORELOC";
7194 flags &= ~MachO::SG_NORELOC;
7196 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7197 outs() << " PROTECTED_VERSION_1";
7198 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7201 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7206 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7210 static void PrintSection(const char *sectname, const char *segname,
7211 uint64_t addr, uint64_t size, uint32_t offset,
7212 uint32_t align, uint32_t reloff, uint32_t nreloc,
7213 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7214 uint32_t cmd, const char *sg_segname,
7215 uint32_t filetype, uint32_t object_size,
7217 outs() << "Section\n";
7218 outs() << " sectname " << format("%.16s\n", sectname);
7219 outs() << " segname " << format("%.16s", segname);
7220 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7221 outs() << " (does not match segment)\n";
7224 if (cmd == MachO::LC_SEGMENT_64) {
7225 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7226 outs() << " size " << format("0x%016" PRIx64, size);
7228 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7229 outs() << " size " << format("0x%08" PRIx64, size);
7231 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7232 outs() << " (past end of file)\n";
7235 outs() << " offset " << offset;
7236 if (offset > object_size)
7237 outs() << " (past end of file)\n";
7240 uint32_t align_shifted = 1 << align;
7241 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7242 outs() << " reloff " << reloff;
7243 if (reloff > object_size)
7244 outs() << " (past end of file)\n";
7247 outs() << " nreloc " << nreloc;
7248 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7249 outs() << " (past end of file)\n";
7252 uint32_t section_type = flags & MachO::SECTION_TYPE;
7255 if (section_type == MachO::S_REGULAR)
7256 outs() << " S_REGULAR\n";
7257 else if (section_type == MachO::S_ZEROFILL)
7258 outs() << " S_ZEROFILL\n";
7259 else if (section_type == MachO::S_CSTRING_LITERALS)
7260 outs() << " S_CSTRING_LITERALS\n";
7261 else if (section_type == MachO::S_4BYTE_LITERALS)
7262 outs() << " S_4BYTE_LITERALS\n";
7263 else if (section_type == MachO::S_8BYTE_LITERALS)
7264 outs() << " S_8BYTE_LITERALS\n";
7265 else if (section_type == MachO::S_16BYTE_LITERALS)
7266 outs() << " S_16BYTE_LITERALS\n";
7267 else if (section_type == MachO::S_LITERAL_POINTERS)
7268 outs() << " S_LITERAL_POINTERS\n";
7269 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7270 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7271 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7272 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7273 else if (section_type == MachO::S_SYMBOL_STUBS)
7274 outs() << " S_SYMBOL_STUBS\n";
7275 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7276 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7277 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7278 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7279 else if (section_type == MachO::S_COALESCED)
7280 outs() << " S_COALESCED\n";
7281 else if (section_type == MachO::S_INTERPOSING)
7282 outs() << " S_INTERPOSING\n";
7283 else if (section_type == MachO::S_DTRACE_DOF)
7284 outs() << " S_DTRACE_DOF\n";
7285 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7286 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7287 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7288 outs() << " S_THREAD_LOCAL_REGULAR\n";
7289 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7290 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7291 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7292 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7293 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7294 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7295 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7296 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7298 outs() << format("0x%08" PRIx32, section_type) << "\n";
7299 outs() << "attributes";
7300 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7301 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7302 outs() << " PURE_INSTRUCTIONS";
7303 if (section_attributes & MachO::S_ATTR_NO_TOC)
7304 outs() << " NO_TOC";
7305 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7306 outs() << " STRIP_STATIC_SYMS";
7307 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7308 outs() << " NO_DEAD_STRIP";
7309 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7310 outs() << " LIVE_SUPPORT";
7311 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7312 outs() << " SELF_MODIFYING_CODE";
7313 if (section_attributes & MachO::S_ATTR_DEBUG)
7315 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7316 outs() << " SOME_INSTRUCTIONS";
7317 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7318 outs() << " EXT_RELOC";
7319 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7320 outs() << " LOC_RELOC";
7321 if (section_attributes == 0)
7322 outs() << " (none)";
7325 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7326 outs() << " reserved1 " << reserved1;
7327 if (section_type == MachO::S_SYMBOL_STUBS ||
7328 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7329 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7330 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7331 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7332 outs() << " (index into indirect symbol table)\n";
7335 outs() << " reserved2 " << reserved2;
7336 if (section_type == MachO::S_SYMBOL_STUBS)
7337 outs() << " (size of stubs)\n";
7342 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
7343 uint32_t object_size) {
7344 outs() << " cmd LC_SYMTAB\n";
7345 outs() << " cmdsize " << st.cmdsize;
7346 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7347 outs() << " Incorrect size\n";
7350 outs() << " symoff " << st.symoff;
7351 if (st.symoff > object_size)
7352 outs() << " (past end of file)\n";
7355 outs() << " nsyms " << st.nsyms;
7358 big_size = st.nsyms;
7359 big_size *= sizeof(struct MachO::nlist_64);
7360 big_size += st.symoff;
7361 if (big_size > object_size)
7362 outs() << " (past end of file)\n";
7366 big_size = st.nsyms;
7367 big_size *= sizeof(struct MachO::nlist);
7368 big_size += st.symoff;
7369 if (big_size > object_size)
7370 outs() << " (past end of file)\n";
7374 outs() << " stroff " << st.stroff;
7375 if (st.stroff > object_size)
7376 outs() << " (past end of file)\n";
7379 outs() << " strsize " << st.strsize;
7380 big_size = st.stroff;
7381 big_size += st.strsize;
7382 if (big_size > object_size)
7383 outs() << " (past end of file)\n";
7388 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7389 uint32_t nsyms, uint32_t object_size,
7391 outs() << " cmd LC_DYSYMTAB\n";
7392 outs() << " cmdsize " << dyst.cmdsize;
7393 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7394 outs() << " Incorrect size\n";
7397 outs() << " ilocalsym " << dyst.ilocalsym;
7398 if (dyst.ilocalsym > nsyms)
7399 outs() << " (greater than the number of symbols)\n";
7402 outs() << " nlocalsym " << dyst.nlocalsym;
7404 big_size = dyst.ilocalsym;
7405 big_size += dyst.nlocalsym;
7406 if (big_size > nsyms)
7407 outs() << " (past the end of the symbol table)\n";
7410 outs() << " iextdefsym " << dyst.iextdefsym;
7411 if (dyst.iextdefsym > nsyms)
7412 outs() << " (greater than the number of symbols)\n";
7415 outs() << " nextdefsym " << dyst.nextdefsym;
7416 big_size = dyst.iextdefsym;
7417 big_size += dyst.nextdefsym;
7418 if (big_size > nsyms)
7419 outs() << " (past the end of the symbol table)\n";
7422 outs() << " iundefsym " << dyst.iundefsym;
7423 if (dyst.iundefsym > nsyms)
7424 outs() << " (greater than the number of symbols)\n";
7427 outs() << " nundefsym " << dyst.nundefsym;
7428 big_size = dyst.iundefsym;
7429 big_size += dyst.nundefsym;
7430 if (big_size > nsyms)
7431 outs() << " (past the end of the symbol table)\n";
7434 outs() << " tocoff " << dyst.tocoff;
7435 if (dyst.tocoff > object_size)
7436 outs() << " (past end of file)\n";
7439 outs() << " ntoc " << dyst.ntoc;
7440 big_size = dyst.ntoc;
7441 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7442 big_size += dyst.tocoff;
7443 if (big_size > object_size)
7444 outs() << " (past end of file)\n";
7447 outs() << " modtaboff " << dyst.modtaboff;
7448 if (dyst.modtaboff > object_size)
7449 outs() << " (past end of file)\n";
7452 outs() << " nmodtab " << dyst.nmodtab;
7455 modtabend = dyst.nmodtab;
7456 modtabend *= sizeof(struct MachO::dylib_module_64);
7457 modtabend += dyst.modtaboff;
7459 modtabend = dyst.nmodtab;
7460 modtabend *= sizeof(struct MachO::dylib_module);
7461 modtabend += dyst.modtaboff;
7463 if (modtabend > object_size)
7464 outs() << " (past end of file)\n";
7467 outs() << " extrefsymoff " << dyst.extrefsymoff;
7468 if (dyst.extrefsymoff > object_size)
7469 outs() << " (past end of file)\n";
7472 outs() << " nextrefsyms " << dyst.nextrefsyms;
7473 big_size = dyst.nextrefsyms;
7474 big_size *= sizeof(struct MachO::dylib_reference);
7475 big_size += dyst.extrefsymoff;
7476 if (big_size > object_size)
7477 outs() << " (past end of file)\n";
7480 outs() << " indirectsymoff " << dyst.indirectsymoff;
7481 if (dyst.indirectsymoff > object_size)
7482 outs() << " (past end of file)\n";
7485 outs() << " nindirectsyms " << dyst.nindirectsyms;
7486 big_size = dyst.nindirectsyms;
7487 big_size *= sizeof(uint32_t);
7488 big_size += dyst.indirectsymoff;
7489 if (big_size > object_size)
7490 outs() << " (past end of file)\n";
7493 outs() << " extreloff " << dyst.extreloff;
7494 if (dyst.extreloff > object_size)
7495 outs() << " (past end of file)\n";
7498 outs() << " nextrel " << dyst.nextrel;
7499 big_size = dyst.nextrel;
7500 big_size *= sizeof(struct MachO::relocation_info);
7501 big_size += dyst.extreloff;
7502 if (big_size > object_size)
7503 outs() << " (past end of file)\n";
7506 outs() << " locreloff " << dyst.locreloff;
7507 if (dyst.locreloff > object_size)
7508 outs() << " (past end of file)\n";
7511 outs() << " nlocrel " << dyst.nlocrel;
7512 big_size = dyst.nlocrel;
7513 big_size *= sizeof(struct MachO::relocation_info);
7514 big_size += dyst.locreloff;
7515 if (big_size > object_size)
7516 outs() << " (past end of file)\n";
7521 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7522 uint32_t object_size) {
7523 if (dc.cmd == MachO::LC_DYLD_INFO)
7524 outs() << " cmd LC_DYLD_INFO\n";
7526 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7527 outs() << " cmdsize " << dc.cmdsize;
7528 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7529 outs() << " Incorrect size\n";
7532 outs() << " rebase_off " << dc.rebase_off;
7533 if (dc.rebase_off > object_size)
7534 outs() << " (past end of file)\n";
7537 outs() << " rebase_size " << dc.rebase_size;
7539 big_size = dc.rebase_off;
7540 big_size += dc.rebase_size;
7541 if (big_size > object_size)
7542 outs() << " (past end of file)\n";
7545 outs() << " bind_off " << dc.bind_off;
7546 if (dc.bind_off > object_size)
7547 outs() << " (past end of file)\n";
7550 outs() << " bind_size " << dc.bind_size;
7551 big_size = dc.bind_off;
7552 big_size += dc.bind_size;
7553 if (big_size > object_size)
7554 outs() << " (past end of file)\n";
7557 outs() << " weak_bind_off " << dc.weak_bind_off;
7558 if (dc.weak_bind_off > object_size)
7559 outs() << " (past end of file)\n";
7562 outs() << " weak_bind_size " << dc.weak_bind_size;
7563 big_size = dc.weak_bind_off;
7564 big_size += dc.weak_bind_size;
7565 if (big_size > object_size)
7566 outs() << " (past end of file)\n";
7569 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7570 if (dc.lazy_bind_off > object_size)
7571 outs() << " (past end of file)\n";
7574 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7575 big_size = dc.lazy_bind_off;
7576 big_size += dc.lazy_bind_size;
7577 if (big_size > object_size)
7578 outs() << " (past end of file)\n";
7581 outs() << " export_off " << dc.export_off;
7582 if (dc.export_off > object_size)
7583 outs() << " (past end of file)\n";
7586 outs() << " export_size " << dc.export_size;
7587 big_size = dc.export_off;
7588 big_size += dc.export_size;
7589 if (big_size > object_size)
7590 outs() << " (past end of file)\n";
7595 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7597 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7598 outs() << " cmd LC_ID_DYLINKER\n";
7599 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7600 outs() << " cmd LC_LOAD_DYLINKER\n";
7601 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7602 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7604 outs() << " cmd ?(" << dyld.cmd << ")\n";
7605 outs() << " cmdsize " << dyld.cmdsize;
7606 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7607 outs() << " Incorrect size\n";
7610 if (dyld.name >= dyld.cmdsize)
7611 outs() << " name ?(bad offset " << dyld.name << ")\n";
7613 const char *P = (const char *)(Ptr) + dyld.name;
7614 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7618 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7619 outs() << " cmd LC_UUID\n";
7620 outs() << " cmdsize " << uuid.cmdsize;
7621 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7622 outs() << " Incorrect size\n";
7626 outs() << format("%02" PRIX32, uuid.uuid[0]);
7627 outs() << format("%02" PRIX32, uuid.uuid[1]);
7628 outs() << format("%02" PRIX32, uuid.uuid[2]);
7629 outs() << format("%02" PRIX32, uuid.uuid[3]);
7631 outs() << format("%02" PRIX32, uuid.uuid[4]);
7632 outs() << format("%02" PRIX32, uuid.uuid[5]);
7634 outs() << format("%02" PRIX32, uuid.uuid[6]);
7635 outs() << format("%02" PRIX32, uuid.uuid[7]);
7637 outs() << format("%02" PRIX32, uuid.uuid[8]);
7638 outs() << format("%02" PRIX32, uuid.uuid[9]);
7640 outs() << format("%02" PRIX32, uuid.uuid[10]);
7641 outs() << format("%02" PRIX32, uuid.uuid[11]);
7642 outs() << format("%02" PRIX32, uuid.uuid[12]);
7643 outs() << format("%02" PRIX32, uuid.uuid[13]);
7644 outs() << format("%02" PRIX32, uuid.uuid[14]);
7645 outs() << format("%02" PRIX32, uuid.uuid[15]);
7649 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
7650 outs() << " cmd LC_RPATH\n";
7651 outs() << " cmdsize " << rpath.cmdsize;
7652 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7653 outs() << " Incorrect size\n";
7656 if (rpath.path >= rpath.cmdsize)
7657 outs() << " path ?(bad offset " << rpath.path << ")\n";
7659 const char *P = (const char *)(Ptr) + rpath.path;
7660 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7664 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
7665 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
7666 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
7667 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
7668 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
7670 outs() << " cmd " << vd.cmd << " (?)\n";
7671 outs() << " cmdsize " << vd.cmdsize;
7672 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7673 outs() << " Incorrect size\n";
7676 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
7677 << ((vd.version >> 8) & 0xff);
7678 if ((vd.version & 0xff) != 0)
7679 outs() << "." << (vd.version & 0xff);
7682 outs() << " sdk n/a";
7684 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
7685 << ((vd.sdk >> 8) & 0xff);
7687 if ((vd.sdk & 0xff) != 0)
7688 outs() << "." << (vd.sdk & 0xff);
7692 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7693 outs() << " cmd LC_SOURCE_VERSION\n";
7694 outs() << " cmdsize " << sd.cmdsize;
7695 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7696 outs() << " Incorrect size\n";
7699 uint64_t a = (sd.version >> 40) & 0xffffff;
7700 uint64_t b = (sd.version >> 30) & 0x3ff;
7701 uint64_t c = (sd.version >> 20) & 0x3ff;
7702 uint64_t d = (sd.version >> 10) & 0x3ff;
7703 uint64_t e = sd.version & 0x3ff;
7704 outs() << " version " << a << "." << b;
7706 outs() << "." << c << "." << d << "." << e;
7708 outs() << "." << c << "." << d;
7714 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7715 outs() << " cmd LC_MAIN\n";
7716 outs() << " cmdsize " << ep.cmdsize;
7717 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7718 outs() << " Incorrect size\n";
7721 outs() << " entryoff " << ep.entryoff << "\n";
7722 outs() << " stacksize " << ep.stacksize << "\n";
7725 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7726 uint32_t object_size) {
7727 outs() << " cmd LC_ENCRYPTION_INFO\n";
7728 outs() << " cmdsize " << ec.cmdsize;
7729 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7730 outs() << " Incorrect size\n";
7733 outs() << " cryptoff " << ec.cryptoff;
7734 if (ec.cryptoff > object_size)
7735 outs() << " (past end of file)\n";
7738 outs() << " cryptsize " << ec.cryptsize;
7739 if (ec.cryptsize > object_size)
7740 outs() << " (past end of file)\n";
7743 outs() << " cryptid " << ec.cryptid << "\n";
7746 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
7747 uint32_t object_size) {
7748 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7749 outs() << " cmdsize " << ec.cmdsize;
7750 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7751 outs() << " Incorrect size\n";
7754 outs() << " cryptoff " << ec.cryptoff;
7755 if (ec.cryptoff > object_size)
7756 outs() << " (past end of file)\n";
7759 outs() << " cryptsize " << ec.cryptsize;
7760 if (ec.cryptsize > object_size)
7761 outs() << " (past end of file)\n";
7764 outs() << " cryptid " << ec.cryptid << "\n";
7765 outs() << " pad " << ec.pad << "\n";
7768 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7770 outs() << " cmd LC_LINKER_OPTION\n";
7771 outs() << " cmdsize " << lo.cmdsize;
7772 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7773 outs() << " Incorrect size\n";
7776 outs() << " count " << lo.count << "\n";
7777 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7778 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7781 while (*string == '\0' && left > 0) {
7787 outs() << " string #" << i << " " << format("%.*s\n", left, string);
7788 uint32_t NullPos = StringRef(string, left).find('\0');
7789 uint32_t len = std::min(NullPos, left) + 1;
7795 outs() << " count " << lo.count << " does not match number of strings "
7799 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7801 outs() << " cmd LC_SUB_FRAMEWORK\n";
7802 outs() << " cmdsize " << sub.cmdsize;
7803 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7804 outs() << " Incorrect size\n";
7807 if (sub.umbrella < sub.cmdsize) {
7808 const char *P = Ptr + sub.umbrella;
7809 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7811 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7815 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7817 outs() << " cmd LC_SUB_UMBRELLA\n";
7818 outs() << " cmdsize " << sub.cmdsize;
7819 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7820 outs() << " Incorrect size\n";
7823 if (sub.sub_umbrella < sub.cmdsize) {
7824 const char *P = Ptr + sub.sub_umbrella;
7825 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7827 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7831 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
7833 outs() << " cmd LC_SUB_LIBRARY\n";
7834 outs() << " cmdsize " << sub.cmdsize;
7835 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7836 outs() << " Incorrect size\n";
7839 if (sub.sub_library < sub.cmdsize) {
7840 const char *P = Ptr + sub.sub_library;
7841 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7843 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7847 static void PrintSubClientCommand(MachO::sub_client_command sub,
7849 outs() << " cmd LC_SUB_CLIENT\n";
7850 outs() << " cmdsize " << sub.cmdsize;
7851 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7852 outs() << " Incorrect size\n";
7855 if (sub.client < sub.cmdsize) {
7856 const char *P = Ptr + sub.client;
7857 outs() << " client " << P << " (offset " << sub.client << ")\n";
7859 outs() << " client ?(bad offset " << sub.client << ")\n";
7863 static void PrintRoutinesCommand(MachO::routines_command r) {
7864 outs() << " cmd LC_ROUTINES\n";
7865 outs() << " cmdsize " << r.cmdsize;
7866 if (r.cmdsize != sizeof(struct MachO::routines_command))
7867 outs() << " Incorrect size\n";
7870 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7871 outs() << " init_module " << r.init_module << "\n";
7872 outs() << " reserved1 " << r.reserved1 << "\n";
7873 outs() << " reserved2 " << r.reserved2 << "\n";
7874 outs() << " reserved3 " << r.reserved3 << "\n";
7875 outs() << " reserved4 " << r.reserved4 << "\n";
7876 outs() << " reserved5 " << r.reserved5 << "\n";
7877 outs() << " reserved6 " << r.reserved6 << "\n";
7880 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7881 outs() << " cmd LC_ROUTINES_64\n";
7882 outs() << " cmdsize " << r.cmdsize;
7883 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
7884 outs() << " Incorrect size\n";
7887 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
7888 outs() << " init_module " << r.init_module << "\n";
7889 outs() << " reserved1 " << r.reserved1 << "\n";
7890 outs() << " reserved2 " << r.reserved2 << "\n";
7891 outs() << " reserved3 " << r.reserved3 << "\n";
7892 outs() << " reserved4 " << r.reserved4 << "\n";
7893 outs() << " reserved5 " << r.reserved5 << "\n";
7894 outs() << " reserved6 " << r.reserved6 << "\n";
7897 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
7898 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
7899 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
7900 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
7901 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
7902 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
7903 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
7904 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
7905 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
7906 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
7907 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
7908 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
7909 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
7910 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
7911 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
7912 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
7913 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
7914 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
7915 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
7916 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
7917 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
7918 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
7921 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
7923 outs() << "\t mmst_reg ";
7924 for (f = 0; f < 10; f++)
7925 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
7927 outs() << "\t mmst_rsrv ";
7928 for (f = 0; f < 6; f++)
7929 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
7933 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
7935 outs() << "\t xmm_reg ";
7936 for (f = 0; f < 16; f++)
7937 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
7941 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
7942 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
7943 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
7944 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
7945 outs() << " denorm " << fpu.fpu_fcw.denorm;
7946 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
7947 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
7948 outs() << " undfl " << fpu.fpu_fcw.undfl;
7949 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
7950 outs() << "\t\t pc ";
7951 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
7952 outs() << "FP_PREC_24B ";
7953 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
7954 outs() << "FP_PREC_53B ";
7955 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
7956 outs() << "FP_PREC_64B ";
7958 outs() << fpu.fpu_fcw.pc << " ";
7960 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
7961 outs() << "FP_RND_NEAR ";
7962 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
7963 outs() << "FP_RND_DOWN ";
7964 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
7965 outs() << "FP_RND_UP ";
7966 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
7967 outs() << "FP_CHOP ";
7969 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
7970 outs() << " denorm " << fpu.fpu_fsw.denorm;
7971 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
7972 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
7973 outs() << " undfl " << fpu.fpu_fsw.undfl;
7974 outs() << " precis " << fpu.fpu_fsw.precis;
7975 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
7976 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
7977 outs() << " c0 " << fpu.fpu_fsw.c0;
7978 outs() << " c1 " << fpu.fpu_fsw.c1;
7979 outs() << " c2 " << fpu.fpu_fsw.c2;
7980 outs() << " tos " << fpu.fpu_fsw.tos;
7981 outs() << " c3 " << fpu.fpu_fsw.c3;
7982 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
7983 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
7984 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
7985 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
7986 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
7987 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
7988 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
7989 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
7990 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
7991 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
7992 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
7993 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
7995 outs() << "\t fpu_stmm0:\n";
7996 Print_mmst_reg(fpu.fpu_stmm0);
7997 outs() << "\t fpu_stmm1:\n";
7998 Print_mmst_reg(fpu.fpu_stmm1);
7999 outs() << "\t fpu_stmm2:\n";
8000 Print_mmst_reg(fpu.fpu_stmm2);
8001 outs() << "\t fpu_stmm3:\n";
8002 Print_mmst_reg(fpu.fpu_stmm3);
8003 outs() << "\t fpu_stmm4:\n";
8004 Print_mmst_reg(fpu.fpu_stmm4);
8005 outs() << "\t fpu_stmm5:\n";
8006 Print_mmst_reg(fpu.fpu_stmm5);
8007 outs() << "\t fpu_stmm6:\n";
8008 Print_mmst_reg(fpu.fpu_stmm6);
8009 outs() << "\t fpu_stmm7:\n";
8010 Print_mmst_reg(fpu.fpu_stmm7);
8011 outs() << "\t fpu_xmm0:\n";
8012 Print_xmm_reg(fpu.fpu_xmm0);
8013 outs() << "\t fpu_xmm1:\n";
8014 Print_xmm_reg(fpu.fpu_xmm1);
8015 outs() << "\t fpu_xmm2:\n";
8016 Print_xmm_reg(fpu.fpu_xmm2);
8017 outs() << "\t fpu_xmm3:\n";
8018 Print_xmm_reg(fpu.fpu_xmm3);
8019 outs() << "\t fpu_xmm4:\n";
8020 Print_xmm_reg(fpu.fpu_xmm4);
8021 outs() << "\t fpu_xmm5:\n";
8022 Print_xmm_reg(fpu.fpu_xmm5);
8023 outs() << "\t fpu_xmm6:\n";
8024 Print_xmm_reg(fpu.fpu_xmm6);
8025 outs() << "\t fpu_xmm7:\n";
8026 Print_xmm_reg(fpu.fpu_xmm7);
8027 outs() << "\t fpu_xmm8:\n";
8028 Print_xmm_reg(fpu.fpu_xmm8);
8029 outs() << "\t fpu_xmm9:\n";
8030 Print_xmm_reg(fpu.fpu_xmm9);
8031 outs() << "\t fpu_xmm10:\n";
8032 Print_xmm_reg(fpu.fpu_xmm10);
8033 outs() << "\t fpu_xmm11:\n";
8034 Print_xmm_reg(fpu.fpu_xmm11);
8035 outs() << "\t fpu_xmm12:\n";
8036 Print_xmm_reg(fpu.fpu_xmm12);
8037 outs() << "\t fpu_xmm13:\n";
8038 Print_xmm_reg(fpu.fpu_xmm13);
8039 outs() << "\t fpu_xmm14:\n";
8040 Print_xmm_reg(fpu.fpu_xmm14);
8041 outs() << "\t fpu_xmm15:\n";
8042 Print_xmm_reg(fpu.fpu_xmm15);
8043 outs() << "\t fpu_rsrv4:\n";
8044 for (uint32_t f = 0; f < 6; f++) {
8046 for (uint32_t g = 0; g < 16; g++)
8047 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
8050 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8054 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8055 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8056 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8057 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8060 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8061 bool isLittleEndian, uint32_t cputype) {
8062 if (t.cmd == MachO::LC_THREAD)
8063 outs() << " cmd LC_THREAD\n";
8064 else if (t.cmd == MachO::LC_UNIXTHREAD)
8065 outs() << " cmd LC_UNIXTHREAD\n";
8067 outs() << " cmd " << t.cmd << " (unknown)\n";
8068 outs() << " cmdsize " << t.cmdsize;
8069 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8070 outs() << " Incorrect size\n";
8074 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8075 const char *end = Ptr + t.cmdsize;
8076 uint32_t flavor, count, left;
8077 if (cputype == MachO::CPU_TYPE_X86_64) {
8078 while (begin < end) {
8079 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8080 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8081 begin += sizeof(uint32_t);
8086 if (isLittleEndian != sys::IsLittleEndianHost)
8087 sys::swapByteOrder(flavor);
8088 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8089 memcpy((char *)&count, begin, sizeof(uint32_t));
8090 begin += sizeof(uint32_t);
8095 if (isLittleEndian != sys::IsLittleEndianHost)
8096 sys::swapByteOrder(count);
8097 if (flavor == MachO::x86_THREAD_STATE64) {
8098 outs() << " flavor x86_THREAD_STATE64\n";
8099 if (count == MachO::x86_THREAD_STATE64_COUNT)
8100 outs() << " count x86_THREAD_STATE64_COUNT\n";
8102 outs() << " count " << count
8103 << " (not x86_THREAD_STATE64_COUNT)\n";
8104 MachO::x86_thread_state64_t cpu64;
8106 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8107 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8108 begin += sizeof(MachO::x86_thread_state64_t);
8110 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8111 memcpy(&cpu64, begin, left);
8114 if (isLittleEndian != sys::IsLittleEndianHost)
8116 Print_x86_thread_state64_t(cpu64);
8117 } else if (flavor == MachO::x86_THREAD_STATE) {
8118 outs() << " flavor x86_THREAD_STATE\n";
8119 if (count == MachO::x86_THREAD_STATE_COUNT)
8120 outs() << " count x86_THREAD_STATE_COUNT\n";
8122 outs() << " count " << count
8123 << " (not x86_THREAD_STATE_COUNT)\n";
8124 struct MachO::x86_thread_state_t ts;
8126 if (left >= sizeof(MachO::x86_thread_state_t)) {
8127 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8128 begin += sizeof(MachO::x86_thread_state_t);
8130 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8131 memcpy(&ts, begin, left);
8134 if (isLittleEndian != sys::IsLittleEndianHost)
8136 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8137 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8138 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8139 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8141 outs() << "tsh.count " << ts.tsh.count
8142 << " (not x86_THREAD_STATE64_COUNT\n";
8143 Print_x86_thread_state64_t(ts.uts.ts64);
8145 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8146 << ts.tsh.count << "\n";
8148 } else if (flavor == MachO::x86_FLOAT_STATE) {
8149 outs() << " flavor x86_FLOAT_STATE\n";
8150 if (count == MachO::x86_FLOAT_STATE_COUNT)
8151 outs() << " count x86_FLOAT_STATE_COUNT\n";
8153 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
8154 struct MachO::x86_float_state_t fs;
8156 if (left >= sizeof(MachO::x86_float_state_t)) {
8157 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8158 begin += sizeof(MachO::x86_float_state_t);
8160 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8161 memcpy(&fs, begin, left);
8164 if (isLittleEndian != sys::IsLittleEndianHost)
8166 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8167 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
8168 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
8169 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8171 outs() << "fsh.count " << fs.fsh.count
8172 << " (not x86_FLOAT_STATE64_COUNT\n";
8173 Print_x86_float_state_t(fs.ufs.fs64);
8175 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8176 << fs.fsh.count << "\n";
8178 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8179 outs() << " flavor x86_EXCEPTION_STATE\n";
8180 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8181 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8183 outs() << " count " << count
8184 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8185 struct MachO::x86_exception_state_t es;
8187 if (left >= sizeof(MachO::x86_exception_state_t)) {
8188 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8189 begin += sizeof(MachO::x86_exception_state_t);
8191 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8192 memcpy(&es, begin, left);
8195 if (isLittleEndian != sys::IsLittleEndianHost)
8197 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8198 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
8199 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
8200 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8202 outs() << "\t esh.count " << es.esh.count
8203 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8204 Print_x86_exception_state_t(es.ues.es64);
8206 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8207 << es.esh.count << "\n";
8210 outs() << " flavor " << flavor << " (unknown)\n";
8211 outs() << " count " << count << "\n";
8212 outs() << " state (unknown)\n";
8213 begin += count * sizeof(uint32_t);
8217 while (begin < end) {
8218 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8219 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8220 begin += sizeof(uint32_t);
8225 if (isLittleEndian != sys::IsLittleEndianHost)
8226 sys::swapByteOrder(flavor);
8227 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8228 memcpy((char *)&count, begin, sizeof(uint32_t));
8229 begin += sizeof(uint32_t);
8234 if (isLittleEndian != sys::IsLittleEndianHost)
8235 sys::swapByteOrder(count);
8236 outs() << " flavor " << flavor << "\n";
8237 outs() << " count " << count << "\n";
8238 outs() << " state (Unknown cputype/cpusubtype)\n";
8239 begin += count * sizeof(uint32_t);
8244 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8245 if (dl.cmd == MachO::LC_ID_DYLIB)
8246 outs() << " cmd LC_ID_DYLIB\n";
8247 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8248 outs() << " cmd LC_LOAD_DYLIB\n";
8249 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8250 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8251 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8252 outs() << " cmd LC_REEXPORT_DYLIB\n";
8253 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8254 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8255 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8256 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8258 outs() << " cmd " << dl.cmd << " (unknown)\n";
8259 outs() << " cmdsize " << dl.cmdsize;
8260 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8261 outs() << " Incorrect size\n";
8264 if (dl.dylib.name < dl.cmdsize) {
8265 const char *P = (const char *)(Ptr) + dl.dylib.name;
8266 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8268 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8270 outs() << " time stamp " << dl.dylib.timestamp << " ";
8271 time_t t = dl.dylib.timestamp;
8272 outs() << ctime(&t);
8273 outs() << " current version ";
8274 if (dl.dylib.current_version == 0xffffffff)
8277 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8278 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8279 << (dl.dylib.current_version & 0xff) << "\n";
8280 outs() << "compatibility version ";
8281 if (dl.dylib.compatibility_version == 0xffffffff)
8284 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8285 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8286 << (dl.dylib.compatibility_version & 0xff) << "\n";
8289 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8290 uint32_t object_size) {
8291 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8292 outs() << " cmd LC_FUNCTION_STARTS\n";
8293 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8294 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8295 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8296 outs() << " cmd LC_FUNCTION_STARTS\n";
8297 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8298 outs() << " cmd LC_DATA_IN_CODE\n";
8299 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8300 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8301 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8302 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8304 outs() << " cmd " << ld.cmd << " (?)\n";
8305 outs() << " cmdsize " << ld.cmdsize;
8306 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8307 outs() << " Incorrect size\n";
8310 outs() << " dataoff " << ld.dataoff;
8311 if (ld.dataoff > object_size)
8312 outs() << " (past end of file)\n";
8315 outs() << " datasize " << ld.datasize;
8316 uint64_t big_size = ld.dataoff;
8317 big_size += ld.datasize;
8318 if (big_size > object_size)
8319 outs() << " (past end of file)\n";
8324 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8325 uint32_t cputype, bool verbose) {
8326 StringRef Buf = Obj->getData();
8328 for (const auto &Command : Obj->load_commands()) {
8329 outs() << "Load command " << Index++ << "\n";
8330 if (Command.C.cmd == MachO::LC_SEGMENT) {
8331 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8332 const char *sg_segname = SLC.segname;
8333 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8334 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8335 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8337 for (unsigned j = 0; j < SLC.nsects; j++) {
8338 MachO::section S = Obj->getSection(Command, j);
8339 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8340 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8341 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8343 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8344 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8345 const char *sg_segname = SLC_64.segname;
8346 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8347 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8348 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8349 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8350 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8351 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8352 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8353 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8354 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8355 sg_segname, filetype, Buf.size(), verbose);
8357 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8358 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8359 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
8360 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8361 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8362 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
8363 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8365 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8366 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8367 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8368 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8369 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8370 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8371 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8372 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8373 PrintDyldLoadCommand(Dyld, Command.Ptr);
8374 } else if (Command.C.cmd == MachO::LC_UUID) {
8375 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8376 PrintUuidLoadCommand(Uuid);
8377 } else if (Command.C.cmd == MachO::LC_RPATH) {
8378 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8379 PrintRpathLoadCommand(Rpath, Command.Ptr);
8380 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
8381 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
8382 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8383 PrintVersionMinLoadCommand(Vd);
8384 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8385 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8386 PrintSourceVersionCommand(Sd);
8387 } else if (Command.C.cmd == MachO::LC_MAIN) {
8388 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8389 PrintEntryPointCommand(Ep);
8390 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
8391 MachO::encryption_info_command Ei =
8392 Obj->getEncryptionInfoCommand(Command);
8393 PrintEncryptionInfoCommand(Ei, Buf.size());
8394 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
8395 MachO::encryption_info_command_64 Ei =
8396 Obj->getEncryptionInfoCommand64(Command);
8397 PrintEncryptionInfoCommand64(Ei, Buf.size());
8398 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
8399 MachO::linker_option_command Lo =
8400 Obj->getLinkerOptionLoadCommand(Command);
8401 PrintLinkerOptionCommand(Lo, Command.Ptr);
8402 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8403 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8404 PrintSubFrameworkCommand(Sf, Command.Ptr);
8405 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8406 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8407 PrintSubUmbrellaCommand(Sf, Command.Ptr);
8408 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8409 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8410 PrintSubLibraryCommand(Sl, Command.Ptr);
8411 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8412 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8413 PrintSubClientCommand(Sc, Command.Ptr);
8414 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8415 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8416 PrintRoutinesCommand(Rc);
8417 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8418 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8419 PrintRoutinesCommand64(Rc);
8420 } else if (Command.C.cmd == MachO::LC_THREAD ||
8421 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8422 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8423 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
8424 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8425 Command.C.cmd == MachO::LC_ID_DYLIB ||
8426 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8427 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8428 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8429 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
8430 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8431 PrintDylibCommand(Dl, Command.Ptr);
8432 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8433 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8434 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8435 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8436 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8437 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8438 MachO::linkedit_data_command Ld =
8439 Obj->getLinkeditDataLoadCommand(Command);
8440 PrintLinkEditDataCommand(Ld, Buf.size());
8442 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8444 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8445 // TODO: get and print the raw bytes of the load command.
8447 // TODO: print all the other kinds of load commands.
8451 static void getAndPrintMachHeader(const MachOObjectFile *Obj,
8452 uint32_t &filetype, uint32_t &cputype,
8454 if (Obj->is64Bit()) {
8455 MachO::mach_header_64 H_64;
8456 H_64 = Obj->getHeader64();
8457 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8458 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8459 filetype = H_64.filetype;
8460 cputype = H_64.cputype;
8462 MachO::mach_header H;
8463 H = Obj->getHeader();
8464 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8465 H.sizeofcmds, H.flags, verbose);
8466 filetype = H.filetype;
8467 cputype = H.cputype;
8471 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8472 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
8473 uint32_t filetype = 0;
8474 uint32_t cputype = 0;
8475 getAndPrintMachHeader(file, filetype, cputype, !NonVerbose);
8476 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
8479 //===----------------------------------------------------------------------===//
8480 // export trie dumping
8481 //===----------------------------------------------------------------------===//
8483 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
8484 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8485 uint64_t Flags = Entry.flags();
8486 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8487 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8488 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8489 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8490 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8491 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8492 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8494 outs() << "[re-export] ";
8496 outs() << format("0x%08llX ",
8497 Entry.address()); // FIXME:add in base address
8498 outs() << Entry.name();
8499 if (WeakDef || ThreadLocal || Resolver || Abs) {
8500 bool NeedsComma = false;
8503 outs() << "weak_def";
8509 outs() << "per-thread";
8515 outs() << "absolute";
8521 outs() << format("resolver=0x%08llX", Entry.other());
8527 StringRef DylibName = "unknown";
8528 int Ordinal = Entry.other() - 1;
8529 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8530 if (Entry.otherName().empty())
8531 outs() << " (from " << DylibName << ")";
8533 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
8539 //===----------------------------------------------------------------------===//
8540 // rebase table dumping
8541 //===----------------------------------------------------------------------===//
8546 SegInfo(const object::MachOObjectFile *Obj);
8548 StringRef segmentName(uint32_t SegIndex);
8549 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8550 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
8553 struct SectionInfo {
8556 StringRef SectionName;
8557 StringRef SegmentName;
8558 uint64_t OffsetInSegment;
8559 uint64_t SegmentStartAddress;
8560 uint32_t SegmentIndex;
8562 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8563 SmallVector<SectionInfo, 32> Sections;
8567 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8568 // Build table of sections so segIndex/offset pairs can be translated.
8569 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
8570 StringRef CurSegName;
8571 uint64_t CurSegAddress;
8572 for (const SectionRef &Section : Obj->sections()) {
8574 if (error(Section.getName(Info.SectionName)))
8576 Info.Address = Section.getAddress();
8577 Info.Size = Section.getSize();
8579 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8580 if (!Info.SegmentName.equals(CurSegName)) {
8582 CurSegName = Info.SegmentName;
8583 CurSegAddress = Info.Address;
8585 Info.SegmentIndex = CurSegIndex - 1;
8586 Info.OffsetInSegment = Info.Address - CurSegAddress;
8587 Info.SegmentStartAddress = CurSegAddress;
8588 Sections.push_back(Info);
8592 StringRef SegInfo::segmentName(uint32_t SegIndex) {
8593 for (const SectionInfo &SI : Sections) {
8594 if (SI.SegmentIndex == SegIndex)
8595 return SI.SegmentName;
8597 llvm_unreachable("invalid segIndex");
8600 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8601 uint64_t OffsetInSeg) {
8602 for (const SectionInfo &SI : Sections) {
8603 if (SI.SegmentIndex != SegIndex)
8605 if (SI.OffsetInSegment > OffsetInSeg)
8607 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8611 llvm_unreachable("segIndex and offset not in any section");
8614 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8615 return findSection(SegIndex, OffsetInSeg).SectionName;
8618 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8619 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8620 return SI.SegmentStartAddress + OffsetInSeg;
8623 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8624 // Build table of sections so names can used in final output.
8625 SegInfo sectionTable(Obj);
8627 outs() << "segment section address type\n";
8628 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8629 uint32_t SegIndex = Entry.segmentIndex();
8630 uint64_t OffsetInSeg = Entry.segmentOffset();
8631 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8632 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8633 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8635 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
8636 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8637 SegmentName.str().c_str(), SectionName.str().c_str(),
8638 Address, Entry.typeName().str().c_str());
8642 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8643 StringRef DylibName;
8645 case MachO::BIND_SPECIAL_DYLIB_SELF:
8646 return "this-image";
8647 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8648 return "main-executable";
8649 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8650 return "flat-namespace";
8653 std::error_code EC =
8654 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
8656 return "<<bad library ordinal>>";
8660 return "<<unknown special ordinal>>";
8663 //===----------------------------------------------------------------------===//
8664 // bind table dumping
8665 //===----------------------------------------------------------------------===//
8667 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8668 // Build table of sections so names can used in final output.
8669 SegInfo sectionTable(Obj);
8671 outs() << "segment section address type "
8672 "addend dylib symbol\n";
8673 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8674 uint32_t SegIndex = Entry.segmentIndex();
8675 uint64_t OffsetInSeg = Entry.segmentOffset();
8676 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8677 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8678 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8680 // Table lines look like:
8681 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
8683 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
8684 Attr = " (weak_import)";
8685 outs() << left_justify(SegmentName, 8) << " "
8686 << left_justify(SectionName, 18) << " "
8687 << format_hex(Address, 10, true) << " "
8688 << left_justify(Entry.typeName(), 8) << " "
8689 << format_decimal(Entry.addend(), 8) << " "
8690 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8691 << Entry.symbolName() << Attr << "\n";
8695 //===----------------------------------------------------------------------===//
8696 // lazy bind table dumping
8697 //===----------------------------------------------------------------------===//
8699 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8700 // Build table of sections so names can used in final output.
8701 SegInfo sectionTable(Obj);
8703 outs() << "segment section address "
8705 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8706 uint32_t SegIndex = Entry.segmentIndex();
8707 uint64_t OffsetInSeg = Entry.segmentOffset();
8708 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8709 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8710 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8712 // Table lines look like:
8713 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
8714 outs() << left_justify(SegmentName, 8) << " "
8715 << left_justify(SectionName, 18) << " "
8716 << format_hex(Address, 10, true) << " "
8717 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
8718 << Entry.symbolName() << "\n";
8722 //===----------------------------------------------------------------------===//
8723 // weak bind table dumping
8724 //===----------------------------------------------------------------------===//
8726 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8727 // Build table of sections so names can used in final output.
8728 SegInfo sectionTable(Obj);
8730 outs() << "segment section address "
8731 "type addend symbol\n";
8732 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8733 // Strong symbols don't have a location to update.
8734 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
8735 outs() << " strong "
8736 << Entry.symbolName() << "\n";
8739 uint32_t SegIndex = Entry.segmentIndex();
8740 uint64_t OffsetInSeg = Entry.segmentOffset();
8741 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8742 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8743 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8745 // Table lines look like:
8746 // __DATA __data 0x00001000 pointer 0 _foo
8747 outs() << left_justify(SegmentName, 8) << " "
8748 << left_justify(SectionName, 18) << " "
8749 << format_hex(Address, 10, true) << " "
8750 << left_justify(Entry.typeName(), 8) << " "
8751 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8756 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
8757 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8758 // information for that address. If the address is found its binding symbol
8759 // name is returned. If not nullptr is returned.
8760 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8761 struct DisassembleInfo *info) {
8762 if (info->bindtable == nullptr) {
8763 info->bindtable = new (BindTable);
8764 SegInfo sectionTable(info->O);
8765 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8766 uint32_t SegIndex = Entry.segmentIndex();
8767 uint64_t OffsetInSeg = Entry.segmentOffset();
8768 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8769 const char *SymbolName = nullptr;
8770 StringRef name = Entry.symbolName();
8772 SymbolName = name.data();
8773 info->bindtable->push_back(std::make_pair(Address, SymbolName));
8776 for (bind_table_iterator BI = info->bindtable->begin(),
8777 BE = info->bindtable->end();
8779 uint64_t Address = BI->first;
8780 if (ReferenceValue == Address) {
8781 const char *SymbolName = BI->second;